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(flags): edit experiment rules in the rules v2 editor (#113272)

Andersff755e29b3b5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c3ee00799e39..6953316590aa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11288,6 +11288,10 @@ snapshots:
hash: v1.k794b7964.7c1812f3bae81f2ec5f88bdd8981269c9ab1db8de052f62261b6a526078e1db1.lLPRMvHcm3J30ZNs_Uv27aiYvPrYiEkQ9v9jzeGl4Rw
scenes-app-feature-flags--edit-rules-v-2-feature-flag--light:
hash: v1.k794b7964.6d2f9704f59bf6e3d61b811d92c7ecfc3d4a5263096d0e57181c2bce6dc4dc97.RTb3YQ69UQA3cySea7dGUkkZhOnIDrzoqgk7t0HpMXI
+ scenes-app-feature-flags--edit-rules-v-2-feature-flag-with-experiment-rules--dark:
+ hash: v1.k794b7964.d8ab86503937e19dfdaecce1b33a43543301dbc9ea7ec044fa86dc1be4dc78f4.l5piKSXuRQfvFZYzzw-EaBJx3ITJV4JXTiYhSMxmryo
+ scenes-app-feature-flags--edit-rules-v-2-feature-flag-with-experiment-rules--light:
+ hash: v1.k794b7964.6ef70a4f20b39736ec4f22678be78ae849f75361623b492c55736a460f79ac54.TZ9q073SpyMeRfUo-w_opEUXWXwk7oYjJq9D8ixrJMY
scenes-app-feature-flags--feature-flag-load-failed--dark:
hash: v1.k794b7964.78c0cc612dbea90f7040fdc919c91d37255bd3c1a5d149a26a7968e86bcd1649.ZSqbZArI-ot3gRLxJErCln6BkMjyS8my3F7ILlT9qX0
scenes-app-feature-flags--feature-flag-load-failed--light:
@@ -11336,6 +11340,10 @@ snapshots:
hash: v1.k794b7964.2e595e65c1e4494c71c07b2772015cbcaf64fb4120d32192163e26ae95ca5231.fNaTKRMtH9HwMByvOc77CzVjKpmDG-1hStBUXueEMLk
scenes-app-feature-flags--rules-v-2-feature-flag-edit-deep-link--light:
hash: v1.k794b7964.8cbffc977bea22684cf73144ab837a5acabffac33eac687ba2c29e6858ebb3a6.OCNkBGO_Dioqet3YCVFl028n_2oOoNgl2foc1d7VzSk
+ scenes-app-feature-flags--rules-v-2-feature-flag-with-experiment-rules--dark:
+ hash: v1.k794b7964.0c8bc0db31efeffe72e342874f4b2e80f702567638d63aee27e2964facdbde64.nFTGZCL9UCQiUc1f4XqDT8rYoy5W7uhjzi6PAfqj14o
+ scenes-app-feature-flags--rules-v-2-feature-flag-with-experiment-rules--light:
+ hash: v1.k794b7964.d2ae1d0fa3a6b10cc03c475fc223daa39b6c17041e5d1e3c05431663073b5062.ZUyX38oS8pRfFpTHCjYMSIF2Wg3EmitLCUmmE8ikdV0
scenes-app-feature-flags--stale-feature-flag--dark:
hash: v1.k794b7964.a5c6ecebf63f113c10df1a1b54b48141b7763f4d1f19f9223f6e445477b7d7f8.I7PbADnaKTfiWr8aPI3zmO0xG_mPSWRVi29ovh4okrs
scenes-app-feature-flags--stale-feature-flag--light:
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx
index 996ec8d73d01..20f059b1fb7b 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.test.tsx
@@ -7,9 +7,11 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { mockGetEventDefinitions, mockGetPropertyDefinitions } from '~/test/mocks'
+import { FeatureFlagRulesV2DraftExperimentRule } from '~/types'
import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'
import { FeatureFlagRulesV2Editor } from './FeatureFlagRulesV2Editor'
+import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'
jest.mock('lib/components/AutoSizer', () => ({
AutoSizer: ({ renderProp }: { renderProp: (size: { height: number; width: number }) => React.ReactNode }) =>
@@ -50,6 +52,46 @@ const V2_FLAG = {
},
}
+const STRING_EXPERIMENT_FLAG = {
+ ...NEW_FLAG,
+ id: 9,
+ key: 'checkout-layout',
+ version: 5,
+ filters: {
+ version: 2,
+ return_type: 'string',
+ default_value: null,
+ rules: [
+ {
+ id: 'rule-split',
+ rule_type: 'experiment',
+ targeting: { properties: [] },
+ paused: false,
+ rollout_percentage: 50,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ seed: 'split-seed',
+ variants: [
+ { key: 'control', weight: 50, value: 'standard' },
+ { key: 'compact', weight: 50, value: 'compact' },
+ ],
+ holdout: { seed: 'holdout-seed', exclusion_percentage: 5 },
+ },
+ ],
+ },
+}
+
+async function renderEditor(id: number): Promise<void> {
+ const pageLogic = featureFlagLogic({ id })
+ pageLogic.mount()
+ await expectLogic(pageLogic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()
+ render(
+ <Provider>
+ <FeatureFlagRulesV2Editor id={id} />
+ </Provider>
+ )
+}
+
describe('FeatureFlagRulesV2Editor', () => {
beforeEach(async () => {
useMocks({
@@ -57,44 +99,106 @@ describe('FeatureFlagRulesV2Editor', () => {
'/api/projects/:team/event_definitions': mockGetEventDefinitions,
'/api/projects/:team/property_definitions': mockGetPropertyDefinitions,
'/api/projects/:team/feature_flags/7/': V2_FLAG,
- '/api/projects/:team/feature_flags/7/status': { status: 'active', reason: 'mock reason' },
+ '/api/projects/:team/feature_flags/9/': STRING_EXPERIMENT_FLAG,
+ '/api/projects/:team/feature_flags/:id/status': { status: 'active', reason: 'mock reason' },
},
})
initKeaTests()
- const pageLogic = featureFlagLogic({ id: 7 })
- pageLogic.mount()
- await expectLogic(pageLogic).toDispatchActions(['loadFeatureFlagSuccess']).toFinishAllListeners()
- render(
- <Provider>
- <FeatureFlagRulesV2Editor id={7} />
- </Provider>
- )
})
afterEach(cleanup)
- it('names each text input by its label', () => {
- expect(screen.getByLabelText('Flag key')).toHaveValue('new-checkout')
- expect(screen.getAllByLabelText(/^Description/).map((input) => input.tagName)).toEqual([
- 'TEXTAREA',
- 'INPUT',
- 'INPUT',
- ])
- expect(screen.getByLabelText('Rollout percentage')).toHaveValue('20')
+ describe('a boolean flag', () => {
+ beforeEach(async () => {
+ await renderEditor(7)
+ })
+
+ it('names each text input by its label', () => {
+ expect(screen.getByLabelText('Flag key')).toHaveValue('new-checkout')
+ expect(screen.getAllByLabelText(/^Description/).map((input) => input.tagName)).toEqual([
+ 'TEXTAREA',
+ 'INPUT',
+ 'INPUT',
+ ])
+ expect(screen.getByLabelText('Rollout percentage')).toHaveValue('20')
+ })
+
+ // Moving the card re-inserts it, which drops focus. React's commit then refocuses the button,
+ // because it is still mounted.
+ it('keeps focus on the rule a keyboard user moved down', async () => {
+ const [moveDown] = document.querySelectorAll<HTMLElement>('[data-attr="rules-v2-move-rule-down"]')
+ moveDown.focus()
+ fireEvent.click(moveDown)
+
+ await waitFor(() =>
+ expect(document.querySelector('[data-attr="rules-v2-rule"] input')).toHaveValue('Everyone else')
+ )
+ const focusedRule = document.activeElement?.closest('[data-attr="rules-v2-rule"]')
+ expect(focusedRule).toHaveTextContent('Rule 2')
+ expect(focusedRule?.querySelector('input')).toHaveValue('Beta users')
+ })
})
- // Moving the card re-inserts it, which drops focus. React's commit then refocuses the button,
- // because it is still mounted.
- it('keeps focus on the rule a keyboard user moved down', async () => {
- const [moveDown] = document.querySelectorAll<HTMLElement>('[data-attr="rules-v2-move-rule-down"]')
- moveDown.focus()
- fireEvent.click(moveDown)
-
- await waitFor(() =>
- expect(document.querySelector('[data-attr="rules-v2-rule"] input')).toHaveValue('Everyone else')
- )
- const focusedRule = document.activeElement?.closest('[data-attr="rules-v2-rule"]')
- expect(focusedRule).toHaveTextContent('Rule 2')
- expect(focusedRule?.querySelector('input')).toHaveValue('Beta users')
+ describe('an experiment rule', () => {
+ const experimentRule = (): FeatureFlagRulesV2DraftExperimentRule =>
+ featureFlagRulesV2EditorLogic({ id: 9 }).values.draft.config
+ .rules[0] as FeatureFlagRulesV2DraftExperimentRule
+ const click = (dataAttr: string, index = 0): void => {
+ fireEvent.click(document.querySelectorAll<HTMLElement>(`[data-attr="${dataAttr}"]`)[index])
+ }
+
+ beforeEach(async () => {
+ await renderEditor(9)
+ })
+
+ it('keeps a variant value that differs from its key when the key is renamed', () => {
+ fireEvent.change(screen.getByLabelText('Variant 1 key'), { target: { value: 'baseline' } })
+ expect(screen.getByLabelText('Variant 1 value')).toHaveValue('standard')
+ })
+
+ it('stores a cleared string default as null', () => {
+ fireEvent.change(screen.getByLabelText('Default value'), { target: { value: 'standard' } })
+ expect(featureFlagRulesV2EditorLogic({ id: 9 }).values.draft.config.default_value).toBe('standard')
+ fireEvent.change(screen.getByLabelText('Default value'), { target: { value: '' } })
+ expect(featureFlagRulesV2EditorLogic({ id: 9 }).values.draft.config.default_value).toBeNull()
+ })
+
+ it('labels every variant input and shows no seed', () => {
+ expect(screen.getByLabelText('Variant 1 key')).toHaveValue('control')
+ expect(screen.getByLabelText('Variant 2 value')).toHaveValue('compact')
+ expect(screen.getByLabelText('Variant 2 weight')).toHaveValue('50')
+ expect(screen.getByLabelText('Holdout excludes')).toHaveValue('5')
+ expect(screen.getByLabelText('Rollout percentage')).toHaveValue('50')
+ expect(document.body).not.toHaveTextContent(/split-seed|holdout-seed/)
+ expect(document.body.innerHTML).not.toMatch(/split-seed|holdout-seed/)
+ })
+
+ it('adds, moves and removes variants and distributes their weights', async () => {
+ click('rules-v2-add-variant')
+ fireEvent.change(screen.getByLabelText('Variant 3 key'), { target: { value: 'spacious' } })
+ await waitFor(() => expect(screen.getByLabelText('Variant 3 value')).toHaveValue('spacious'))
+ click('rules-v2-distribute-weights')
+ click('rules-v2-move-variant-up', 2)
+ click('rules-v2-remove-variant', 0)
+
+ expect(experimentRule().variants).toEqual([
+ { key: 'spacious', weight: 33.33, value: 'spacious' },
+ { key: 'compact', weight: 33.33, value: 'compact' },
+ ])
+ expect(experimentRule()).toMatchObject({ seed: 'split-seed', holdout: { seed: 'holdout-seed' } })
+ })
+
+ it('pauses the experiment rule, removes its holdout and adds a new one', async () => {
+ click('rules-v2-experiment-paused')
+ click('rules-v2-experiment-holdout')
+
+ expect(experimentRule()).toMatchObject({ paused: true })
+ expect(experimentRule()).not.toHaveProperty('holdout')
+ expect(screen.queryByLabelText('Holdout excludes')).not.toBeInTheDocument()
+
+ click('rules-v2-experiment-holdout')
+ expect(experimentRule().holdout).toEqual({ exclusion_percentage: 10 })
+ await waitFor(() => expect(screen.getByLabelText('Holdout excludes')).toHaveValue('10'))
+ })
})
})
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx
index 937fdda2bf6d..9d6927310094 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagRulesV2Editor.tsx
@@ -3,38 +3,42 @@ import { router } from 'kea-router'
import { useId } from 'react'
import { IconPlusSmall } from '@posthog/icons'
-import {
- LemonBanner,
- LemonButton,
- LemonInput,
- LemonSegmentedButton,
- LemonSelect,
- LemonTextArea,
-} from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { tagsModel } from '~/models/tagsModel'
+import { RULES_V2_EDITABLE_RETURN_TYPES } from 'products/feature_flags/frontend/featureFlagConfigFormat'
+
import { FeatureFlagLogicProps, slugifyFeatureFlagKey } from './featureFlagLogic'
-import { BOOLEAN_OPTIONS, featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'
+import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'
import { RulesV2RuleEditor } from './RulesV2RuleEditor'
+import { RulesV2ValueInput } from './RulesV2ValueInput'
+
+const RETURN_TYPE_OPTIONS = RULES_V2_EDITABLE_RETURN_TYPES.map((value) => ({
+ value,
+ label: capitalizeFirstLetter(value),
+}))
export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Element {
const logic = featureFlagRulesV2EditorLogic({ id })
const { draft, ruleKeys, featureFlag, saving, saveError, saveDisabledReason, fieldError } = useValues(logic)
- const { setDraft, setConfig, addRule, saveRulesV2Flag, editFeatureFlag } = useActions(logic)
+ const { setDraft, setConfig, setReturnType, addRule, saveRulesV2Flag, editFeatureFlag } = useActions(logic)
const { tags } = useValues(tagsModel)
const { loadTagsIfNeeded } = useActions(tagsModel)
const isNew = id === 'new'
const keyInputId = useId()
const descriptionInputId = useId()
+ const defaultValueInputId = useId()
+ const returnType = draft.config.return_type
const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
return (
@@ -142,25 +146,33 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Ele
/>
</LemonField.Pure>
<div className="flex flex-wrap gap-4">
- <LemonField.Pure label="Return type">
+ <LemonField.Pure label="Return type" error={fieldError('filters.return_type')}>
<LemonSelect
- value={draft.config.return_type}
- options={[{ value: 'boolean', label: 'Boolean' }]}
- disabledReason="Other return types are not available yet."
+ value={returnType}
+ onChange={setReturnType}
+ options={RETURN_TYPE_OPTIONS}
+ disabledReason={
+ isNew ? undefined : 'The return type cannot be changed after the flag is created.'
+ }
+ data-attr="rules-v2-return-type"
/>
</LemonField.Pure>
<LemonField.Pure
label="Default value"
- help="Returned when no rule matches. Null returns no value, so the SDK uses the caller's default."
+ htmlFor={defaultValueInputId}
+ help={
+ returnType === 'boolean'
+ ? "Returned when no rule matches. Null returns no value, so the SDK uses the caller's default."
+ : "Returned when no rule matches. Leave it empty to return no value, so the SDK uses the caller's default."
+ }
error={fieldError('filters.default_value')}
>
- <LemonSegmentedButton
- size="small"
- value={String(draft.config.default_value)}
- onChange={(value) =>
- setConfig({ default_value: value === 'null' ? null : value === 'true' })
- }
- options={[...BOOLEAN_OPTIONS, { value: 'null', label: 'null' }]}
+ <RulesV2ValueInput
+ id={defaultValueInputId}
+ returnType={returnType}
+ value={draft.config.default_value}
+ onChange={(default_value) => setConfig({ default_value })}
+ nullable
data-attr="rules-v2-default-value"
/>
</LemonField.Pure>
@@ -184,6 +196,7 @@ export function FeatureFlagRulesV2Editor({ id }: FeatureFlagLogicProps): JSX.Ele
index={index}
rule={rule}
ruleCount={draft.config.rules.length}
+ returnType={returnType}
/>
))}
<div>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
index c3a74e7e36b8..fd59cab9d00c 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.stories.tsx
@@ -17,6 +17,65 @@ const RULES_V2_FLAG_ID = 1802
const DELETED_FLAG_ID = 1526
const DELETED_COHORT_FLAG_ID = 1803
+const EXPERIMENT_RULE_FIELDS = {
+ rule_type: 'experiment',
+ targeting: { properties: [] },
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+}
+
+// Served on its own route only, so the list stories keep their rows.
+const RULES_V2_EXPERIMENT_FLAG = {
+ ...featureFlags.results.find((flag) => flag.id === RULES_V2_FLAG_ID),
+ id: 1804,
+ key: 'checkout-layout-rules-v2',
+ name: 'Checkout layout, split across three variants',
+ filters: {
+ version: 2,
+ return_type: 'string',
+ default_value: 'standard',
+ rules: [
+ {
+ id: '2b7e9c41-5d3a-4f8e-b6a1-9c0d2e3f4a5b',
+ rule_type: 'targeted_release',
+ description: 'Internal testers',
+ targeting: {
+ properties: [{ key: 'email', type: 'person', value: '@hedgehog.example', operator: 'icontains' }],
+ },
+ value: 'compact',
+ },
+ {
+ ...EXPERIMENT_RULE_FIELDS,
+ id: '7c1f2e3d-4b5a-4c6d-8e9f-0a1b2c3d4e5f',
+ description: 'Layout test',
+ paused: false,
+ rollout_percentage: 50,
+ on_rollout_miss: 'continue',
+ seed: '3e8f1a2b-9c4d-4e5f-a6b7-c8d9e0f1a2b3',
+ variants: [
+ { key: 'control', weight: 33.34, value: 'standard' },
+ { key: 'compact', weight: 33.33, value: 'compact' },
+ { key: 'spacious', weight: 33.33, value: 'spacious' },
+ ],
+ holdout: { seed: '5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d', exclusion_percentage: 5 },
+ },
+ {
+ ...EXPERIMENT_RULE_FIELDS,
+ id: '9d8c7b6a-5f4e-4d3c-9b2a-1f0e9d8c7b6a',
+ description: 'Mobile layout test, paused',
+ paused: true,
+ rollout_percentage: 100,
+ on_rollout_miss: 'return_default',
+ seed: '0f1e2d3c-4b5a-4968-8776-655443322110',
+ variants: [
+ { key: 'control', weight: 50, value: 'standard' },
+ { key: 'stacked', weight: 50, value: 'stacked' },
+ ],
+ },
+ ],
+ },
+}
+
const meta: Meta = {
component: App,
tags: ['ff'],
@@ -62,6 +121,9 @@ const meta: Meta = {
},
],
'/api/projects/:team_id/feature_flags/:flagId/': ({ params }) => {
+ if (Number(params['flagId']) === RULES_V2_EXPERIMENT_FLAG.id) {
+ return [200, RULES_V2_EXPERIMENT_FLAG]
+ }
const flag = featureFlags.results.find((r) => r.id === Number(params['flagId']))
if (flag?.id === DELETED_FLAG_ID) {
return [200, { ...flag, deleted: true, can_edit: true }]
@@ -235,6 +297,19 @@ export const EditRulesV2FeatureFlag: Story = {
},
}
+export const RulesV2FeatureFlagWithExperimentRules: Story = {
+ parameters: {
+ pageUrl: urls.featureFlag(RULES_V2_EXPERIMENT_FLAG.id),
+ },
+}
+
+export const EditRulesV2FeatureFlagWithExperimentRules: Story = {
+ parameters: {
+ pageUrl: `${urls.featureFlag(RULES_V2_EXPERIMENT_FLAG.id)}?edit=true`,
+ featureFlags: [FEATURE_FLAGS.REALTIME_COHORT_FLAG_TARGETING, FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR],
+ },
+}
+
export const StaleFeatureFlagWithAiAssessment: Story = {
parameters: {
pageUrl: urls.featureFlag(STALE_FLAG_ID),
diff --git a/frontend/src/scenes/feature-flags/PercentageInput.tsx b/frontend/src/scenes/feature-flags/PercentageInput.tsx
index 9e0c95d6a1fc..ec33b74cf0f0 100644
--- a/frontend/src/scenes/feature-flags/PercentageInput.tsx
+++ b/frontend/src/scenes/feature-flags/PercentageInput.tsx
@@ -15,6 +15,7 @@ export function PercentageInput({
id?: string
step?: number
className?: string
+ 'aria-label'?: string
'data-attr'?: string
}): JSX.Element {
const [localValue, setLocalValue] = useState(String(value))
@@ -62,6 +63,7 @@ export function PercentageInput({
setLocalValue(String(clamped))
}
}}
+ aria-label={rest['aria-label']}
data-attr={rest['data-attr']}
/>
<span className="LemonInput__suffix">%</span>
diff --git a/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx b/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx
new file mode 100644
index 000000000000..1c049f80b02a
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/RulesV2ExperimentFields.tsx
@@ -0,0 +1,224 @@
+import { useActions, useValues } from 'kea'
+import { useId } from 'react'
+
+import { IconBalance, IconPlusSmall, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSwitch } from '@posthog/lemon-ui'
+
+import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { FeatureFlagRulesV2DraftExperimentRule, FeatureFlagRulesV2ReturnType, FeatureFlagRulesV2Variant } from '~/types'
+
+import { FeatureFlagLogicProps } from './featureFlagLogic'
+import {
+ MAX_VARIANTS,
+ MIN_VARIANTS,
+ NEW_HOLDOUT,
+ moved,
+ newVariant,
+ withEqualWeights,
+ withVariantKey,
+} from './featureFlagRulesV2Draft'
+import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'
+import { PercentageInput } from './PercentageInput'
+import { RulesV2ValueInput } from './RulesV2ValueInput'
+
+interface ExperimentFieldsProps extends FeatureFlagLogicProps {
+ index: number
+ rule: FeatureFlagRulesV2DraftExperimentRule
+}
+
+/** Pause and holdout, which an experiment rule checks before its rollout. Seeds are server-owned and never shown. */
+export function RulesV2PauseAndHoldoutFields({ id, index, rule }: ExperimentFieldsProps): JSX.Element {
+ const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))
+ const { updateRule } = useActions(featureFlagRulesV2EditorLogic({ id }))
+ const path = `filters.rules[${index}]`
+ const holdoutInputId = useId()
+ const { holdout, ...withoutHoldout } = rule
+ const holdoutSeedError = fieldError(`${path}.holdout.seed`)
+
+ return (
+ <div className="flex flex-wrap gap-4">
+ <LemonField.Pure
+ help="Matching persons get the default value while the experiment is paused."
+ error={fieldError(`${path}.paused`)}
+ >
+ <LemonSwitch
+ label="Paused"
+ checked={rule.paused}
+ onChange={(paused) => updateRule(index, { ...rule, paused })}
+ bordered
+ data-attr="rules-v2-experiment-paused"
+ />
+ </LemonField.Pure>
+ <div className="flex flex-col gap-2">
+ <LemonField.Pure
+ help="Held-out persons get the default value and no variant."
+ error={fieldError(`${path}.holdout`) ?? (holdoutSeedError && `Holdout seed: ${holdoutSeedError}`)}
+ >
+ <LemonSwitch
+ label="Hold out persons"
+ checked={!!holdout}
+ // Removing the holdout drops its stored seed; the server keeps it if the holdout is added back before saving.
+ onChange={(on) => updateRule(index, on ? { ...rule, holdout: NEW_HOLDOUT } : withoutHoldout)}
+ bordered
+ data-attr="rules-v2-experiment-holdout"
+ />
+ </LemonField.Pure>
+ {holdout && (
+ <LemonField.Pure
+ label="Holdout excludes"
+ htmlFor={holdoutInputId}
+ className="w-40"
+ error={fieldError(`${path}.holdout.exclusion_percentage`)}
+ >
+ <PercentageInput
+ id={holdoutInputId}
+ value={holdout.exclusion_percentage}
+ onChange={(exclusion_percentage) =>
+ updateRule(index, { ...rule, holdout: { ...holdout, exclusion_percentage } })
+ }
+ data-attr="rules-v2-experiment-holdout-percentage"
+ />
+ </LemonField.Pure>
+ )}
+ </div>
+ </div>
+ )
+}
+
+export function RulesV2VariantsField({
+ id,
+ index,
+ rule,
+ returnType,
+}: ExperimentFieldsProps & { returnType: FeatureFlagRulesV2ReturnType }): JSX.Element {
+ const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))
+ const { updateRule } = useActions(featureFlagRulesV2EditorLogic({ id }))
+ const path = `filters.rules[${index}]`
+ const { variants } = rule
+ const setVariants = (next: FeatureFlagRulesV2Variant[]): void => updateRule(index, { ...rule, variants: next })
+ const setVariant = (variantIndex: number, variant: FeatureFlagRulesV2Variant): void =>
+ setVariants(variants.map((current, i) => (i === variantIndex ? variant : current)))
+ // Shown under the rows rather than as the field's error, which would outline every input in the table.
+ const variantsError = fieldError(`${path}.variants`)
+
+ return (
+ <LemonField.Pure
+ label="Variants"
+ help="Each enrolled person gets one variant, picked by weight. Changing the weights or their order moves some persons to another variant."
+ >
+ <div className="flex flex-col gap-2" data-attr="rules-v2-variants">
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_7rem_6.5rem] gap-2 items-center text-xs font-semibold text-secondary">
+ <span>Key</span>
+ <span>Value</span>
+ <span className="flex items-center gap-1">
+ Weight
+ <LemonButton
+ size="xsmall"
+ icon={<IconBalance />}
+ tooltip="Distribute weights equally"
+ onClick={() => setVariants(withEqualWeights(variants))}
+ data-attr="rules-v2-distribute-weights"
+ />
+ </span>
+ <span />
+ </div>
+ {variants.map((variant, variantIndex) => {
+ const variantPath = `${path}.variants[${variantIndex}]`
+ const label = `Variant ${variantIndex + 1}`
+ return (
+ <div
+ // Rows hold no state of their own; with index keys, focus stays put when a row moves.
+ key={variantIndex}
+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_7rem_6.5rem] gap-2 items-start"
+ data-attr="rules-v2-variant"
+ >
+ <LemonField.Pure error={fieldError(`${variantPath}.key`) ?? fieldError(variantPath)}>
+ <LemonInput
+ aria-label={`${label} key`}
+ value={variant.key}
+ onChange={(key) =>
+ setVariant(variantIndex, withVariantKey(variant, key, returnType))
+ }
+ placeholder="e.g. test"
+ className="ph-ignore-input"
+ autoComplete="off"
+ spellCheck={false}
+ data-attr="rules-v2-variant-key"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure error={fieldError(`${variantPath}.value`)}>
+ <RulesV2ValueInput
+ returnType={returnType}
+ aria-label={`${label} value`}
+ value={variant.value}
+ onChange={(value) => setVariant(variantIndex, { ...variant, value })}
+ data-attr="rules-v2-variant-value"
+ />
+ </LemonField.Pure>
+ <LemonField.Pure error={fieldError(`${variantPath}.weight`)}>
+ <PercentageInput
+ aria-label={`${label} weight`}
+ value={variant.weight}
+ onChange={(weight) => setVariant(variantIndex, { ...variant, weight })}
+ data-attr="rules-v2-variant-weight"
+ />
+ </LemonField.Pure>
+ <div className="flex">
+ <LemonButton
+ icon={<IconArrowUp />}
+ size="small"
+ tooltip="Move up"
+ disabledReason={variantIndex === 0 ? 'This variant is first.' : undefined}
+ onClick={() => setVariants(moved(variants, variantIndex, variantIndex - 1))}
+ data-attr="rules-v2-move-variant-up"
+ />
+ <LemonButton
+ icon={<IconArrowDown />}
+ size="small"
+ tooltip="Move down"
+ disabledReason={
+ variantIndex === variants.length - 1 ? 'This variant is last.' : undefined
+ }
+ onClick={() => setVariants(moved(variants, variantIndex, variantIndex + 1))}
+ data-attr="rules-v2-move-variant-down"
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ status="danger"
+ tooltip="Remove variant"
+ disabledReason={
+ variants.length <= MIN_VARIANTS
+ ? `An experiment needs at least ${MIN_VARIANTS} variants.`
+ : undefined
+ }
+ onClick={() => setVariants(variants.filter((_, i) => i !== variantIndex))}
+ data-attr="rules-v2-remove-variant"
+ />
+ </div>
+ </div>
+ )
+ })}
+ {variantsError && <LemonField.Error error={variantsError} />}
+ <div>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconPlusSmall />}
+ disabledReason={
+ variants.length >= MAX_VARIANTS
+ ? `An experiment has at most ${MAX_VARIANTS} variants.`
+ : undefined
+ }
+ onClick={() => setVariants([...variants, newVariant(returnType, variants.length)])}
+ data-attr="rules-v2-add-variant"
+ >
+ Add variant
+ </LemonButton>
+ </div>
+ </div>
+ </LemonField.Pure>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx
index cfe325fccf9d..50876133b2fd 100644
--- a/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx
+++ b/frontend/src/scenes/feature-flags/RulesV2RuleEditor.tsx
@@ -2,18 +2,21 @@ import { useActions, useValues } from 'kea'
import { useId } from 'react'
import { IconTrash } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'
import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { IconArrowDown, IconArrowUp } from 'lib/lemon-ui/icons'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { FeatureFlagRulesV2DraftRule } from '~/types'
+import { FeatureFlagRulesV2DraftRule, FeatureFlagRulesV2ReturnType } from '~/types'
import { FeatureFlagLogicProps } from './featureFlagLogic'
-import { BOOLEAN_OPTIONS, featureFlagRulesV2EditorLogic, withRuleType } from './featureFlagRulesV2EditorLogic'
+import { withRuleType } from './featureFlagRulesV2Draft'
+import { featureFlagRulesV2EditorLogic } from './featureFlagRulesV2EditorLogic'
import { PercentageInput } from './PercentageInput'
+import { RulesV2PauseAndHoldoutFields, RulesV2VariantsField } from './RulesV2ExperimentFields'
+import { RulesV2ValueInput } from './RulesV2ValueInput'
export function RulesV2RuleEditor({
id,
@@ -21,17 +24,21 @@ export function RulesV2RuleEditor({
rule,
ruleCount,
ruleKey,
+ returnType,
}: FeatureFlagLogicProps & {
index: number
rule: FeatureFlagRulesV2DraftRule
ruleCount: number
ruleKey: number
+ returnType: FeatureFlagRulesV2ReturnType
}): JSX.Element {
const { fieldError } = useValues(featureFlagRulesV2EditorLogic({ id }))
const { updateRule, removeRule, moveRule } = useActions(featureFlagRulesV2EditorLogic({ id }))
const path = `filters.rules[${index}]`
const descriptionInputId = useId()
const rolloutInputId = useId()
+ const valueInputId = useId()
+ const seedError = fieldError(`${path}.seed`)
return (
<div className="rounded border p-3 bg-surface-primary flex flex-col gap-3" data-attr="rules-v2-rule">
@@ -40,10 +47,11 @@ export function RulesV2RuleEditor({
<LemonSelect
size="small"
value={rule.rule_type}
- onChange={(ruleType) => updateRule(index, withRuleType(rule, ruleType))}
+ onChange={(ruleType) => updateRule(index, withRuleType(rule, ruleType, returnType))}
options={[
{ value: 'targeted_release', label: 'Targeted release' },
{ value: 'percentage_rollout', label: 'Percentage rollout' },
+ { value: 'experiment', label: 'Experiment' },
]}
data-attr="rules-v2-rule-type"
/>
@@ -74,6 +82,7 @@ export function RulesV2RuleEditor({
/>
</div>
{fieldError(path) && <LemonBanner type="error">{fieldError(path)}</LemonBanner>}
+ {seedError && <LemonBanner type="error">Assignment seed: {seedError}</LemonBanner>}
<LemonField.Pure
label="Description"
htmlFor={descriptionInputId}
@@ -102,7 +111,8 @@ export function RulesV2RuleEditor({
addText="Add condition"
/>
</LemonField.Pure>
- {rule.rule_type === 'percentage_rollout' && (
+ {rule.rule_type === 'experiment' && <RulesV2PauseAndHoldoutFields id={id} index={index} rule={rule} />}
+ {rule.rule_type !== 'targeted_release' && (
<div className="flex flex-wrap gap-4">
<LemonField.Pure
label="Rollout percentage"
@@ -130,15 +140,19 @@ export function RulesV2RuleEditor({
</LemonField.Pure>
</div>
)}
- <LemonField.Pure label="Value" error={fieldError(`${path}.value`)}>
- <LemonSegmentedButton
- size="small"
- value={String(rule.value)}
- onChange={(value) => updateRule(index, { ...rule, value: value === 'true' })}
- options={BOOLEAN_OPTIONS}
- data-attr="rules-v2-rule-value"
- />
- </LemonField.Pure>
+ {rule.rule_type === 'experiment' ? (
+ <RulesV2VariantsField id={id} index={index} rule={rule} returnType={returnType} />
+ ) : (
+ <LemonField.Pure label="Value" htmlFor={valueInputId} error={fieldError(`${path}.value`)}>
+ <RulesV2ValueInput
+ id={valueInputId}
+ returnType={returnType}
+ value={rule.value}
+ onChange={(value) => updateRule(index, { ...rule, value })}
+ data-attr="rules-v2-rule-value"
+ />
+ </LemonField.Pure>
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx b/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx
new file mode 100644
index 000000000000..aee74fa3abc1
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/RulesV2ValueInput.tsx
@@ -0,0 +1,54 @@
+import { LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import { FeatureFlagRulesV2ReturnType, JsonType } from '~/types'
+
+const BOOLEAN_OPTIONS = [
+ { value: 'true', label: 'true' },
+ { value: 'false', label: 'false' },
+]
+
+/** A value of the flag's return type. A nullable string value is null while its input is empty. */
+export function RulesV2ValueInput({
+ returnType,
+ value,
+ onChange,
+ nullable = false,
+ id,
+ 'aria-label': ariaLabel,
+ 'data-attr': dataAttr,
+}: {
+ returnType: FeatureFlagRulesV2ReturnType
+ value: JsonType | null
+ onChange: (value: JsonType | null) => void
+ nullable?: boolean
+ id?: string
+ 'aria-label'?: string
+ 'data-attr'?: string
+}): JSX.Element {
+ if (returnType === 'string') {
+ return (
+ <LemonInput
+ id={id}
+ aria-label={ariaLabel}
+ value={typeof value === 'string' ? value : ''}
+ onChange={(text) => onChange(nullable && text === '' ? null : text)}
+ placeholder={nullable ? 'Leave empty for null' : undefined}
+ className="ph-ignore-input"
+ autoComplete="off"
+ spellCheck={false}
+ data-attr={dataAttr}
+ />
+ )
+ }
+ // LemonSegmentedButton drops these props, so a labelled group carries them.
+ return (
+ <div role="group" id={id} aria-label={ariaLabel} data-attr={dataAttr}>
+ <LemonSegmentedButton
+ size="small"
+ value={String(value)}
+ onChange={(option) => onChange(option === 'null' ? null : option === 'true')}
+ options={nullable ? [...BOOLEAN_OPTIONS, { value: 'null', label: 'null' }] : BOOLEAN_OPTIONS}
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index 57131a015d94..fb2c7a0d7231 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -5512,41 +5512,41 @@ describe('the editor a flag opens in', () => {
expect(await editorKind(id, editorEnabled, search)).toBe(expected)
})
- // The editor builds its draft from the stored rules and would throw on, or drop, what it cannot represent.
+ const V2_FLAG_URL = `/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`
+ const EXPERIMENT_RULE = {
+ id: 'rule-split',
+ rule_type: 'experiment',
+ targeting: { properties: [] },
+ paused: false,
+ variants: [
+ { key: 'control', weight: 50, value: false },
+ { key: 'test', weight: 50, value: true },
+ ],
+ rollout_percentage: 100,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+ seed: 'stored-seed',
+ }
+
it.each([
['a string return type', { return_type: 'string', default_value: 'control' }],
- ['group assignment', { aggregation_group_type_index: 0 }],
+ ['an experiment rule', { rules: [EXPERIMENT_RULE] }],
[
- 'an experiment rule',
- {
- rules: [
- {
- id: 'rule-experiment',
- rule_type: 'experiment',
- targeting: { properties: [] },
- paused: false,
- variants: [
- { key: 'control', weight: 50, value: false },
- { key: 'test', weight: 50, value: true },
- ],
- rollout_percentage: 100,
- on_rollout_miss: 'continue',
- assignment_algorithm: 'sha1_60_v1',
- assign_by: 'person',
- seed: 'stored-seed',
- },
- ],
- },
+ 'an experiment rule with a holdout',
+ { rules: [{ ...EXPERIMENT_RULE, holdout: { seed: 'holdout-seed', exclusion_percentage: 5 } }] },
],
+ ])('a v2 flag with %s opens the rules v2 editor', async (_label, filters) => {
+ useMocks({ get: { [V2_FLAG_URL]: () => [200, { ...V2_FLAG, filters: { ...V2_FLAG.filters, ...filters } }] } })
+ expect(await editorKind(7, true)).toBe('rules_v2')
+ })
+
+ // The editor would drop, or rewrite on save, what it cannot represent.
+ it.each([
+ ['a number return type', { return_type: 'number', default_value: 1 }],
+ ['group assignment', { aggregation_group_type_index: 0 }],
])('a v2 flag with %s opens no editor, even with the editor on', async (_label, filters) => {
- useMocks({
- get: {
- [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [
- 200,
- { ...V2_FLAG, filters: { ...V2_FLAG.filters, ...filters } },
- ],
- },
- })
+ useMocks({ get: { [V2_FLAG_URL]: () => [200, { ...V2_FLAG, filters: { ...V2_FLAG.filters, ...filters } }] } })
expect(await editorKind(7, true)).toBeNull()
})
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts
new file mode 100644
index 000000000000..98dd3ad75a43
--- /dev/null
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2Draft.ts
@@ -0,0 +1,236 @@
+import {
+ FeatureFlagRulesV2DraftConfig,
+ FeatureFlagRulesV2DraftExperimentRule,
+ FeatureFlagRulesV2DraftHoldout,
+ FeatureFlagRulesV2DraftRule,
+ FeatureFlagRulesV2ReturnType,
+ FeatureFlagRulesV2Variant,
+ JsonType,
+} from '~/types'
+
+import { isRulesV2Value } from 'products/feature_flags/frontend/featureFlagConfigFormat'
+
+export const MIN_VARIANTS = 2
+export const MAX_VARIANTS = 20
+const VARIANT_KEY = /^[a-zA-Z0-9_-]+$/
+// `String` gives the shortest decimal that round-trips the number, so 33.33 passes and 1e-7 does not.
+const AT_MOST_TWO_DECIMALS = /^\d+(\.\d{1,2})?$/
+
+export function moved<T>(items: T[], from: number, to: number): T[] {
+ const result = [...items]
+ result.splice(to, 0, ...result.splice(from, 1))
+ return result
+}
+
+/** The value a new rule starts with. A string has no sensible default, so the user must enter one. */
+export function rulesV2InitialValue(returnType: FeatureFlagRulesV2ReturnType): JsonType {
+ return returnType === 'boolean' ? true : ''
+}
+
+export function rulesV2InitialDefault(returnType: FeatureFlagRulesV2ReturnType): JsonType | null {
+ return returnType === 'boolean' ? false : null
+}
+
+// A boolean experiment rule starts as control false and test true; a string variant serves its own key.
+function initialVariantValue(returnType: FeatureFlagRulesV2ReturnType, key: string, index: number): JsonType {
+ return returnType === 'boolean' ? index > 0 : key
+}
+
+export const NEW_TARGETED_RELEASE_RULE: FeatureFlagRulesV2DraftRule = {
+ rule_type: 'targeted_release',
+ targeting: { properties: [] },
+ value: true,
+}
+
+// The rollout fields a rule gains when it becomes a percentage rollout; the server assigns its seed.
+const NEW_ROLLOUT_FIELDS = {
+ rollout_percentage: 0,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+} as const
+
+const NEW_EXPERIMENT_ROLLOUT_FIELDS = { ...NEW_ROLLOUT_FIELDS, rollout_percentage: 100 } as const
+
+/**
+ * Keeps the rule's identity and shared fields; type-specific fields come and go with the type. A rollout keeps its
+ * percentage and miss behaviour between the two randomized types. The seed is dropped, and the server keeps the
+ * stored one for as long as the rule stays randomized.
+ */
+export function withRuleType(
+ rule: FeatureFlagRulesV2DraftRule,
+ ruleType: FeatureFlagRulesV2DraftRule['rule_type'],
+ returnType: FeatureFlagRulesV2ReturnType
+): FeatureFlagRulesV2DraftRule {
+ if (rule.rule_type === ruleType) {
+ return rule
+ }
+ const { id, targeting, description, metadata } = rule
+ const shared = { id, targeting, description, metadata }
+ const value = rule.rule_type === 'experiment' ? rulesV2InitialValue(returnType) : rule.value
+ const rollout =
+ rule.rule_type === 'targeted_release'
+ ? null
+ : {
+ rollout_percentage: rule.rollout_percentage,
+ on_rollout_miss: rule.on_rollout_miss,
+ assignment_algorithm: rule.assignment_algorithm,
+ assign_by: rule.assign_by,
+ }
+ switch (ruleType) {
+ case 'targeted_release':
+ return { ...shared, rule_type: ruleType, value }
+ case 'percentage_rollout':
+ return { ...shared, rule_type: ruleType, value, ...(rollout ?? NEW_ROLLOUT_FIELDS) }
+ case 'experiment':
+ return {
+ ...shared,
+ rule_type: ruleType,
+ ...(rollout ?? NEW_EXPERIMENT_ROLLOUT_FIELDS),
+ paused: false,
+ variants: ['control', 'test'].map((key, index) => ({
+ key,
+ weight: 50,
+ value: initialVariantValue(returnType, key, index),
+ })),
+ }
+ }
+}
+
+export const NEW_HOLDOUT: FeatureFlagRulesV2DraftHoldout = { exclusion_percentage: 10 }
+
+export function newVariant(returnType: FeatureFlagRulesV2ReturnType, index: number): FeatureFlagRulesV2Variant {
+ return { key: '', weight: 0, value: initialVariantValue(returnType, '', index) }
+}
+
+/** On a string flag, a variant that serves its own key keeps doing so when the key changes. */
+export function withVariantKey(
+ variant: FeatureFlagRulesV2Variant,
+ key: string,
+ returnType: FeatureFlagRulesV2ReturnType
+): FeatureFlagRulesV2Variant {
+ const followsKey = returnType === 'string' && variant.value === variant.key
+ return { ...variant, key, ...(followsKey ? { value: key } : {}) }
+}
+
+/** Equal weights in hundredths; the first variants absorb the remainder, so the total is exactly 100. */
+export function withEqualWeights(variants: FeatureFlagRulesV2Variant[]): FeatureFlagRulesV2Variant[] {
+ const base = Math.floor(10000 / variants.length)
+ const remainder = 10000 - base * variants.length
+ return variants.map((variant, index) => ({ ...variant, weight: (base + (index < remainder ? 1 : 0)) / 100 }))
+}
+
+/**
+ * Resets the default, rule and variant values to the new type's starting values.
+ * A type change only happens before the flag is created.
+ */
+export function withReturnType(
+ config: FeatureFlagRulesV2DraftConfig,
+ returnType: FeatureFlagRulesV2ReturnType
+): FeatureFlagRulesV2DraftConfig {
+ if (config.return_type === returnType) {
+ return config
+ }
+ return {
+ ...config,
+ return_type: returnType,
+ default_value: rulesV2InitialDefault(returnType),
+ rules: config.rules.map((rule) =>
+ rule.rule_type === 'experiment'
+ ? {
+ ...rule,
+ variants: rule.variants.map((variant, index) => ({
+ ...variant,
+ value: initialVariantValue(returnType, variant.key, index),
+ })),
+ }
+ : { ...rule, value: rulesV2InitialValue(returnType) }
+ ),
+ }
+}
+
+function percentageError(value: unknown): string | null {
+ if (typeof value !== 'number' || !(value >= 0 && value <= 100)) {
+ return 'Must be between 0 and 100.'
+ }
+ return AT_MOST_TWO_DECIMALS.test(String(value)) ? null : 'Must have at most two decimal places.'
+}
+
+function valueError(value: unknown, returnType: FeatureFlagRulesV2ReturnType): string | null {
+ if (isRulesV2Value(value, returnType)) {
+ return null
+ }
+ return returnType === 'boolean' ? 'Must be true or false.' : 'Enter a value.'
+}
+
+function variantKeyError(key: string, seen: Set<string>): string | null {
+ if (!key) {
+ return 'Enter a key.'
+ }
+ if (!VARIANT_KEY.test(key)) {
+ return 'Only letters, numbers, hyphens (-) and underscores (_) are allowed.'
+ }
+ return seen.has(key) ? 'Variant keys must be unique.' : null
+}
+
+function experimentErrors(
+ rule: FeatureFlagRulesV2DraftExperimentRule,
+ path: string,
+ returnType: FeatureFlagRulesV2ReturnType,
+ errors: Record<string, string>
+): void {
+ const seen = new Set<string>()
+ let weightsValid = true
+ rule.variants.forEach((variant, index) => {
+ const variantPath = `${path}.variants[${index}]`
+ addError(errors, `${variantPath}.key`, variantKeyError(variant.key, seen))
+ seen.add(variant.key)
+ const weightError = percentageError(variant.weight)
+ weightsValid &&= weightError === null
+ addError(errors, `${variantPath}.weight`, weightError)
+ addError(errors, `${variantPath}.value`, valueError(variant.value, returnType))
+ })
+ // Two decimals each, so a total in hundredths is exact where a float sum is not.
+ const total = rule.variants.reduce((sum, variant) => sum + Math.round(variant.weight * 100), 0)
+ addError(
+ errors,
+ `${path}.variants`,
+ rule.variants.length < MIN_VARIANTS
+ ? `Add at least ${MIN_VARIANTS} variants.`
+ : rule.variants.length > MAX_VARIANTS
+ ? `At most ${MAX_VARIANTS} variants are allowed.`
+ : weightsValid && total !== 10000
+ ? `Variant weights must total 100% (now ${total / 100}%).`
+ : null
+ )
+ if (rule.holdout) {
+ addError(errors, `${path}.holdout.exclusion_percentage`, percentageError(rule.holdout.exclusion_percentage))
+ }
+}
+
+function addError(errors: Record<string, string>, field: string, error: string | null): void {
+ if (error) {
+ errors[field] = error
+ }
+}
+
+/**
+ * What the client can check with certainty before a save, keyed by the path the server reports the same error on.
+ * The server stays the authority: it also checks what is not repeated here, such as reserved values.
+ */
+export function rulesV2DraftErrors(config: FeatureFlagRulesV2DraftConfig): Record<string, string> {
+ const errors: Record<string, string> = {}
+ config.rules.forEach((rule, index) => {
+ const path = `filters.rules[${index}]`
+ if (rule.rule_type !== 'experiment') {
+ addError(errors, `${path}.value`, valueError(rule.value, config.return_type))
+ }
+ if (rule.rule_type !== 'targeted_release') {
+ addError(errors, `${path}.rollout_percentage`, percentageError(rule.rollout_percentage))
+ }
+ if (rule.rule_type === 'experiment') {
+ experimentErrors(rule, path, config.return_type, errors)
+ }
+ })
+ return errors
+}
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
index ec303a61a993..eab55b57cbc3 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.test.ts
@@ -15,16 +15,30 @@ import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
-import { FeatureFlagType, PropertyFilterType, PropertyOperator } from '~/types'
+import {
+ FeatureFlagRulesV2Config,
+ FeatureFlagRulesV2DraftExperimentRule,
+ FeatureFlagRulesV2DraftRule,
+ FeatureFlagType,
+ PropertyFilterType,
+ PropertyOperator,
+} from '~/types'
import { NEW_FLAG, featureFlagLogic } from './featureFlagLogic'
import {
+ NEW_HOLDOUT,
NEW_TARGETED_RELEASE_RULE,
+ moved,
+ newVariant,
+ rulesV2DraftErrors,
+ withEqualWeights,
+ withRuleType,
+} from './featureFlagRulesV2Draft'
+import {
featureFlagRulesV2EditorLogic,
rulesV2DraftFromFlag,
rulesV2SaveError,
rulesV2WriteBody,
- withRuleType,
} from './featureFlagRulesV2EditorLogic'
jest.mock('~/layout/panel-layout/ProjectTree/projectTreeLogic', () => ({
@@ -32,6 +46,47 @@ jest.mock('~/layout/panel-layout/ProjectTree/projectTreeLogic', () => ({
refreshTreeItem: jest.fn(),
}))
+// An experiment rule with fields the editor does not render: they must survive a save unchanged.
+const EXPERIMENT_RULE = {
+ id: 'rule-split',
+ rule_type: 'experiment',
+ description: 'Layout test',
+ targeting: { properties: [] },
+ metadata: { owner: 'growth' },
+ paused: false,
+ rollout_percentage: 50,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+ seed: 'split-seed',
+ variants: [
+ { key: 'control', weight: 33.34, value: 'standard' },
+ { key: 'compact', weight: 33.33, value: 'compact' },
+ { key: 'spacious', weight: 33.33, value: 'spacious' },
+ ],
+ holdout: { seed: 'holdout-seed', exclusion_percentage: 5 },
+ some_future_field: { kept: true },
+}
+
+const STRING_FLAG_RULES = [
+ { id: 'rule-beta', rule_type: 'targeted_release', targeting: { properties: [] }, value: 'compact' },
+ EXPERIMENT_RULE,
+]
+
+const STRING_FLAG = {
+ ...NEW_FLAG,
+ id: 9,
+ key: 'checkout-layout',
+ name: 'Checkout layout',
+ version: 5,
+ filters: {
+ version: 2,
+ return_type: 'string',
+ default_value: null,
+ rules: STRING_FLAG_RULES,
+ },
+} as unknown as FeatureFlagType
+
const V2_FLAG = {
...NEW_FLAG,
id: 7,
@@ -71,6 +126,7 @@ describe('featureFlagRulesV2EditorLogic', () => {
useMocks({
get: {
[`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/7/`]: () => [200, V2_FLAG],
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/9/`]: () => [200, STRING_FLAG],
},
})
initKeaTests()
@@ -82,7 +138,7 @@ describe('featureFlagRulesV2EditorLogic', () => {
})
describe('rules v2 editor documents', () => {
- it('keeps stored rule ids, never holds a seed, and sends new rules without an id', () => {
+ it('echoes stored rule ids and seeds, and sends new rules without either', () => {
const draft = rulesV2DraftFromFlag(V2_FLAG)
const body = rulesV2WriteBody({
...draft,
@@ -90,14 +146,54 @@ describe('featureFlagRulesV2EditorLogic', () => {
})
expect(body.filters.rules.map((rule) => rule.id)).toEqual(['rule-beta', 'rule-rollout', undefined])
- expect(JSON.stringify(body)).not.toContain('seed')
+ expect(body.filters.rules.map((rule) => ('seed' in rule ? rule.seed : null))).toEqual([
+ null,
+ 'stored-seed',
+ null,
+ ])
expect(body).toMatchObject({ key: 'new-checkout', name: 'Checkout redesign', version: 3 })
expect(body.filters).toMatchObject({ version: 2, return_type: 'boolean', default_value: false })
})
+ it('sends a stored experiment rule back unchanged, seeds and unrendered fields included', () => {
+ const draft = rulesV2DraftFromFlag(STRING_FLAG)
+ expect(rulesV2WriteBody(draft).filters).toEqual(STRING_FLAG.filters)
+ })
+
+ it('sends a new experiment rule and a new holdout with only the fields the server accepts', () => {
+ const experimentRule = withRuleType(
+ NEW_TARGETED_RELEASE_RULE,
+ 'experiment',
+ 'boolean'
+ ) as FeatureFlagRulesV2DraftExperimentRule
+ const draft = rulesV2DraftFromFlag(V2_FLAG)
+ const body = rulesV2WriteBody({
+ ...draft,
+ config: { ...draft.config, rules: [{ ...experimentRule, holdout: NEW_HOLDOUT }] },
+ })
+
+ const [sent] = JSON.parse(JSON.stringify(body)).filters.rules
+ expect(Object.keys(sent).sort()).toEqual([
+ 'assign_by',
+ 'assignment_algorithm',
+ 'holdout',
+ 'on_rollout_miss',
+ 'paused',
+ 'rollout_percentage',
+ 'rule_type',
+ 'targeting',
+ 'variants',
+ ])
+ expect(sent.holdout).toEqual({ exclusion_percentage: 10 })
+ expect(sent.variants).toEqual([
+ { key: 'control', weight: 50, value: false },
+ { key: 'test', weight: 50, value: true },
+ ])
+ })
+
it('adds the rollout fields when a rule becomes a percentage rollout and drops them when it stops', () => {
const rule = { ...NEW_TARGETED_RELEASE_RULE, id: 'rule-beta', description: 'Beta users' }
- const rollout = withRuleType(rule, 'percentage_rollout')
+ const rollout = withRuleType(rule, 'percentage_rollout', 'boolean')
expect(rollout).toEqual({
...rule,
rule_type: 'percentage_rollout',
@@ -106,7 +202,107 @@ describe('featureFlagRulesV2EditorLogic', () => {
assignment_algorithm: 'sha1_60_v1',
assign_by: 'person',
})
- expect(withRuleType(rollout, 'targeted_release')).toEqual(rule)
+ expect(withRuleType(rollout, 'targeted_release', 'boolean')).toEqual(rule)
+ })
+
+ it.each([
+ {
+ from: 'a targeted release',
+ rule: {
+ id: 'rule-beta',
+ rule_type: 'targeted_release',
+ targeting: { properties: [] },
+ value: 'compact',
+ },
+ rollout: { rollout_percentage: 100, on_rollout_miss: 'continue' },
+ },
+ {
+ from: 'a percentage rollout',
+ rule: {
+ id: 'rule-rollout',
+ rule_type: 'percentage_rollout',
+ targeting: { properties: [] },
+ value: 'compact',
+ rollout_percentage: 30,
+ on_rollout_miss: 'return_default',
+ assignment_algorithm: 'sha1_60_v1',
+ seed: 'stored-seed',
+ },
+ rollout: { rollout_percentage: 30, on_rollout_miss: 'return_default' },
+ },
+ ] as { from: string; rule: FeatureFlagRulesV2DraftRule; rollout: Record<string, unknown> }[])(
+ 'turns $from into an experiment rule with no client seed',
+ ({ rule, rollout }) => {
+ const experimentRule = withRuleType(
+ rule,
+ 'experiment',
+ 'string'
+ ) as FeatureFlagRulesV2DraftExperimentRule
+ expect(experimentRule).toMatchObject({
+ id: rule.id,
+ rule_type: 'experiment',
+ paused: false,
+ assignment_algorithm: 'sha1_60_v1',
+ ...rollout,
+ variants: [
+ { key: 'control', weight: 50, value: 'control' },
+ { key: 'test', weight: 50, value: 'test' },
+ ],
+ })
+ expect(experimentRule).not.toHaveProperty('value')
+ expect(experimentRule.seed).toBeUndefined()
+ expect(experimentRule.holdout).toBeUndefined()
+ }
+ )
+
+ it('turns an experiment rule into a percentage rollout that keeps its rollout but not its seed', () => {
+ const rollout = withRuleType(
+ EXPERIMENT_RULE as FeatureFlagRulesV2DraftExperimentRule,
+ 'percentage_rollout',
+ 'string'
+ )
+ expect(rollout).toEqual({
+ id: 'rule-split',
+ rule_type: 'percentage_rollout',
+ description: 'Layout test',
+ targeting: { properties: [] },
+ metadata: { owner: 'growth' },
+ value: '',
+ rollout_percentage: 50,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+ })
+ })
+
+ // As floats these add up to 100.00000000000001; the server totals them exactly.
+ it('accepts weights that total exactly 100 in hundredths', () => {
+ const variants = [
+ { key: 'control', weight: 64.04, value: 'standard' },
+ { key: 'compact', weight: 35.95, value: 'compact' },
+ { key: 'spacious', weight: 0.01, value: 'spacious' },
+ ]
+ const config = STRING_FLAG.filters as FeatureFlagRulesV2Config
+ expect(
+ rulesV2DraftErrors({
+ ...config,
+ rules: [{ ...EXPERIMENT_RULE, variants } as FeatureFlagRulesV2DraftRule],
+ })
+ ).toEqual({})
+ })
+
+ it('adds, moves and removes variants, and distributes their weights to exactly 100', () => {
+ const variants = [...EXPERIMENT_RULE.variants, newVariant('string', 3)]
+ expect(variants[3]).toEqual({ key: '', weight: 0, value: '' })
+ expect(moved(variants, 2, 0).map((variant) => variant.key)).toEqual(['spacious', 'control', 'compact', ''])
+ expect(withEqualWeights(variants).map((variant) => variant.weight)).toEqual([25, 25, 25, 25])
+ expect(withEqualWeights(variants.slice(0, 3)).map((variant) => variant.weight)).toEqual([
+ 33.34, 33.33, 33.33,
+ ])
+ expect(withEqualWeights([...variants, ...variants, ...variants]).map((v) => v.weight)).toEqual([
+ ...Array(4).fill(8.34),
+ ...Array(8).fill(8.33),
+ ])
})
it.each([
@@ -130,6 +326,76 @@ describe('featureFlagRulesV2EditorLogic', () => {
'filters.rules[2]',
'filters.rules[2].id: Rule ids are server-assigned.',
],
+ [
+ { attr: 'filters__rules__1__variants__2__weight', detail: 'Must have at most 2 decimal places.' },
+ 'filters.rules[1].variants[2].weight',
+ 'Must have at most 2 decimal places.',
+ ],
+ [
+ { attr: 'filters__rules__1__variants__0__key', detail: 'Variant keys must be unique.' },
+ 'filters.rules[1].variants[0].key',
+ 'Variant keys must be unique.',
+ ],
+ [
+ {
+ attr: 'filters__rules__0__variants__1__value',
+ detail: 'Must be a non-empty string other than $false or $true.',
+ },
+ 'filters.rules[0].variants[1].value',
+ 'Must be a non-empty string other than $false or $true.',
+ ],
+ [
+ {
+ attr: 'filters',
+ code: 'unknown_field',
+ detail: 'filters.rules[0].variants[1].label: Unknown field.',
+ },
+ 'filters.rules[0].variants[1]',
+ 'filters.rules[0].variants[1].label: Unknown field.',
+ ],
+ [
+ { attr: 'filters__rules__0__variants', detail: 'Variant weights must total exactly 100.' },
+ 'filters.rules[0].variants',
+ 'Variant weights must total exactly 100.',
+ ],
+ [
+ { attr: 'filters__rules__3__holdout__exclusion_percentage', detail: 'Must be between 0 and 100.' },
+ 'filters.rules[3].holdout.exclusion_percentage',
+ 'Must be between 0 and 100.',
+ ],
+ [
+ { attr: 'filters', code: 'unknown_field', detail: 'filters.rules[3].holdout.label: Unknown field.' },
+ 'filters.rules[3].holdout',
+ 'filters.rules[3].holdout.label: Unknown field.',
+ ],
+ [
+ { attr: 'filters__rules__3__holdout__seed', detail: 'Assignment seeds are server-assigned.' },
+ 'filters.rules[3].holdout.seed',
+ 'Assignment seeds are server-assigned.',
+ ],
+ [
+ {
+ attr: 'filters__rules__2__seed',
+ detail: 'Cannot be changed; resetting assignment is a separate operation.',
+ },
+ 'filters.rules[2].seed',
+ 'Cannot be changed; resetting assignment is a separate operation.',
+ ],
+ [
+ { attr: 'filters__rules__2__paused', detail: 'Must be true or false.' },
+ 'filters.rules[2].paused',
+ 'Must be true or false.',
+ ],
+ [
+ { attr: 'filters__return_type', detail: 'Cannot be changed after the flag is created.' },
+ 'filters.return_type',
+ 'Cannot be changed after the flag is created.',
+ ],
+ [
+ { attr: 'filters', code: 'unsupported', detail: 'This flag cannot be updated through this API.' },
+ null,
+ 'This flag cannot be updated through this API.',
+ ],
[
{ attr: 'filters__default_value', detail: 'Must be true or false.' },
'filters.default_value',
@@ -195,6 +461,52 @@ describe('featureFlagRulesV2EditorLogic', () => {
expect(refreshTreeItem).toHaveBeenCalledWith('feature_flag', '8')
})
+ it('creates a string flag with an experiment rule and a holdout that carry no seed', async () => {
+ const create = jest.spyOn(api, 'create').mockResolvedValue({ ...STRING_FLAG, id: 10 })
+ const logic = featureFlagRulesV2EditorLogic({ id: 'new' })
+ logic.mount()
+
+ logic.actions.setDraft({ key: 'checkout-layout' })
+ logic.actions.setReturnType('string')
+ logic.actions.addRule()
+ expect(logic.values.draft.config).toMatchObject({ return_type: 'string', default_value: null })
+ expect(logic.values.saveDisabledReason).toBe('Rule 1: Enter a value.')
+ logic.actions.updateRule(0, withRuleType(logic.values.draft.config.rules[0], 'experiment', 'string'))
+ logic.actions.updateRule(0, {
+ ...(logic.values.draft.config.rules[0] as FeatureFlagRulesV2DraftExperimentRule),
+ paused: true,
+ holdout: NEW_HOLDOUT,
+ })
+ expect(logic.values.saveDisabledReason).toBeNull()
+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())
+ .toDispatchActions(['saveRulesV2FlagSuccess'])
+ .toFinishAllListeners()
+
+ const body = create.mock.calls[0][1] as Record<string, any>
+ expect(body.filters).toEqual({
+ version: 2,
+ return_type: 'string',
+ default_value: null,
+ rules: [
+ {
+ rule_type: 'experiment',
+ targeting: { properties: [] },
+ paused: true,
+ rollout_percentage: 100,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ assign_by: 'person',
+ variants: [
+ { key: 'control', weight: 50, value: 'control' },
+ { key: 'test', weight: 50, value: 'test' },
+ ],
+ holdout: { exclusion_percentage: 10 },
+ },
+ ],
+ })
+ expect(JSON.stringify(body)).not.toContain('seed')
+ })
+
it('blocks a create in a project that requires evaluation contexts, which a rules v2 create cannot set', () => {
enabledFeaturesLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.FLAG_EVALUATION_TAGS]: true })
teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, require_evaluation_contexts: true })
@@ -234,8 +546,8 @@ describe('featureFlagRulesV2EditorLogic', () => {
const body = update.mock.calls[0][1] as Record<string, any>
expect(body.version).toBe(3)
- expect(body.filters.rules.map((rule: { id: string }) => rule.id)).toEqual(['rule-rollout', 'rule-beta'])
- expect(JSON.stringify(body)).not.toContain('seed')
+ const [stored0, stored1] = (V2_FLAG.filters as FeatureFlagRulesV2Config).rules
+ expect(body.filters.rules).toEqual([stored1, stored0])
expect(refreshTreeItem).toHaveBeenCalledWith('feature_flag', '7')
expect(pageLogic.values).toMatchObject({ isEditingFlag: false, featureFlag: { version: 4 } })
})
@@ -432,4 +744,157 @@ describe('featureFlagRulesV2EditorLogic', () => {
})
})
})
+ describe('editing an experiment rule', () => {
+ let logic: ReturnType<typeof featureFlagRulesV2EditorLogic.build>
+
+ const experimentRule = (): FeatureFlagRulesV2DraftExperimentRule =>
+ logic.values.draft.config.rules[1] as FeatureFlagRulesV2DraftExperimentRule
+ const setExperimentRule = (fields: Partial<FeatureFlagRulesV2DraftExperimentRule>): void =>
+ logic.actions.updateRule(1, { ...experimentRule(), ...fields })
+ const setVariant = (index: number, fields: Record<string, unknown>): void =>
+ setExperimentRule({
+ variants: experimentRule().variants.map((v, i) => (i === index ? { ...v, ...fields } : v)),
+ })
+
+ beforeEach(async () => {
+ const pageLogic = featureFlagLogic({ id: 9 })
+ pageLogic.mount()
+ await expectLogic(pageLogic, () => pageLogic.actions.editFeatureFlag(true))
+ .toDispatchActions(['loadFeatureFlagSuccess'])
+ .toFinishAllListeners()
+ logic = featureFlagRulesV2EditorLogic({ id: 9 })
+ logic.mount()
+ })
+
+ it('changes another rule and moves the experiment rule without touching any of its fields', async () => {
+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...STRING_FLAG, version: 6 })
+
+ logic.actions.updateRule(0, { ...STRING_FLAG_RULES[0], value: 'spacious' } as FeatureFlagRulesV2DraftRule)
+ logic.actions.moveRule(1, 0)
+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())
+ .toDispatchActions(['saveRulesV2FlagSuccess'])
+ .toFinishAllListeners()
+
+ const body = update.mock.calls[0][1] as Record<string, any>
+ expect(body.version).toBe(5)
+ expect(body.filters.rules).toEqual([
+ EXPERIMENT_RULE,
+ { id: 'rule-beta', rule_type: 'targeted_release', targeting: { properties: [] }, value: 'spacious' },
+ ])
+ })
+
+ it('edits variants and the holdout, echoing both seeds and keeping fields it does not show', async () => {
+ const update = jest.spyOn(api, 'update').mockResolvedValue({ ...STRING_FLAG, version: 6 })
+
+ setExperimentRule({ variants: moved(experimentRule().variants, 2, 0) })
+ setExperimentRule({ variants: experimentRule().variants.filter((variant) => variant.key !== 'compact') })
+ setVariant(0, { weight: 50 })
+ setVariant(1, { weight: 50 })
+ setExperimentRule({ holdout: { ...experimentRule().holdout!, exclusion_percentage: 7.5 }, paused: true })
+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag())
+ .toDispatchActions(['saveRulesV2FlagSuccess'])
+ .toFinishAllListeners()
+
+ const sent = (update.mock.calls[0][1] as Record<string, any>).filters.rules[1]
+ expect(sent).toEqual({
+ ...EXPERIMENT_RULE,
+ paused: true,
+ variants: [
+ { key: 'spacious', weight: 50, value: 'spacious' },
+ { key: 'control', weight: 50, value: 'standard' },
+ ],
+ holdout: { seed: 'holdout-seed', exclusion_percentage: 7.5 },
+ })
+ })
+
+ it('removes the holdout with its seed, and adds one back without a seed', () => {
+ const { holdout: _holdout, ...withoutHoldout } = experimentRule()
+ logic.actions.updateRule(1, withoutHoldout)
+ expect(experimentRule()).not.toHaveProperty('holdout')
+
+ setExperimentRule({ holdout: NEW_HOLDOUT })
+ expect(rulesV2WriteBody(logic.values.draft).filters.rules[1]).toMatchObject({
+ seed: 'split-seed',
+ holdout: { exclusion_percentage: 10 },
+ })
+ expect(JSON.stringify(experimentRule().holdout)).not.toContain('seed')
+ })
+
+ it.each([
+ {
+ check: 'weights that do not total 100',
+ edit: () => setVariant(0, { weight: 23.34 }),
+ field: 'filters.rules[1].variants',
+ error: 'Variant weights must total 100% (now 90%).',
+ },
+ {
+ check: 'a weight with three decimal places',
+ edit: () => setVariant(1, { weight: 33.333 }),
+ field: 'filters.rules[1].variants[1].weight',
+ error: 'Must have at most two decimal places.',
+ },
+ {
+ check: 'a duplicate key',
+ edit: () => setVariant(2, { key: 'control' }),
+ field: 'filters.rules[1].variants[2].key',
+ error: 'Variant keys must be unique.',
+ },
+ {
+ check: 'a key with a dot',
+ edit: () => setVariant(2, { key: 'layout.v2' }),
+ field: 'filters.rules[1].variants[2].key',
+ error: 'Only letters, numbers, hyphens (-) and underscores (_) are allowed.',
+ },
+ {
+ check: 'an empty key',
+ edit: () => setVariant(2, { key: '' }),
+ field: 'filters.rules[1].variants[2].key',
+ error: 'Enter a key.',
+ },
+ {
+ check: 'an empty string value',
+ edit: () => setVariant(0, { value: '' }),
+ field: 'filters.rules[1].variants[0].value',
+ error: 'Enter a value.',
+ },
+ {
+ check: 'a value of another type',
+ edit: () => setVariant(0, { value: true }),
+ field: 'filters.rules[1].variants[0].value',
+ error: 'Enter a value.',
+ },
+ {
+ check: 'a single variant',
+ edit: () => setExperimentRule({ variants: [{ key: 'control', weight: 100, value: 'standard' }] }),
+ field: 'filters.rules[1].variants',
+ error: 'Add at least 2 variants.',
+ },
+ {
+ check: 'a holdout above 100%',
+ edit: () => setExperimentRule({ holdout: { exclusion_percentage: 101 } }),
+ field: 'filters.rules[1].holdout.exclusion_percentage',
+ error: 'Must be between 0 and 100.',
+ },
+ ])('flags $check against its field and blocks the save', ({ edit, field, error }) => {
+ expect(logic.values.saveDisabledReason).toBeNull()
+ edit()
+ expect(logic.values.fieldError(field)).toBe(error)
+ expect(logic.values.saveDisabledReason).toBe(`Rule 2: ${error}`)
+ })
+
+ it('shows a server error on the variant field it names', async () => {
+ jest.spyOn(api, 'update').mockRejectedValue({
+ status: 400,
+ attr: 'filters__rules__1__variants__2__value',
+ detail: 'Must be a non-empty string other than $false or $true.',
+ })
+
+ await expectLogic(logic, () => logic.actions.saveRulesV2Flag()).toDispatchActions([
+ 'saveRulesV2FlagFailure',
+ ])
+ expect(logic.values.fieldError('filters.rules[1].variants[2].value')).toBe(
+ 'Must be a non-empty string other than $false or $true.'
+ )
+ })
+ })
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
index 21fb51d0282f..8f8b07a50a4c 100644
--- a/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagRulesV2EditorLogic.ts
@@ -30,7 +30,7 @@ import {
FeatureFlagConfig,
FeatureFlagRulesV2DraftConfig,
FeatureFlagRulesV2DraftRule,
- FeatureFlagRulesV2Rule,
+ FeatureFlagRulesV2ReturnType,
FeatureFlagType,
PropertyOperator,
TeamPublicType,
@@ -56,6 +56,13 @@ import {
validateFeatureFlagKey,
variantKeyToIndexFeatureFlagPayloads,
} from './featureFlagLogic'
+import {
+ NEW_TARGETED_RELEASE_RULE,
+ moved,
+ rulesV2DraftErrors,
+ rulesV2InitialValue,
+ withReturnType,
+} from './featureFlagRulesV2Draft'
export interface FeatureFlagRulesV2Draft {
key: string
@@ -88,64 +95,11 @@ export const NEW_RULES_V2_DRAFT: FeatureFlagRulesV2Draft = {
version: null,
}
-export const BOOLEAN_OPTIONS = [
- { value: 'true', label: 'true' },
- { value: 'false', label: 'false' },
-]
-
-export const NEW_TARGETED_RELEASE_RULE: FeatureFlagRulesV2DraftRule = {
- rule_type: 'targeted_release',
- targeting: { properties: [] },
- value: true,
-}
-
-// The rollout fields a rule gains when it becomes a percentage rollout; the server assigns its seed.
-export const NEW_ROLLOUT_FIELDS = {
- rollout_percentage: 0,
- on_rollout_miss: 'continue',
- assignment_algorithm: 'sha1_60_v1',
- assign_by: 'person',
-} as const
-
// React keys for rule cards: new rules have no id, and index keys would follow a moved rule's position.
let lastRuleKey = 0
const nextRuleKey = (): number => ++lastRuleKey
-function moved<T>(items: T[], from: number, to: number): T[] {
- const result = [...items]
- result.splice(to, 0, ...result.splice(from, 1))
- return result
-}
-
-const RULE_FIELDS = new Set(['rule_type', 'description', 'targeting', 'value', 'rollout_percentage', 'on_rollout_miss'])
-
-/** Keeps the rule's identity and shared fields; rollout fields come and go with the type. */
-export function withRuleType(
- rule: FeatureFlagRulesV2DraftRule,
- ruleType: FeatureFlagRulesV2DraftRule['rule_type']
-): FeatureFlagRulesV2DraftRule {
- if (rule.rule_type === ruleType) {
- return rule
- }
- const { id, targeting, description, metadata, value } = rule
- const shared = { id, targeting, description, metadata, value }
- return ruleType === 'percentage_rollout'
- ? { ...shared, rule_type: ruleType, ...NEW_ROLLOUT_FIELDS }
- : { ...shared, rule_type: ruleType }
-}
-
-function toDraftRule(rule: FeatureFlagRulesV2Rule): FeatureFlagRulesV2DraftRule {
- if (rule.rule_type === 'targeted_release') {
- return rule
- }
- if (rule.rule_type === 'percentage_rollout') {
- const { seed: _seed, ...draftRule } = rule
- return draftRule
- }
- // Only editable documents reach the editor; dropping a rule here would delete it on save.
- throw new Error('Experiment rules cannot be edited here.')
-}
-
+/** The draft holds the stored document as loaded, seeds and unrendered fields included, so a save echoes them. */
export function rulesV2DraftFromFlag(flag: FeatureFlagType): FeatureFlagRulesV2Draft {
if (!isRulesV2FeatureFlagConfig(flag.filters)) {
return NEW_RULES_V2_DRAFT
@@ -154,7 +108,7 @@ export function rulesV2DraftFromFlag(flag: FeatureFlagType): FeatureFlagRulesV2D
key: flag.key,
name: flag.name ?? '',
tags: flag.tags ?? [],
- config: { ...flag.filters, rules: flag.filters.rules.map(toDraftRule) },
+ config: flag.filters,
version: flag.version,
}
}
@@ -170,15 +124,45 @@ export function rulesV2WriteBody(draft: FeatureFlagRulesV2Draft): RulesV2WriteBo
}
}
+const RULE_FIELDS = [
+ 'rule_type',
+ 'description',
+ 'targeting',
+ 'value',
+ 'rollout_percentage',
+ 'on_rollout_miss',
+ 'paused',
+ 'seed',
+ 'variants',
+ 'variants[]',
+ 'variants[].key',
+ 'variants[].weight',
+ 'variants[].value',
+ 'holdout',
+ 'holdout.exclusion_percentage',
+ 'holdout.seed',
+]
+// The paths, with list indices removed, that the editor shows an error against.
+const EDITOR_FIELDS = new Set([
+ 'key',
+ 'name',
+ 'tags',
+ 'filters.return_type',
+ 'filters.default_value',
+ 'filters.rules[]',
+ ...RULE_FIELDS.map((field) => `filters.rules[].${field}`),
+])
+
+/** The longest prefix of `path` that the editor has a field for, so a nested error lands on its nearest field. */
function editorField(path: string): string | null {
- if (path === 'key' || path === 'name' || path === 'tags' || path === 'filters.default_value') {
- return path
- }
- const rule = /^filters\.rules\[(\d+)\](?:\.(\w+))?/.exec(path)
- if (!rule) {
- return null
+ let prefix: string | undefined = path
+ while (prefix) {
+ if (EDITOR_FIELDS.has(prefix.replace(/\[\d+\]/g, '[]'))) {
+ return prefix
+ }
+ prefix = /^(.+)(?:\.\w+|\[\d+\])$/.exec(prefix)?.[1]
}
- return rule[2] && RULE_FIELDS.has(rule[2]) ? `filters.rules[${rule[1]}].${rule[2]}` : `filters.rules[${rule[1]}]`
+ return null
}
/** `attr` joins nested keys with `__`; a document path that is not the input's own stays in the message. */
@@ -202,6 +186,7 @@ export interface featureFlagRulesV2EditorLogicValues {
currentProjectId: number | null // projectLogic
currentTeam: TeamPublicType | TeamType | null // teamLogic
draft: FeatureFlagRulesV2Draft
+ draftErrors: Record<string, string>
fieldError: (field: string) => string | null
hasUnsavedChanges: boolean
ruleKeys: number[]
@@ -273,6 +258,9 @@ export interface featureFlagRulesV2EditorLogicActions {
setDraft: (draft: Partial<FeatureFlagRulesV2Draft>) => {
draft: Partial<FeatureFlagRulesV2Draft>
}
+ setReturnType: (returnType: FeatureFlagRulesV2ReturnType) => {
+ returnType: FeatureFlagRulesV2ReturnType
+ }
setRule: (
index: number,
rule: FeatureFlagRulesV2DraftRule
@@ -296,9 +284,14 @@ export interface featureFlagRulesV2EditorLogicActions {
export interface featureFlagRulesV2EditorLogicMeta {
key: number | 'link' | 'new'
__keaTypeGenInternalSelectorTypes: {
- fieldError: (saveError: RulesV2SaveError | null) => (field: string) => string | null
+ draftErrors: (draft: FeatureFlagRulesV2Draft) => Record<string, string>
+ fieldError: (
+ saveError: RulesV2SaveError | null,
+ draftErrors: Record<string, string>
+ ) => (field: string) => string | null
saveDisabledReason: (
draft: FeatureFlagRulesV2Draft,
+ draftErrors: Record<string, string>,
currentTeam: TeamPublicType | TeamType | null,
enabledFeatures: FeatureFlagsSet,
id: number | 'link' | 'new'
@@ -335,6 +328,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
loadDraft: (draft: FeatureFlagRulesV2Draft) => ({ draft }),
setDraft: (draft: Partial<FeatureFlagRulesV2Draft>) => ({ draft }),
setConfig: (config: Partial<FeatureFlagRulesV2DraftConfig>) => ({ config }),
+ setReturnType: (returnType: FeatureFlagRulesV2ReturnType) => ({ returnType }),
addRule: true,
updateRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),
setRule: (index: number, rule: FeatureFlagRulesV2DraftRule) => ({ index, rule }),
@@ -352,9 +346,19 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
loadDraft: (_, { draft }) => draft,
setDraft: (state, { draft }) => ({ ...state, ...draft }),
setConfig: (state, { config }) => ({ ...state, config: { ...state.config, ...config } }),
+ setReturnType: (state, { returnType }) => ({
+ ...state,
+ config: withReturnType(state.config, returnType),
+ }),
addRule: (state) => ({
...state,
- config: { ...state.config, rules: [...state.config.rules, NEW_TARGETED_RELEASE_RULE] },
+ config: {
+ ...state.config,
+ rules: [
+ ...state.config.rules,
+ { ...NEW_TARGETED_RELEASE_RULE, value: rulesV2InitialValue(state.config.return_type) },
+ ],
+ },
}),
setRule: (state, { index, rule }) => ({
...state,
@@ -389,6 +393,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
saveRulesV2Flag: () => null,
setDraft: () => null,
setConfig: () => null,
+ setReturnType: () => null,
addRule: () => null,
setRule: () => null,
removeRule: () => null,
@@ -402,6 +407,7 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
saveRulesV2FlagSuccess: () => false,
setDraft: () => true,
setConfig: () => true,
+ setReturnType: () => true,
addRule: () => true,
setRule: () => true,
removeRule: () => true,
@@ -418,16 +424,22 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
],
}),
selectors({
+ draftErrors: [
+ (s) => [s.draft],
+ (draft: FeatureFlagRulesV2Draft): Record<string, string> => rulesV2DraftErrors(draft.config),
+ ],
+ // The server's error wins: it is about the document as it was sent.
fieldError: [
- (s) => [s.saveError],
- (saveError: RulesV2SaveError | null) =>
+ (s) => [s.saveError, s.draftErrors],
+ (saveError: RulesV2SaveError | null, draftErrors: Record<string, string>) =>
(field: string): string | null =>
- saveError?.field === field ? saveError.message : null,
+ saveError?.field === field ? saveError.message : (draftErrors[field] ?? null),
],
saveDisabledReason: [
- (s, p) => [s.draft, s.currentTeam, s.enabledFeatures, p.id],
+ (s, p) => [s.draft, s.draftErrors, s.currentTeam, s.enabledFeatures, p.id],
(
draft: FeatureFlagRulesV2Draft,
+ draftErrors: Record<string, string>,
currentTeam: TeamPublicType | TeamType | null,
enabledFeatures: FeatureFlagsSet,
id: FeatureFlagLogicProps['id']
@@ -442,13 +454,10 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
if (keyError) {
return keyError
}
- const badRollout = draft.config.rules.some(
- (rule) =>
- rule.rule_type === 'percentage_rollout' &&
- !(rule.rollout_percentage >= 0 && rule.rollout_percentage <= 100)
- )
- if (badRollout) {
- return 'Rollout percentages must be between 0 and 100.'
+ const [firstErrorField, firstError] = Object.entries(draftErrors)[0] ?? []
+ if (firstErrorField) {
+ const ruleIndex = Number(/^filters\.rules\[(\d+)\]/.exec(firstErrorField)?.[1])
+ return `Rule ${ruleIndex + 1}: ${firstError}`
}
// The server accepts a condition with no value, but the condition never matches.
// Set and not-set conditions take no value, so they are not incomplete.
@@ -485,10 +494,10 @@ export const featureFlagRulesV2EditorLogic = kea<featureFlagRulesV2EditorLogicTy
return
}
// The server does not enforce the project's confirmation setting, so this check is the only gate.
- // Both sides are compared without seeds, because the draft never holds one and a stored seed would count as a change.
+ // The draft holds the stored seeds, so only a real edit differs from the stored document.
const confirmationEnabled = !!values.currentTeam?.feature_flag_confirmation_enabled
const confirmationShown = checkFeatureFlagConfirmation(
- { ...storedFlag, filters: rulesV2DraftFromFlag(storedFlag).config as FeatureFlagConfig },
+ storedFlag,
{ ...storedFlag, key: values.draft.key, filters: values.draft.config as FeatureFlagConfig },
confirmationEnabled,
confirmationEnabled ? values.currentTeam?.feature_flag_confirmation_message : undefined,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 458bdc455cfd..eb15a53c8013 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -4511,7 +4511,6 @@ interface FeatureFlagRulesV2RuleBase {
targeting: { properties: AnyPropertyFilter[] }
description?: string
metadata?: Record<string, unknown>
- value: JsonType
}
interface FeatureFlagRulesV2RolloutFields {
@@ -4524,18 +4523,34 @@ interface FeatureFlagRulesV2RolloutFields {
export interface FeatureFlagRulesV2TargetedReleaseRule extends FeatureFlagRulesV2RuleBase {
rule_type: 'targeted_release'
+ value: JsonType
}
export interface FeatureFlagRulesV2PercentageRolloutRule
extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {
rule_type: 'percentage_rollout'
+ value: JsonType
+}
+
+export interface FeatureFlagRulesV2Variant {
+ key: string
+ /** Percentage of the subjects the rule enrolls; the weights of a rule total 100. */
+ weight: number
+ value: JsonType
}
+/** Belongs to its rule. The seed is server-owned. */
+export interface FeatureFlagRulesV2Holdout {
+ seed: string
+ exclusion_percentage: number
+}
+
+/** Serves the values of its variants. An experiment links to its rule, so the rule never names an experiment. */
export interface FeatureFlagRulesV2ExperimentRule extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {
rule_type: 'experiment'
paused: boolean
- variants: { key: string; weight: number; value: JsonType }[]
- holdout?: { seed: string; exclusion_percentage: number }
+ variants: FeatureFlagRulesV2Variant[]
+ holdout?: FeatureFlagRulesV2Holdout
}
export type FeatureFlagRulesV2Rule =
@@ -4557,10 +4572,22 @@ export interface FeatureFlagUnsupportedConfig extends WithoutFeatureFlagFiltersK
aggregation_group_type_index?: never
}
-/** A rule while the editor drafts it: a new rule has no `id` until the server assigns one, and no draft holds a `seed`. */
+/**
+ * A rule while the editor drafts it. A new rule has no `id`, and a new rollout or holdout no `seed`, until the server
+ * assigns them. A stored rule keeps both, and every field the editor does not render, as it was loaded.
+ */
export type FeatureFlagRulesV2DraftRule =
| (Omit<FeatureFlagRulesV2TargetedReleaseRule, 'id'> & { id?: string })
- | (Omit<FeatureFlagRulesV2PercentageRolloutRule, 'id' | 'seed'> & { id?: string })
+ | (Omit<FeatureFlagRulesV2PercentageRolloutRule, 'id' | 'seed'> & { id?: string; seed?: string })
+ | (Omit<FeatureFlagRulesV2ExperimentRule, 'id' | 'seed' | 'holdout'> & {
+ id?: string
+ seed?: string
+ holdout?: FeatureFlagRulesV2DraftHoldout
+ })
+
+export type FeatureFlagRulesV2DraftExperimentRule = Extract<FeatureFlagRulesV2DraftRule, { rule_type: 'experiment' }>
+
+export type FeatureFlagRulesV2DraftHoldout = Omit<FeatureFlagRulesV2Holdout, 'seed'> & { seed?: string }
export interface FeatureFlagRulesV2DraftConfig extends Omit<FeatureFlagRulesV2Config, 'rules'> {
rules: FeatureFlagRulesV2DraftRule[]
diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx
index dbab4e4a6281..953f5947dab0 100644
--- a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx
+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.test.tsx
@@ -44,7 +44,6 @@ describe('FeatureFlagRulesV2Readonly', () => {
id: 'rule-3',
rule_type: 'experiment',
targeting: { properties: [] },
- value: true,
rollout_percentage: 100,
on_rollout_miss: 'continue',
assignment_algorithm: 'sha1_60_v1',
@@ -80,35 +79,50 @@ describe('FeatureFlagRulesV2Readonly', () => {
expect(container).not.toHaveTextContent('seed-must-not-render')
})
- it('shows an experiment rule by its variants and paused state', () => {
- const config: FeatureFlagRulesV2Config = {
- ...CONFIG,
- rules: [
- {
- id: 'rule-2',
- rule_type: 'experiment',
- targeting: { properties: [] },
- value: true,
- rollout_percentage: 100,
- on_rollout_miss: 'continue',
- assignment_algorithm: 'sha1_60_v1',
- seed: 'seed-must-not-render',
- paused: true,
- variants: [
- { key: 'control', weight: 50, value: false },
- { key: 'test', weight: 50, value: true },
- ],
- },
+ it('labels every experiment rule "Experiment" and shows its variants, pause and holdout', () => {
+ const experimentRule = {
+ rule_type: 'experiment' as const,
+ targeting: { properties: [] },
+ paused: true,
+ rollout_percentage: 50,
+ on_rollout_miss: 'continue' as const,
+ assignment_algorithm: 'sha1_60_v1',
+ seed: 'rule-seed-must-not-render',
+ variants: [
+ { key: 'control', weight: 33.34, value: 'standard' },
+ { key: 'compact', weight: 66.66, value: 'compact-layout' },
],
}
const { container } = render(
<Provider>
- <FeatureFlagRulesV2Readonly config={config} />
+ <FeatureFlagRulesV2Readonly
+ config={{
+ version: 2,
+ return_type: 'string',
+ default_value: null,
+ rules: [
+ {
+ ...experimentRule,
+ id: 'rule-paused',
+ holdout: { seed: 'holdout-seed-must-not-render', exclusion_percentage: 5 },
+ },
+ { ...experimentRule, id: 'rule-running', paused: false },
+ ],
+ }}
+ />
</Provider>
)
- expect(container).toHaveTextContent('Paused')
- expect(container).toHaveTextContent('control')
- expect(container).not.toHaveTextContent('seed-must-not-render')
+ const [pausedRow, runningRow] = Array.from(container.querySelectorAll('tbody tr'))
+ expect(pausedRow).toHaveTextContent('Experiment')
+ expect(pausedRow).toHaveTextContent('Paused')
+ expect(pausedRow).toHaveTextContent('control33.34%"standard"')
+ expect(pausedRow).toHaveTextContent('compact66.66%"compact-layout"')
+ expect(pausedRow).toHaveTextContent('50%Miss: next rule')
+ expect(pausedRow).toHaveTextContent('Holdout excludes 5%')
+ expect(runningRow).toHaveTextContent('Experiment')
+ expect(runningRow).not.toHaveTextContent('Paused')
+ expect(runningRow).not.toHaveTextContent('Holdout')
+ expect(container).not.toHaveTextContent('must-not-render')
})
})
diff --git a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx
index 2c451ab84a4c..50f1ed090a53 100644
--- a/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx
+++ b/products/feature_flags/frontend/FeatureFlagRulesV2Readonly.tsx
@@ -43,7 +43,12 @@ function ValueCell({ rule }: { rule: FeatureFlagRulesV2Rule }): JSX.Element {
return (
<div className="flex flex-col gap-1">
{rule.paused && (
- <LemonTag type="warning" size="small" className="self-start">
+ <LemonTag
+ type="warning"
+ size="small"
+ className="self-start"
+ title="Persons this rule targets get the default value while it is paused."
+ >
Paused
</LemonTag>
)}
diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.test.ts b/products/feature_flags/frontend/featureFlagConfigFormat.test.ts
index 41f7b945f468..05a8233276f0 100644
--- a/products/feature_flags/frontend/featureFlagConfigFormat.test.ts
+++ b/products/feature_flags/frontend/featureFlagConfigFormat.test.ts
@@ -1,3 +1,4 @@
+import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { FeatureFlagConfig } from '~/types'
@@ -7,9 +8,34 @@ import {
featureFlagConfigFormat,
featureFlagConfigFormatLabel,
featureFlagDeleteOptions,
+ isRulesV2EditableConfig,
rowVersionToken,
} from './featureFlagConfigFormat'
+const EXPERIMENT_RULE = {
+ id: 'rule-split',
+ rule_type: 'experiment',
+ targeting: { properties: [] },
+ paused: false,
+ rollout_percentage: 100,
+ on_rollout_miss: 'continue',
+ assignment_algorithm: 'sha1_60_v1',
+ seed: 'split-seed',
+ variants: [
+ { key: 'control', weight: 50, value: 'standard' },
+ { key: 'test', weight: 50, value: 'compact' },
+ ],
+}
+
+const stringFlag = (rule: Record<string, unknown>, config: Record<string, unknown> = {}): FeatureFlagConfig =>
+ ({
+ version: 2,
+ return_type: 'string',
+ default_value: null,
+ rules: [{ ...EXPERIMENT_RULE, ...rule }],
+ ...config,
+ }) as FeatureFlagConfig
+
describe('featureFlagConfigFormat', () => {
it.each([
[undefined, 'v1', 'Config v1'],
@@ -33,6 +59,40 @@ describe('featureFlagConfigFormat', () => {
expect(rowVersionToken(flag)).toEqual(expected)
})
+ const EDITOR_ON = { [FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR]: true }
+
+ it.each([
+ ['an experiment rule', stringFlag({}), true],
+ ['a string targeted release', stringFlag({ rule_type: 'targeted_release', value: 'compact' }), true],
+ [
+ 'an experiment rule with a holdout',
+ stringFlag({ holdout: { seed: 'holdout-seed', exclusion_percentage: 5 } }),
+ true,
+ ],
+ [
+ 'a boolean experiment rule',
+ stringFlag(
+ { variants: [{ key: 'a', weight: 100, value: true }] },
+ { return_type: 'boolean', default_value: false }
+ ),
+ true,
+ ],
+ ['group assignment', stringFlag({}, { aggregation_group_type_index: 0 }), false],
+ ['a variant value of another type', stringFlag({ variants: [{ key: 'a', weight: 100, value: 1 }] }), false],
+ [
+ 'a number return type',
+ stringFlag(
+ { variants: [{ key: 'a', weight: 100, value: 1 }] },
+ { return_type: 'number', default_value: 1 }
+ ),
+ false,
+ ],
+ ['an unknown rule type', stringFlag({ rule_type: 'future_rule' }), false],
+ ])('decides whether a flag with %s opens the editor', (_, filters, editable) => {
+ expect(isRulesV2EditableConfig(filters, EDITOR_ON)).toBe(editable)
+ expect(isRulesV2EditableConfig(filters, {})).toBe(false)
+ })
+
it.each([
[undefined, true],
[{ groups: [] }, true],
diff --git a/products/feature_flags/frontend/featureFlagConfigFormat.ts b/products/feature_flags/frontend/featureFlagConfigFormat.ts
index b17add38e358..eb9925026f48 100644
--- a/products/feature_flags/frontend/featureFlagConfigFormat.ts
+++ b/products/feature_flags/frontend/featureFlagConfigFormat.ts
@@ -3,7 +3,15 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-import { FeatureFlagConfig, FeatureFlagFilters, FeatureFlagRulesV2Config, TeamPublicType, TeamType } from '~/types'
+import {
+ FeatureFlagConfig,
+ FeatureFlagFilters,
+ FeatureFlagRulesV2Config,
+ FeatureFlagRulesV2ReturnType,
+ FeatureFlagRulesV2Rule,
+ TeamPublicType,
+ TeamType,
+} from '~/types'
export type FeatureFlagConfigFormat = 'v1' | 'v2' | 'unsupported'
@@ -107,13 +115,41 @@ export function rulesV2CreateDisabledReason(
: null
}
-/** Whether the rules v2 editor is on and can edit this document: boolean return type, person assignment, no experiment rules. */
+export const RULES_V2_EDITABLE_RETURN_TYPES: FeatureFlagRulesV2ReturnType[] = ['boolean', 'string']
+
+export function isRulesV2Value(value: unknown, returnType: FeatureFlagRulesV2ReturnType): boolean {
+ switch (returnType) {
+ case 'boolean':
+ return typeof value === 'boolean'
+ case 'string':
+ return typeof value === 'string' && value !== ''
+ default:
+ return false
+ }
+}
+
+function isRulesV2EditableRule(rule: FeatureFlagRulesV2Rule, returnType: FeatureFlagRulesV2ReturnType): boolean {
+ switch (rule.rule_type) {
+ case 'targeted_release':
+ case 'percentage_rollout':
+ return isRulesV2Value(rule.value, returnType)
+ case 'experiment':
+ return rule.variants.every((variant) => isRulesV2Value(variant.value, returnType))
+ default:
+ return false
+ }
+}
+
+/**
+ * Whether the rules v2 editor is on and can edit this document: a return type it authors, person assignment, and
+ * rules it can show. Anything else stays read-only, so a save never rewrites what the editor cannot represent.
+ */
export function isRulesV2EditableConfig(filters: FeatureFlagConfig, enabledFeatures: FeatureFlagsSet): boolean {
return (
!!enabledFeatures[FEATURE_FLAGS.FEATURE_FLAG_RULES_V2_EDITOR] &&
isRulesV2FeatureFlagConfig(filters) &&
- filters.return_type === 'boolean' &&
+ RULES_V2_EDITABLE_RETURN_TYPES.includes(filters.return_type) &&
filters.aggregation_group_type_index == null &&
- filters.rules.every((rule) => rule.rule_type !== 'experiment' && typeof rule.value === 'boolean')
+ filters.rules.every((rule) => isRulesV2EditableRule(rule, filters.return_type))
)
}