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): make the scheduled rollout timeline show real reach (#96581)

posthog[bot]54d8ee179022
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d91492a69d19..b8b41fa2e9f5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10402,10 +10402,18 @@ snapshots:
hash: v1.k794b7964.4bee55e405082cc86dbd6cbaeb89cc1d583174707ba34ebcd95648ad8c32658a.yMqVeg0qnl7x4i2wG3eomTFBZVXVSQCdgHVkoY70t0A
scenes-app-feature-flags-request-usage-summary-card--billing-units--light:
hash: v1.k794b7964.4c874fa56cb5763308d6014643e745856067d5ae0cd7d14cff6454718555b111.lviDpRxDXwBFa5Z4SbmojXPgplv48hNUG3VUIelmOrw
+ scenes-app-feature-flags-schedule-timeline--covered-rollout-ramp--dark:
+ hash: v1.k794b7964.a16393e9799f0a818ec54927d7e808860e64a8b0ab38667909b227bafdc7baf4.3a8ugi4Iv6LFx7U3W2wPsyqW7I6-oTS1ITx-74Sw6mI
+ scenes-app-feature-flags-schedule-timeline--covered-rollout-ramp--light:
+ hash: v1.k794b7964.87440ca24f1c67833eeac4c254e81a0d9e5a6eca72a90053165ca2e43d440d36.s44kIRmE0vrIFAS5mSj1OVDwCWFFq7oeNb1z6h5knYE
+ scenes-app-feature-flags-schedule-timeline--edge-step-labels--dark:
+ hash: v1.k794b7964.80b91247f288e836b99853ff3a1921184cc36621729d964870047e1b356cd2fe.vji9HS2Hp2Kdn6IsqOBZsMM2B9hpQ7-2yH4EEat4Jh4
+ scenes-app-feature-flags-schedule-timeline--edge-step-labels--light:
+ hash: v1.k794b7964.b977adbbcb59635a3b478ffd4ed41f7bc5803bb159f90a675668e2571f6c70e5.c_WEpoX7fZ1siRkx54hn1JgrT4MYzcJujYqQOXpyFKw
scenes-app-feature-flags-schedule-timeline--rollout-ramp--dark:
- hash: v1.k794b7964.2953688108a239d2ec1fed7e9536ba4fe608d7894111f5eeaf6f8a47339d8aff.sgkcFh_IvnLvMdJI7mdrIZEMQFbXUeRMTQxiWJUpalU
+ hash: v1.k794b7964.a25d523cfa2098bcd1505f27e1152a712086ba2f5b4c2733ed02abf76e3e2990.wBGaE6uS0YbRr65WjgHcOLfToFjg9_YeU_jy6znKqaE
scenes-app-feature-flags-schedule-timeline--rollout-ramp--light:
- hash: v1.k794b7964.0785f69304e857d326d3f0b6fd1d080b98693832830dc27efee8962998071f21.1PukOHY28udTttP75f7GWVgGOqw5NVX8UynvDughGJo
+ hash: v1.k794b7964.e23abcdc63e112d1fba5dcd4caaa7ff3ee0df46f75ebcdab9e99a94ec716b699.l-ccW4sqQIcxEJkm8gU1ONQJHRkpeM_K9k5dmC9gX9A
scenes-app-feature-flags-schedule-timeline--single-occurrence--dark:
hash: v1.k794b7964.5f56b26c9731f7507c03e0ca3830b20dc9c54e0af644d969931a942054969403.gZwCiTKCj8cQ8GfXJIV5uUG058HQ5g5M4Z2qMVNYaHs
scenes-app-feature-flags-schedule-timeline--single-occurrence--light:
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
index a9abf1044579..9453e997dad1 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
@@ -1,4 +1,4 @@
-import { MOCK_DEFAULT_PROJECT } from 'lib/api.mock'
+import { MOCK_DEFAULT_PROJECT, MOCK_GROUP_TYPES } from 'lib/api.mock'
import '@testing-library/jest-dom'
@@ -8,9 +8,13 @@ import { BindLogic, Provider } from 'kea'
import { dayjs } from 'lib/dayjs'
import { useMocks } from '~/mocks/jest'
+import { groupsModel } from '~/models/groupsModel'
import { initKeaTests } from '~/test/init'
import {
+ AnyPropertyFilter,
FeatureFlagType,
+ PropertyFilterType,
+ PropertyOperator,
RecurrenceInterval,
ScheduledChangeOperationType,
ScheduledChangeRequestState,
@@ -33,12 +37,28 @@ const MULTIVARIATE_FILTERS: FeatureFlagType['filters']['multivariate'] = {
],
}
+/** The banner's sentence also lives in the live region beside it, so banner queries skip that node. */
+const IGNORE_LIVE_REGION = { ignore: '[aria-live]' }
+
+const PERSON_FILTER: AnyPropertyFilter = {
+ key: 'email',
+ value: 'a',
+ type: PropertyFilterType.Person,
+ operator: PropertyOperator.Exact,
+}
+
function buildFeatureFlag({
active,
rolloutPercentage,
+ aggregationGroupTypeIndex,
+ flagAggregationGroupTypeIndex,
+ properties = [],
}: {
active: boolean
rolloutPercentage: number | null
+ aggregationGroupTypeIndex?: number | null
+ flagAggregationGroupTypeIndex?: number | null
+ properties?: AnyPropertyFilter[]
}): FeatureFlagType {
return {
...NEW_FLAG,
@@ -46,12 +66,28 @@ function buildFeatureFlag({
active,
filters: {
...NEW_FLAG.filters,
- groups: [{ properties: [], rollout_percentage: rolloutPercentage, variant: null }],
+ aggregation_group_type_index: flagAggregationGroupTypeIndex,
+ groups: [
+ {
+ properties,
+ rollout_percentage: rolloutPercentage,
+ variant: null,
+ aggregation_group_type_index: aggregationGroupTypeIndex,
+ },
+ ],
multivariate: MULTIVARIATE_FILTERS,
},
}
}
+function stepLineStart(timeline: Element): { x: number; y: number } {
+ const starts = [...timeline.querySelectorAll('path')].map((path) => {
+ const [, x, y] = path.getAttribute('d')!.split(' ')
+ return { x: Number(x), y: Number(y) }
+ })
+ return starts.reduce((leftmost, point) => (point.x < leftmost.x ? point : leftmost))
+}
+
describe('FeatureFlagSchedule', () => {
const logicProps = { id: 'new' as const }
@@ -72,6 +108,23 @@ describe('FeatureFlagSchedule', () => {
})
}
+ function scheduleConditionAdd(rolloutPercentage: number, aggregationGroupTypeIndex?: number | null): void {
+ featureFlagLogic(logicProps).actions.setSchedulePayload(
+ {
+ groups: [
+ {
+ properties: [],
+ rollout_percentage: rolloutPercentage,
+ variant: null,
+ aggregation_group_type_index: aggregationGroupTypeIndex,
+ },
+ ],
+ multivariate: null,
+ },
+ null
+ )
+ }
+
beforeEach(() => {
useMocks({
get: {
@@ -159,6 +212,130 @@ describe('FeatureFlagSchedule', () => {
expect(screen.getByText(new RegExp(expectedText))).toBeInTheDocument()
})
+ const conditionAddCases: {
+ name: string
+ active?: boolean
+ currentRollout: number
+ currentGroupTypeIndex?: number | null
+ scheduledGroupTypeIndex?: number | null
+ scheduledRollout: number
+ expectWarning: boolean
+ }[] = [
+ { name: 'below the current rollout', currentRollout: 100, scheduledRollout: 25, expectWarning: true },
+ { name: 'level with the current rollout', currentRollout: 40, scheduledRollout: 40, expectWarning: true },
+ { name: 'above the current rollout', currentRollout: 40, scheduledRollout: 60, expectWarning: false },
+ { name: 'left at the form default', currentRollout: 100, scheduledRollout: 0, expectWarning: false },
+ {
+ name: 'covered only by a condition on another aggregation target',
+ currentRollout: 100,
+ currentGroupTypeIndex: 0,
+ scheduledRollout: 25,
+ expectWarning: false,
+ },
+ {
+ name: 'scheduled on another aggregation target',
+ currentRollout: 100,
+ scheduledGroupTypeIndex: 0,
+ scheduledRollout: 25,
+ expectWarning: false,
+ },
+ {
+ name: 'covered by a condition on its own aggregation target',
+ currentRollout: 100,
+ currentGroupTypeIndex: 0,
+ scheduledGroupTypeIndex: 0,
+ scheduledRollout: 25,
+ expectWarning: true,
+ },
+ { name: 'on a disabled flag', active: false, currentRollout: 100, scheduledRollout: 25, expectWarning: true },
+ ]
+
+ it.each(conditionAddCases)(
+ 'condition add $name: warns=$expectWarning',
+ ({
+ active = true,
+ currentRollout,
+ currentGroupTypeIndex,
+ scheduledGroupTypeIndex,
+ scheduledRollout,
+ expectWarning,
+ }) => {
+ renderSchedule(
+ buildFeatureFlag({
+ active,
+ rolloutPercentage: currentRollout,
+ aggregationGroupTypeIndex: currentGroupTypeIndex,
+ }),
+ ScheduledChangeOperationType.AddReleaseCondition
+ )
+
+ act(() => {
+ scheduleConditionAdd(scheduledRollout, scheduledGroupTypeIndex)
+ })
+
+ const warning = screen.queryByText(/^This flag (already serves|is disabled)/, IGNORE_LIVE_REGION)
+ expect(!!warning).toEqual(expectWarning)
+ }
+ )
+
+ it.each([
+ {
+ name: 'an active flag aggregating on persons',
+ active: true,
+ flagAggregationGroupTypeIndex: undefined,
+ expectedText: 'This flag already serves 100% of all users,',
+ },
+ {
+ name: 'an active flag aggregating on a group type',
+ active: true,
+ flagAggregationGroupTypeIndex: 0,
+ expectedText: 'This flag already serves 100% of all organizations,',
+ },
+ {
+ name: 'a disabled flag',
+ active: false,
+ flagAggregationGroupTypeIndex: undefined,
+ expectedText: 'This flag is disabled, but it is already set to serve 100% of all users,',
+ },
+ ])(
+ 'condition add warning on $name reads "$expectedText"',
+ ({ active, flagAggregationGroupTypeIndex, expectedText }) => {
+ renderSchedule(
+ buildFeatureFlag({ active, rolloutPercentage: 100, flagAggregationGroupTypeIndex }),
+ ScheduledChangeOperationType.AddReleaseCondition
+ )
+
+ act(() => {
+ groupsModel.actions.loadAllGroupTypesSuccess(MOCK_GROUP_TYPES)
+ scheduleConditionAdd(25)
+ })
+
+ expect(
+ screen.getByText(/^This flag (already serves|is disabled)/, IGNORE_LIVE_REGION).closest('.LemonBanner')
+ ).toHaveTextContent(expectedText)
+ // The live region carries its own copy of the sentence, so assert it says the same thing.
+ // A reader who never sees the banner gets this instead.
+ const announced = document.querySelector('[aria-live="polite"]')
+ expect(announced).toHaveTextContent(expectedText)
+ expect(announced).toHaveTextContent('A condition at 25% will not change who sees the flag.')
+ }
+ )
+
+ it('leaves the live region mounted and empty when the warning does not apply', () => {
+ // A region that appears already populated is not announced, so it cannot mount with the banner.
+ renderSchedule(
+ buildFeatureFlag({ active: true, rolloutPercentage: 40 }),
+ ScheduledChangeOperationType.AddReleaseCondition
+ )
+
+ act(() => {
+ scheduleConditionAdd(60)
+ })
+
+ expect(screen.queryByText(/This flag already serves/, IGNORE_LIVE_REGION)).not.toBeInTheDocument()
+ expect(document.querySelector('[aria-live="polite"]')).toBeEmptyDOMElement()
+ })
+
// useMocks trips the hooks naming lint inside named helpers, so each test registers
// its own mock before calling this.
const renderWithSchedules = (): void => {
@@ -171,6 +348,15 @@ describe('FeatureFlagSchedule', () => {
})
}
+ const addConditionChange = (rolloutPercentage: number, daysFromNow: number): ScheduledChangeType =>
+ makeScheduledChange({
+ scheduled_at: dayjs().add(daysFromNow, 'day').toISOString(),
+ payload: {
+ operation: ScheduledChangeOperationType.AddReleaseCondition,
+ value: { groups: [{ properties: [], rollout_percentage: rolloutPercentage, variant: null }] },
+ },
+ })
+
const schedulesMock = (
schedules: ScheduledChangeType[]
): Record<string, () => [number, { results: ScheduledChangeType[] }]> => ({
@@ -215,6 +401,27 @@ describe('FeatureFlagSchedule', () => {
expect(document.querySelector('[data-attr="feature-flag-open-schedule-form"]')).toBeInTheDocument()
})
+ it('opens the step line at the first scheduled level when only a targeted condition covers the flag', async () => {
+ useMocks({
+ get: schedulesMock([addConditionChange(25, 30), addConditionChange(50, 60)]),
+ })
+ renderWithSchedules()
+ await screen.findByText('What happens next')
+ // The mount loads a flag of its own. Set the targeted condition after that load settles.
+ act(() => {
+ featureFlagLogic(logicProps).actions.setFeatureFlag(
+ buildFeatureFlag({ active: true, rolloutPercentage: 100, properties: [PERSON_FILTER] })
+ )
+ })
+
+ const timeline = document.querySelector('[data-attr="feature-flag-schedule-timeline"]')!
+ const firstMark = timeline.querySelector('circle')!
+ expect(stepLineStart(timeline)).toEqual({
+ x: Number(firstMark.getAttribute('cx')),
+ y: Number(firstMark.getAttribute('cy')),
+ })
+ })
+
describe('approval visibility', () => {
it('shows the Needs approval tag and an approval link for a pending gated schedule', async () => {
useMocks({
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
index 8c5be4a549d3..59eca961a232 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
@@ -61,7 +61,13 @@ import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseCon
import { groupFilters } from './FeatureFlags'
import { featureFlagScheduleEditLogic } from './featureFlagScheduleEditLogic'
import { FeatureFlagVariantsForm } from './FeatureFlagVariantsForm'
-import { isSchedulePaused, maxRolloutPercentage } from './scheduleOccurrences'
+import {
+ isSchedulePaused,
+ maxRolloutPercentage,
+ maxUntargetedRolloutPercentage,
+ projectedRolloutPercentage,
+ sharedAggregationTarget,
+} from './scheduleOccurrences'
import { ScheduleTimeline } from './ScheduleTimeline'
export const DAYJS_FORMAT = 'MMMM DD, YYYY h:mm A'
@@ -487,6 +493,34 @@ export default function FeatureFlagSchedule(): JSX.Element {
const aggregationGroupTypeIndex = featureFlag.filters.aggregation_group_type_index
const scheduleFilters = { ...schedulePayload.filters, aggregation_group_type_index: aggregationGroupTypeIndex }
+ // Release condition sets are OR'd. The sets that bucket on one identifier share a hash. A condition
+ // at or below a rollout the flag already serves to everyone therefore reaches nobody new.
+ const scheduledAggregationTarget = sharedAggregationTarget(
+ schedulePayload.filters?.groups,
+ aggregationGroupTypeIndex
+ )
+ const servedOnSharedTarget = maxUntargetedRolloutPercentage(
+ featureFlag.filters.groups,
+ aggregationGroupTypeIndex,
+ scheduledAggregationTarget
+ )
+ const scheduledConditionRollout = maxRolloutPercentage(schedulePayload.filters?.groups)
+ const conditionReachesNobodyNew =
+ scheduledChangeOperation === ScheduledChangeOperationType.AddReleaseCondition &&
+ servedOnSharedTarget !== null &&
+ scheduledConditionRollout !== null &&
+ // An untouched form starts at 0%, where nobody has said what they want yet.
+ scheduledConditionRollout > 0 &&
+ scheduledConditionRollout <= servedOnSharedTarget
+ // The banner splits these across elements to survive a page translator, so it cannot also be the
+ // announced string. Both read these three parts, so the wording cannot drift between them.
+ const coveredLead = featureFlag.active
+ ? 'This flag already serves'
+ : 'This flag is disabled, but it is already set to serve'
+ const coveredTarget = aggregationLabel(scheduledAggregationTarget, true).plural
+ const coveredTail =
+ 'will not change who sees the flag. To stage a rollout, lower the existing condition first, then schedule the increases.'
+
const { variants: displayVariants, payloads: displayPayloads } = getScheduledVariantsPayloads(
featureFlag,
schedulePayload
@@ -562,7 +596,7 @@ export default function FeatureFlagSchedule(): JSX.Element {
</div>
<ScheduleTimeline
occurrences={scheduleTimelineOccurrences}
- currentRolloutPercentage={maxRolloutPercentage(featureFlag.filters.groups)}
+ currentRolloutPercentage={projectedRolloutPercentage(featureFlag.filters)}
timezone={scheduleTimezone}
/>
</div>
@@ -962,6 +996,26 @@ export default function FeatureFlagSchedule(): JSX.Element {
</div>
)}
+ {/* The banner mounts and unmounts as the rollout field changes, and a live region that
+ appears already populated is not announced. This one stays mounted and only its text
+ changes, so each change is a mutation a screen reader reads out. sr-only takes it out
+ of flow, so the empty case adds no gap to the column. */}
+ <span aria-live="polite" aria-atomic="true" className="sr-only">
+ {conditionReachesNobodyNew
+ ? `${coveredLead} ${servedOnSharedTarget}% of all ${coveredTarget}, and release conditions are combined with OR. A condition at ${scheduledConditionRollout}% ${coveredTail}`
+ : ''}
+ </span>
+ {conditionReachesNobodyNew && (
+ <LemonBanner type="warning">
+ {/* These values move while the banner stays up. Each one is therefore its own element
+ rather than a bare text node among siblings. A page-translation extension swaps such a
+ node for a <font>. React then writes the new value to the detached node. */}
+ <span>{coveredLead}</span> <span translate="no">{`${servedOnSharedTarget}%`}</span> of all{' '}
+ <span>{coveredTarget}</span>, and release conditions are combined with OR. A condition at{' '}
+ <span translate="no">{`${scheduledConditionRollout}%`}</span> {coveredTail}
+ </LemonBanner>
+ )}
+
{/* Warning when updating variants won't actually change what anyone sees */}
{scheduledChangeOperation === ScheduledChangeOperationType.UpdateVariants &&
!!featureFlag.filters.multivariate &&
diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx
index 4c926ac9594d..27b8b24b843f 100644
--- a/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx
+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.stories.tsx
@@ -35,6 +35,7 @@ function occurrence(
projected,
addedRolloutPercentage:
payload.operation === ScheduledChangeOperationType.AddReleaseCondition ? projected.rolloutPercentage : null,
+ rolloutUnchanged: false,
needsApproval,
}
}
@@ -51,6 +52,30 @@ function rolloutStep(daysFromNow: number, rollout: number, needsApproval = false
)
}
+function coveredRolloutStep(daysFromNow: number, rollout: number, needsApproval = false): ScheduleOccurrence {
+ return {
+ ...rolloutStep(daysFromNow, rollout, needsApproval),
+ projected: { active: true, rolloutPercentage: 100, variantCount: null },
+ rolloutUnchanged: true,
+ }
+}
+
+/**
+ * Marks near both edges that carry the longest label the chart can draw. Two such labels overlap
+ * when they sit close together near one edge. The plan therefore has only these two.
+ */
+export function EdgeStepLabels(): JSX.Element {
+ return (
+ <div className="max-w-3xl">
+ <ScheduleTimeline
+ occurrences={[coveredRolloutStep(1, 25, true), coveredRolloutStep(30, 100, true)]}
+ currentRolloutPercentage={100}
+ timezone="UTC"
+ />
+ </div>
+ )
+}
+
export function RolloutRamp(): JSX.Element {
return (
<div className="max-w-3xl">
@@ -92,3 +117,15 @@ export function SingleOccurrence(): JSX.Element {
/>
)
}
+
+export function CoveredRolloutRamp(): JSX.Element {
+ return (
+ <div className="max-w-3xl">
+ <ScheduleTimeline
+ occurrences={[coveredRolloutStep(1, 25), coveredRolloutStep(2, 50), coveredRolloutStep(30, 100)]}
+ currentRolloutPercentage={100}
+ timezone="UTC"
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx
index 9e97015fe7bb..f4a1045815e3 100644
--- a/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx
+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.test.tsx
@@ -15,11 +15,26 @@ function occurrence(overrides: Partial<ScheduleOccurrence> = {}): ScheduleOccurr
schedule: makeScheduledChange({ scheduled_at: '2099-08-26T10:22:00Z' }),
projected: { active: true, rolloutPercentage: 50, variantCount: null },
addedRolloutPercentage: null,
+ rolloutUnchanged: false,
needsApproval: false,
...overrides,
}
}
+function coveredStep(
+ active: boolean,
+ addedRolloutPercentage: number,
+ overrides: Partial<ScheduleOccurrence> = {}
+): ScheduleOccurrence {
+ return occurrence({
+ operation: ScheduledChangeOperationType.AddReleaseCondition,
+ addedRolloutPercentage,
+ rolloutUnchanged: true,
+ projected: { active, rolloutPercentage: 100, variantCount: null },
+ ...overrides,
+ })
+}
+
describe('ScheduleTimeline', () => {
// The component reads the wall clock to place marks, so an unpinned clock leaves the fixed
// fixture dates decades away and squashes every x onto the right edge.
@@ -78,6 +93,133 @@ describe('ScheduleTimeline', () => {
expect(screen.getByText('Next: add a condition at 10% rollout on Aug 26, 10:22 AM')).toBeInTheDocument()
})
+ it.each([
+ {
+ name: 'a flag that serves the level',
+ active: true,
+ expected:
+ 'Next: add a condition at 25% rollout, no change from the 100% the flag already serves on Aug 26, 10:22 AM',
+ },
+ {
+ name: 'a flag that is off',
+ active: false,
+ expected:
+ 'Next: add a condition at 25% rollout, no change from the 100% set on this disabled flag on Aug 26, 10:22 AM',
+ },
+ ])('summarizes a covered condition add as no change on $name', ({ active, expected }) => {
+ render(
+ <ScheduleTimeline occurrences={[coveredStep(active, 25)]} currentRolloutPercentage={100} timezone="UTC" />
+ )
+
+ expect(screen.getByText(expected)).toBeInTheDocument()
+ })
+
+ it.each([
+ {
+ name: 'a flag that serves the level',
+ active: true,
+ expectedTitle: 'This condition sits at 25%, at or below the 100% the flag already serves',
+ },
+ {
+ name: 'a flag that is off',
+ active: false,
+ expectedTitle: 'This condition sits at 25%, at or below the 100% set on this disabled flag',
+ },
+ ])(
+ 'labels a step that holds its level, so a flat line does not read as broken: $name',
+ ({ active, expectedTitle }) => {
+ const { container } = render(
+ <ScheduleTimeline
+ occurrences={[
+ coveredStep(active, 25),
+ coveredStep(active, 50, { timestamp: '2099-08-28T10:22:00Z' }),
+ ]}
+ currentRolloutPercentage={100}
+ timezone="UTC"
+ />
+ )
+
+ expect(screen.getAllByText('still 100%')).toHaveLength(2)
+ expect(container.querySelector('g > title')?.textContent).toEqual(expectedTitle)
+ }
+ )
+
+ it('drops a step label that would overlap an earlier one on the same level', () => {
+ render(
+ <ScheduleTimeline
+ occurrences={[
+ coveredStep(true, 25),
+ coveredStep(true, 50, { timestamp: '2099-08-27T10:22:00Z' }),
+ coveredStep(true, 75, { timestamp: '2099-09-24T10:22:00Z' }),
+ ]}
+ currentRolloutPercentage={100}
+ timezone="UTC"
+ />
+ )
+
+ expect(screen.getAllByText('still 100%')).toHaveLength(2)
+ })
+
+ it('keeps a dropped step label reachable as the mark title', () => {
+ // The drop rule reaches any two levels within about 10 points, not only equal ones: one font
+ // size is 9 units and the plot spends 0.9 units per point. These two land 4.5 units apart
+ // vertically and overlap horizontally, so the 100% label is dropped. Neither step needs
+ // approval or holds its level, so without the title its mark carries no text at all.
+ const step = (timestamp: string, rollout: number): ScheduleOccurrence =>
+ occurrence({
+ timestamp,
+ operation: ScheduledChangeOperationType.AddReleaseCondition,
+ addedRolloutPercentage: rollout,
+ projected: { active: true, rolloutPercentage: rollout, variantCount: null },
+ })
+ const { container } = render(
+ <ScheduleTimeline
+ occurrences={[
+ step('2099-08-25T11:22:00Z', 95),
+ step('2099-08-25T12:22:00Z', 100),
+ step('2099-09-24T10:22:00Z', 100),
+ ]}
+ currentRolloutPercentage={90}
+ timezone="UTC"
+ />
+ )
+
+ expect(screen.getByText('95%')).toBeInTheDocument()
+ expect(Array.from(container.querySelectorAll('g > title')).map((node) => node.textContent)).toEqual([
+ '100% rollout',
+ ])
+ })
+
+ it('anchors a step label at its mark near either edge, so the text stays in the plot', () => {
+ const step = (timestamp: string, rollout: number): ScheduleOccurrence =>
+ occurrence({
+ timestamp,
+ operation: ScheduledChangeOperationType.AddReleaseCondition,
+ addedRolloutPercentage: rollout,
+ projected: { active: true, rolloutPercentage: rollout, variantCount: null },
+ needsApproval: true,
+ })
+ const { container } = render(
+ <ScheduleTimeline
+ occurrences={[
+ step('2099-08-25T11:22:00Z', 25),
+ step('2099-08-27T12:22:00Z', 50),
+ // 90 of the plan's 100 hours, so x is 530.8. That sits inside the end band at the
+ // current pad and outside it at the old 30, which is what pins the constant.
+ step('2099-08-29T04:22:00Z', 75),
+ step('2099-08-29T14:22:00Z', 100),
+ ]}
+ currentRolloutPercentage={10}
+ timezone="UTC"
+ />
+ )
+
+ const anchors = Array.from(container.querySelectorAll('text'))
+ .filter((node) => node.textContent?.includes('needs approval'))
+ .map((node) => node.getAttribute('text-anchor'))
+ expect(anchors).toEqual(['start', 'middle', 'end', 'end'])
+ })
+
it('renders the step chart for two or more occurrences', () => {
const { container } = render(
<ScheduleTimeline
@@ -96,6 +238,7 @@ describe('ScheduleTimeline', () => {
expect(container.querySelector('svg')).toBeInTheDocument()
expect(screen.queryByText(/^Next:/)).not.toBeInTheDocument()
+ expect(screen.getByText(/^The line shows/)).toBeInTheDocument()
})
it('dashes the jump of an approval-blocked step, and not the level before it', () => {
@@ -136,7 +279,7 @@ describe('ScheduleTimeline', () => {
render(
<ScheduleTimeline
occurrences={[
- occurrence(),
+ occurrence({ projected: { active: true, rolloutPercentage: null, variantCount: null } }),
occurrence({
timestamp: '2099-08-28T10:22:00Z',
operation: ScheduledChangeOperationType.AddReleaseCondition,
@@ -150,6 +293,34 @@ describe('ScheduleTimeline', () => {
expect(screen.getByText('Condition')).toBeInTheDocument()
expect(screen.queryByText('0 variants')).not.toBeInTheDocument()
+ expect(screen.getByText(/^No rollout line is shown/)).toBeInTheDocument()
+ // The last occurrence always maps to the plot edge, where a centered label leaves the
+ // viewBox. Anchoring is what keeps it readable, so pin it here.
+ expect(screen.getByText('Condition')).toHaveAttribute('text-anchor', 'end')
+ })
+
+ it('says the line counts reach when the only plottable step is the last occurrence', () => {
+ // The step has no level before it to run from, and the trailing run stops at the plot edge
+ // this mark already sits on, so the chart draws a labelled mark and no segment.
+ render(
+ <ScheduleTimeline
+ occurrences={[
+ occurrence({ projected: { active: true, rolloutPercentage: null, variantCount: null } }),
+ occurrence({
+ timestamp: '2099-08-28T10:22:00Z',
+ operation: ScheduledChangeOperationType.AddReleaseCondition,
+ addedRolloutPercentage: 25,
+ projected: { active: true, rolloutPercentage: 25, variantCount: null },
+ }),
+ ]}
+ currentRolloutPercentage={null}
+ timezone="UTC"
+ />
+ )
+
+ expect(screen.getByText('25%')).toBeInTheDocument()
+ expect(screen.getByText(/^The line shows/)).toBeInTheDocument()
+ expect(screen.queryByText(/^No rollout line is shown/)).not.toBeInTheDocument()
})
it('exposes the plan and a focus stop for a user without a mouse', () => {
diff --git a/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx b/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx
index f0eac082bfef..fced2ff71a17 100644
--- a/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx
+++ b/frontend/src/scenes/feature-flags/ScheduleTimeline.tsx
@@ -3,7 +3,7 @@ import { pluralize } from 'lib/utils/strings'
import { ScheduledChangeOperationType } from '~/types'
-import { ScheduleOccurrence } from './scheduleOccurrences'
+import { ScheduleOccurrence, ScheduleProjectedState } from './scheduleOccurrences'
const WIDTH = 600
const HEIGHT = 140
@@ -17,6 +17,28 @@ const TIME_LABEL_MIN_GAP = 40
const TOP_LABEL_MIN_GAP = 40
/** How far the second lane sits above the first. Tuned against the 9px label size. */
const TOP_LABEL_LANE_OFFSET = 10
+const LABEL_FONT_SIZE = 9
+/** Average width of one label character at the 9px size, measured in a browser. */
+const LABEL_CHAR_WIDTH = 4.5
+/**
+ * The longest string either builder can produce. stepLabel and markerLabel tie at 27 characters, the
+ * other being "3 variants (needs approval)".
+ */
+const WIDEST_LABEL = 'still 100% (needs approval)'
+/**
+ * Inside this distance from an edge, a centered label leaves the plot. Half the widest label, plus
+ * headroom for a wider fallback font. Derived rather than written down, so lengthening either
+ * builder's longest string carries through here on its own.
+ */
+const LABEL_EDGE_PAD = (WIDEST_LABEL.length * LABEL_CHAR_WIDTH) / 2 + 5
+
+type LabelAnchor = 'start' | 'middle' | 'end'
+
+function describeCoveringLevel(projected: ScheduleProjectedState): string {
+ return projected.active
+ ? `${projected.rolloutPercentage}% the flag already serves`
+ : `${projected.rolloutPercentage}% set on this disabled flag`
+}
function describeOccurrence(occurrence: ScheduleOccurrence): string {
const { operation, projected, addedRolloutPercentage } = occurrence
@@ -24,11 +46,13 @@ function describeOccurrence(occurrence: ScheduleOccurrence): string {
return projected.active ? 'enabled' : 'disabled'
}
if (operation === ScheduledChangeOperationType.AddReleaseCondition) {
+ if (addedRolloutPercentage === null) {
+ return 'add a condition'
+ }
// Describe the condition this change adds, not the flag's projected max rollout: the change
// appends a condition set, so an existing higher one would otherwise be misreported here.
- return addedRolloutPercentage !== null
- ? `add a condition at ${addedRolloutPercentage}% rollout`
- : 'add a condition'
+ const added = `add a condition at ${addedRolloutPercentage}% rollout`
+ return occurrence.rolloutUnchanged ? `${added}, no change from the ${describeCoveringLevel(projected)}` : added
}
return `switch to ${pluralize(occurrence.projected.variantCount ?? 0, 'variant')}`
}
@@ -70,6 +94,56 @@ function yForRollout(rollout: number): number {
return MARGIN.top + ((100 - rollout) * PLOT_HEIGHT) / 100
}
+/**
+ * `unlabelledRollout` is the level of a step whose label was dropped for overlapping an earlier one.
+ * Without it such a mark is a bare dot: the drop takes away the only reading of its level, and a
+ * plain step has no other reason to carry a title.
+ */
+function markTitle(occurrence: ScheduleOccurrence, unlabelledRollout: number | null): string {
+ return [
+ unlabelledRollout !== null ? `${unlabelledRollout}% rollout` : '',
+ occurrence.needsApproval ? 'Needs approval' : '',
+ occurrence.rolloutUnchanged
+ ? `This condition sits at ${occurrence.addedRolloutPercentage}%, at or below the ${describeCoveringLevel(occurrence.projected)}`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('. ')
+}
+
+function stepLabel(occurrence: ScheduleOccurrence, rollout: number): string {
+ const level = occurrence.rolloutUnchanged ? `still ${rollout}%` : `${rollout}%`
+ return occurrence.needsApproval ? `${level} (needs approval)` : level
+}
+
+/**
+ * Near an edge a label ends or starts at its mark, because the SVG clips what leaves the viewBox.
+ * Both step labels and marker labels anchor through here.
+ */
+function labelAnchor(x: number): LabelAnchor {
+ if (x > MARGIN.left + PLOT_WIDTH - LABEL_EDGE_PAD) {
+ return 'end'
+ }
+ if (x < MARGIN.left + LABEL_EDGE_PAD) {
+ return 'start'
+ }
+ return 'middle'
+}
+
+function labelExtent(x: number, anchor: LabelAnchor, text: string): { left: number; right: number } {
+ const width = text.length * LABEL_CHAR_WIDTH
+ const left = anchor === 'start' ? x : anchor === 'end' ? x - width : x - width / 2
+ return { left, right: left + width }
+}
+
+interface PlacedLabel {
+ text: string
+ y: number
+ anchor: LabelAnchor
+ left: number
+ right: number
+}
+
/** Where each occurrence's marks and labels land, resolved before render so the JSX map stays pure. */
interface OccurrenceLayout {
x: number
@@ -77,6 +151,14 @@ interface OccurrenceLayout {
timeLabel: string | null
/** Alternates between two heights when top-lane markers land near the same x. */
topLabelY: number
+ /** The step mark's y. Null for a marker. */
+ stepY: number | null
+ /**
+ * Null for a marker, and for a step label that would overlap an earlier step label whose baseline
+ * sits within one font size of its own. One font size is 9 units and the plot spends 0.9 units per
+ * rollout point, so two steps less than about 10 points apart on nearby dates stack their text.
+ */
+ placedStepLabel: PlacedLabel | null
}
/**
@@ -92,7 +174,7 @@ export function ScheduleTimeline({
timezone,
}: {
occurrences: ScheduleOccurrence[]
- /** The flag's max rollout across condition sets today, the step line's starting level. */
+ /** What the flag reaches today, the step line's starting level. See projectedRolloutPercentage. */
currentRolloutPercentage: number | null
timezone: string
}): JSX.Element | null {
@@ -122,6 +204,7 @@ export function ScheduleTimeline({
let lastTimeLabelX = -Infinity
let lastTopLabelX = -Infinity
let topLabelLane = 0
+ const shownStepLabels: PlacedLabel[] = []
occurrences.forEach((occurrence, index) => {
const x = xFor(times[index])
const timeLabel = x - lastTimeLabelX >= TIME_LABEL_MIN_GAP ? relativeLabel(times[index], now) : null
@@ -129,10 +212,25 @@ export function ScheduleTimeline({
lastTimeLabelX = x
}
let topLabelY = MARGIN.top - 8
- const onStepLine =
- occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition &&
- occurrence.projected.rolloutPercentage !== null
- if (!onStepLine) {
+ let stepY: number | null = null
+ let placedStepLabel: PlacedLabel | null = null
+ const rollout = occurrence.projected.rolloutPercentage
+ if (occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition && rollout !== null) {
+ stepY = yForRollout(rollout)
+ const text = stepLabel(occurrence, rollout)
+ const anchor = labelAnchor(x)
+ const label = { text, y: stepY - 7, anchor, ...labelExtent(x, anchor, text) }
+ const collides = shownStepLabels.some(
+ (shown) =>
+ Math.abs(shown.y - label.y) < LABEL_FONT_SIZE &&
+ label.left < shown.right &&
+ label.right > shown.left
+ )
+ if (!collides) {
+ shownStepLabels.push(label)
+ placedStepLabel = label
+ }
+ } else {
// Two lanes clear the common case of a pair landing together. Three or more markers
// inside one gap still overlap, because the lane alternates rather than tracks every
// occupied slot. The occurrence cap keeps that rare.
@@ -140,7 +238,7 @@ export function ScheduleTimeline({
lastTopLabelX = x
topLabelY -= topLabelLane * TOP_LABEL_LANE_OFFSET
}
- layouts.push({ x, timeLabel, topLabelY })
+ layouts.push({ x, timeLabel, topLabelY, stepY, placedStepLabel })
})
// Step-line segments, split so an approval-blocked step dashes its jump and not its run.
@@ -175,6 +273,13 @@ export function ScheduleTimeline({
})
}
+ // A known level is not the same as a drawn segment. A plan whose only plottable step is its last
+ // occurrence draws a labelled mark and no segment: the step has no level before it to run from,
+ // and the trailing run stops at the plot edge the mark already sits on. Reading the segments here
+ // would tell that reader no line is drawn because every condition is targeted, beside a mark
+ // proving otherwise.
+ const hasRolloutLevel = currentRolloutPercentage !== null || layouts.some((layout) => layout.stepY !== null)
+
// role="img" makes the chart a single leaf node, so a screen reader never descends into the
// marks and hears no date, level, or approval state. The label has to carry the plan itself.
const chartLabel = `Timeline of ${occurrences.length} upcoming scheduled changes: ${occurrences
@@ -187,132 +292,144 @@ export function ScheduleTimeline({
.join(', then ')}`
return (
- // The chart scrolls horizontally rather than scale its 9-unit labels below legibility. The
- // minimum width is WIDTH itself, so at the floor one viewBox unit is one pixel and the
- // labels hold at 9px. A smaller floor would scale them down by the same ratio.
- // A plain div with overflow takes no focus and no arrow keys, so the scroll region needs a
- // focus stop of its own to be reachable without a mouse.
- <div
- className="flex flex-col gap-1 overflow-x-auto"
- tabIndex={0}
- role="group"
- aria-label="Scrollable schedule timeline"
- data-attr="feature-flag-schedule-timeline"
- >
- <svg
- viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
- className="w-full max-w-3xl"
- style={{ minWidth: WIDTH }}
- role="img"
- aria-label={chartLabel}
+ <div className="flex flex-col gap-1">
+ {/* The chart scrolls horizontally rather than scale its 9-unit labels below legibility.
+ The minimum width is WIDTH itself, so at the floor one viewBox unit is one pixel and
+ the labels hold at 9px. A smaller floor would scale them down by the same ratio.
+ A plain div with overflow takes no focus and no arrow keys, so the scroll region
+ needs a focus stop of its own to be reachable without a mouse. */}
+ <div
+ className="overflow-x-auto"
+ tabIndex={0}
+ role="group"
+ aria-label="Scrollable schedule timeline"
+ data-attr="feature-flag-schedule-timeline"
>
- {[0, 50, 100].map((rollout) => (
- <g key={rollout}>
- <line
- x1={MARGIN.left}
- x2={MARGIN.left + PLOT_WIDTH}
- y1={yForRollout(rollout)}
- y2={yForRollout(rollout)}
- stroke="var(--color-border-primary)"
- strokeWidth={rollout === 0 ? 1 : 0.5}
- />
- <text
- x={MARGIN.left - 4}
- y={yForRollout(rollout) + 3}
- textAnchor="end"
- fontSize={9}
- fill="var(--color-text-secondary)"
- >
- {rollout}%
- </text>
- </g>
- ))}
-
- {stepSegments.map((segment, index) => (
- <path
- key={index}
- d={segment.path}
- fill="none"
- stroke="var(--data-color-1)"
- strokeWidth={2}
- strokeDasharray={segment.blocked ? '4 3' : undefined}
- opacity={segment.blocked ? 0.5 : 1}
- />
- ))}
-
- {occurrences.map((occurrence, index) => {
- const { x, timeLabel, topLabelY } = layouts[index]
- const blocked = occurrence.needsApproval
- const isRolloutStep = occurrence.operation === ScheduledChangeOperationType.AddReleaseCondition
- const rollout = occurrence.projected.rolloutPercentage
- return (
- <g key={`${occurrence.schedule.id}-${occurrence.timestamp}`} opacity={blocked ? 0.5 : 1}>
- {blocked && <title>Needs approval</title>}
+ <svg
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ className="w-full max-w-3xl"
+ style={{ minWidth: WIDTH }}
+ role="img"
+ aria-label={chartLabel}
+ >
+ {[0, 50, 100].map((rollout) => (
+ <g key={rollout}>
<line
- x1={x}
- x2={x}
- y1={BASELINE_Y}
- y2={BASELINE_Y + 4}
+ x1={MARGIN.left}
+ x2={MARGIN.left + PLOT_WIDTH}
+ y1={yForRollout(rollout)}
+ y2={yForRollout(rollout)}
stroke="var(--color-border-primary)"
+ strokeWidth={rollout === 0 ? 1 : 0.5}
/>
- {isRolloutStep && rollout !== null ? (
- <>
- <circle
- cx={x}
- cy={yForRollout(rollout)}
- r={3.5}
- fill="var(--data-color-1)"
- stroke="var(--color-bg-surface-primary)"
- strokeWidth={1.5}
- strokeDasharray={blocked ? '2 2' : undefined}
- />
- <text
- x={x}
- y={yForRollout(rollout) - 7}
- textAnchor="middle"
- fontSize={9}
- fill="var(--color-text-secondary)"
- >
- {rollout}%{blocked ? ' (needs approval)' : ''}
- </text>
- </>
- ) : (
- <>
- <line
- x1={x}
- x2={x}
- y1={MARGIN.top - 4}
- y2={BASELINE_Y}
- stroke="var(--color-border-primary)"
- strokeDasharray="2 3"
- />
+ <text
+ x={MARGIN.left - 4}
+ y={yForRollout(rollout) + 3}
+ textAnchor="end"
+ fontSize={LABEL_FONT_SIZE}
+ fill="var(--color-text-secondary)"
+ >
+ {rollout}%
+ </text>
+ </g>
+ ))}
+
+ {stepSegments.map((segment, index) => (
+ <path
+ key={index}
+ d={segment.path}
+ fill="none"
+ stroke="var(--data-color-1)"
+ strokeWidth={2}
+ strokeDasharray={segment.blocked ? '4 3' : undefined}
+ opacity={segment.blocked ? 0.5 : 1}
+ />
+ ))}
+
+ {occurrences.map((occurrence, index) => {
+ const { x, timeLabel, topLabelY, stepY, placedStepLabel } = layouts[index]
+ const blocked = occurrence.needsApproval
+ // A browser shows only the first <title> child as the hover tooltip.
+ const title = markTitle(
+ occurrence,
+ stepY !== null && !placedStepLabel ? occurrence.projected.rolloutPercentage : null
+ )
+ return (
+ <g key={`${occurrence.schedule.id}-${occurrence.timestamp}`} opacity={blocked ? 0.5 : 1}>
+ {title && <title>{title}</title>}
+ <line
+ x1={x}
+ x2={x}
+ y1={BASELINE_Y}
+ y2={BASELINE_Y + 4}
+ stroke="var(--color-border-primary)"
+ />
+ {stepY !== null ? (
+ <>
+ <circle
+ cx={x}
+ cy={stepY}
+ r={3.5}
+ fill="var(--data-color-1)"
+ stroke="var(--color-bg-surface-primary)"
+ strokeWidth={1.5}
+ strokeDasharray={blocked ? '2 2' : undefined}
+ />
+ {placedStepLabel && (
+ <text
+ x={x}
+ y={placedStepLabel.y}
+ textAnchor={placedStepLabel.anchor}
+ fontSize={LABEL_FONT_SIZE}
+ fill="var(--color-text-secondary)"
+ >
+ {placedStepLabel.text}
+ </text>
+ )}
+ </>
+ ) : (
+ <>
+ <line
+ x1={x}
+ x2={x}
+ y1={MARGIN.top - 4}
+ y2={BASELINE_Y}
+ stroke="var(--color-border-primary)"
+ strokeDasharray="2 3"
+ />
+ <text
+ x={x}
+ y={topLabelY}
+ textAnchor={labelAnchor(x)}
+ fontSize={LABEL_FONT_SIZE}
+ fill="var(--color-text-secondary)"
+ >
+ {markerLabel(occurrence)}
+ {blocked ? ' (needs approval)' : ''}
+ </text>
+ </>
+ )}
+ {timeLabel && (
<text
x={x}
- y={topLabelY}
+ y={BASELINE_Y + 15}
textAnchor="middle"
- fontSize={9}
+ fontSize={LABEL_FONT_SIZE}
fill="var(--color-text-secondary)"
>
- {markerLabel(occurrence)}
- {blocked ? ' (needs approval)' : ''}
+ {timeLabel}
</text>
- </>
- )}
- {timeLabel && (
- <text
- x={x}
- y={BASELINE_Y + 15}
- textAnchor="middle"
- fontSize={9}
- fill="var(--color-text-secondary)"
- >
- {timeLabel}
- </text>
- )}
- </g>
- )
- })}
- </svg>
+ )}
+ </g>
+ )
+ })}
+ </svg>
+ </div>
+ <p className="text-xs text-muted m-0">
+ {hasRolloutLevel
+ ? 'The line shows how much of your audience the flag reaches. It does not count conditions that target specific users, or conditions set to a different audience type, because their reach depends on how many match them.'
+ : 'No rollout line is shown because every condition targets specific users or a different audience type. Their reach depends on how many match them.'}
+ </p>
</div>
)
}
diff --git a/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts b/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts
index 0ad1915ef0f7..5e87554a0aed 100644
--- a/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts
+++ b/frontend/src/scenes/feature-flags/scheduleOccurrences.test.ts
@@ -1,7 +1,11 @@
import { dayjs } from 'lib/dayjs'
import {
+ AnyPropertyFilter,
+ FeatureFlagGroupType,
FeatureFlagType,
+ PropertyFilterType,
+ PropertyOperator,
RecurrenceInterval,
ScheduledChangeOperationType,
ScheduledChangePayload,
@@ -10,7 +14,12 @@ import {
} from '~/types'
import { makeScheduledChange, resetScheduledChangeIds } from './makeScheduledChange'
-import { OCCURRENCE_CAP, expandScheduleOccurrences } from './scheduleOccurrences'
+import {
+ OCCURRENCE_CAP,
+ expandScheduleOccurrences,
+ maxUntargetedRolloutPercentage,
+ sharedAggregationTarget,
+} from './scheduleOccurrences'
const NOW = dayjs('2026-01-01T00:00:00Z')
@@ -18,10 +27,30 @@ function change(overrides: Partial<ScheduledChangeType> & { payload: ScheduledCh
return makeScheduledChange({ scheduled_at: NOW.add(1, 'day').toISOString(), ...overrides })
}
-function conditionPayload(rolloutPercentage: number): ScheduledChangePayload {
+const PERSON_FILTER: AnyPropertyFilter = {
+ key: 'email',
+ value: 'a',
+ type: PropertyFilterType.Person,
+ operator: PropertyOperator.Exact,
+}
+
+function conditionPayload(
+ rolloutPercentage: number,
+ properties: AnyPropertyFilter[] = [],
+ aggregationGroupTypeIndex?: number | null
+): ScheduledChangePayload {
return {
operation: ScheduledChangeOperationType.AddReleaseCondition,
- value: { groups: [{ properties: [], rollout_percentage: rolloutPercentage, variant: null }] },
+ value: {
+ groups: [
+ {
+ properties,
+ rollout_percentage: rolloutPercentage,
+ variant: null,
+ aggregation_group_type_index: aggregationGroupTypeIndex,
+ },
+ ],
+ },
}
}
@@ -58,6 +87,7 @@ describe('expandScheduleOccurrences', () => {
expect(occurrences.map((o) => o.projected.rolloutPercentage)).toEqual([25, 50, 75, 100])
expect(occurrences.map((o) => o.addedRolloutPercentage)).toEqual([25, 50, 75, 100])
+ expect(occurrences.map((o) => o.rolloutUnchanged)).toEqual([false, false, false, false])
expect(occurrences.map((o) => o.timestamp)).toEqual([
NOW.add(1, 'day').toISOString(),
NOW.add(2, 'day').toISOString(),
@@ -66,6 +96,136 @@ describe('expandScheduleOccurrences', () => {
])
})
+ it.each([
+ {
+ name: 'a flag that already serves everyone',
+ current: 100,
+ adds: [25, 50, 100],
+ expected: [true, true, true],
+ },
+ { name: 'a ramp that overtakes the current level', current: 30, adds: [25, 50], expected: [true, false] },
+ { name: 'an add that matches the current level', current: 25, adds: [25], expected: [true] },
+ {
+ name: 'an add covered by an earlier scheduled add',
+ current: 10,
+ adds: [50, 30],
+ expected: [false, true],
+ },
+ ])('marks a covered condition add as no change: $name', ({ current, adds, expected }) => {
+ const schedules = adds.map((rollout, index) =>
+ change({ payload: conditionPayload(rollout), scheduled_at: NOW.add(index + 1, 'day').toISOString() })
+ )
+
+ const occurrences = expandScheduleOccurrences(
+ schedules,
+ flag({ filters: { groups: [{ properties: [], rollout_percentage: current, variant: null }] } }),
+ NOW
+ )
+
+ expect(occurrences.map((o) => o.rolloutUnchanged)).toEqual(expected)
+ })
+
+ it('ignores property-narrowed condition sets in the projected reach and the no-change flag', () => {
+ const schedules = [
+ change({ payload: conditionPayload(100, [PERSON_FILTER]), scheduled_at: NOW.add(1, 'day').toISOString() }),
+ change({ payload: conditionPayload(50), scheduled_at: NOW.add(2, 'day').toISOString() }),
+ // A narrowed add is still judged on its raw percentage, because it buckets on the same
+ // hash as the untargeted set that already covers it.
+ change({ payload: conditionPayload(25, [PERSON_FILTER]), scheduled_at: NOW.add(3, 'day').toISOString() }),
+ ]
+
+ const occurrences = expandScheduleOccurrences(
+ schedules,
+ flag({
+ filters: {
+ groups: [
+ { properties: [PERSON_FILTER], rollout_percentage: 100, variant: null },
+ { properties: [], rollout_percentage: 10, variant: null },
+ ],
+ multivariate: null,
+ },
+ }),
+ NOW
+ )
+
+ expect(occurrences.map((o) => o.rolloutUnchanged)).toEqual([false, false, true])
+ expect(occurrences.map((o) => o.projected.rolloutPercentage)).toEqual([10, 50, 50])
+ })
+
+ const aggregationCases: {
+ name: string
+ flagAggregation: number | null | undefined
+ coveringAggregation: number | null | undefined
+ addedAggregation?: number | null
+ extraGroups?: FeatureFlagGroupType[]
+ expected: boolean
+ expectedRollout: number | null
+ }[] = [
+ {
+ name: 'a covering set on another aggregation target',
+ flagAggregation: undefined,
+ coveringAggregation: 0,
+ expected: false,
+ expectedRollout: 25,
+ },
+ {
+ name: 'a covering set that shares the flag-level group target',
+ flagAggregation: 0,
+ coveringAggregation: undefined,
+ expected: true,
+ expectedRollout: 100,
+ },
+ {
+ name: 'an added set on another aggregation target',
+ flagAggregation: undefined,
+ coveringAggregation: undefined,
+ addedAggregation: 0,
+ expected: false,
+ expectedRollout: 100,
+ },
+ {
+ name: 'a covering set on a target the line does not plot',
+ flagAggregation: null,
+ coveringAggregation: 0,
+ addedAggregation: 0,
+ extraGroups: [
+ { properties: [], rollout_percentage: 10, variant: null, aggregation_group_type_index: null },
+ ],
+ expected: false,
+ expectedRollout: 10,
+ },
+ ]
+
+ it.each(aggregationCases)(
+ 'judges an added condition against $name: no change=$expected',
+ ({ flagAggregation, coveringAggregation, addedAggregation, extraGroups = [], expected, expectedRollout }) => {
+ const schedules = [change({ payload: conditionPayload(25, [], addedAggregation) })]
+
+ const occurrences = expandScheduleOccurrences(
+ schedules,
+ flag({
+ filters: {
+ groups: [
+ {
+ properties: [],
+ rollout_percentage: 100,
+ variant: null,
+ aggregation_group_type_index: coveringAggregation,
+ },
+ ...extraGroups,
+ ],
+ aggregation_group_type_index: flagAggregation,
+ multivariate: null,
+ },
+ }),
+ NOW
+ )
+
+ expect(occurrences[0].rolloutUnchanged).toBe(expected)
+ expect(occurrences[0].projected.rolloutPercentage).toBe(expectedRollout)
+ }
+ )
+
it('carries status, rollout, and variant projections through a mixed plan', () => {
const schedules = [
change({
@@ -95,6 +255,7 @@ describe('expandScheduleOccurrences', () => {
{ active: false, rolloutPercentage: 10, variantCount: null },
{ active: false, rolloutPercentage: 10, variantCount: 2 },
])
+ expect(occurrences.map((o) => o.rolloutUnchanged)).toEqual([false, true, false])
})
it.each([
@@ -381,3 +542,93 @@ describe('expandScheduleOccurrences', () => {
expect(occurrences[0].timestamp).toEqual('2026-01-30T09:00:00.000Z')
})
})
+
+describe('maxUntargetedRolloutPercentage', () => {
+ const cases: {
+ name: string
+ groups: FeatureFlagGroupType[]
+ flagAggregation?: number | null
+ target: number | null | undefined
+ expected: number | null
+ }[] = [
+ {
+ name: 'ignores a condition set a property filter narrows',
+ groups: [
+ { properties: [PERSON_FILTER], rollout_percentage: 100, variant: null },
+ { properties: [], rollout_percentage: 20, variant: null },
+ ],
+ target: null,
+ expected: 20,
+ },
+ {
+ name: 'reads a missing rollout as everyone',
+ groups: [{ properties: [], rollout_percentage: null, variant: null }],
+ target: null,
+ expected: 100,
+ },
+ {
+ name: 'returns null when every set is narrowed',
+ groups: [{ properties: [PERSON_FILTER], rollout_percentage: 100, variant: null }],
+ target: null,
+ expected: null,
+ },
+ {
+ name: 'ignores a condition set that targets a group type',
+ groups: [
+ { properties: [], rollout_percentage: 100, variant: null, aggregation_group_type_index: 0 },
+ { properties: [], rollout_percentage: 20, variant: null },
+ ],
+ target: null,
+ expected: 20,
+ },
+ {
+ name: 'measures a condition set that inherits the flag-level group target',
+ groups: [{ properties: [], rollout_percentage: 60, variant: null }],
+ flagAggregation: 0,
+ target: 0,
+ expected: 60,
+ },
+ {
+ name: 'returns null when the target is unknown',
+ groups: [{ properties: [], rollout_percentage: 60, variant: null }],
+ target: undefined,
+ expected: null,
+ },
+ ]
+
+ it.each(cases)('$name', ({ groups, flagAggregation, target, expected }) => {
+ expect(maxUntargetedRolloutPercentage(groups, flagAggregation, target)).toEqual(expected)
+ })
+})
+
+describe('sharedAggregationTarget', () => {
+ const cases: {
+ name: string
+ groups: FeatureFlagGroupType[]
+ flagAggregation?: number | null
+ expected: number | null | undefined
+ }[] = [
+ {
+ name: 'reads the flag-level target when every set inherits it',
+ groups: [
+ { properties: [], rollout_percentage: 100, variant: null },
+ { properties: [], rollout_percentage: 50, variant: null },
+ ],
+ flagAggregation: 0,
+ expected: 0,
+ },
+ {
+ name: 'returns undefined when the sets target different identifiers',
+ groups: [
+ { properties: [], rollout_percentage: 100, variant: null, aggregation_group_type_index: 0 },
+ { properties: [], rollout_percentage: 50, variant: null, aggregation_group_type_index: null },
+ ],
+ expected: undefined,
+ },
+ { name: 'returns undefined when there are no sets', groups: [], expected: undefined },
+ ]
+
+ it.each(cases)('$name', ({ groups, flagAggregation, expected }) => {
+ expect(sharedAggregationTarget(groups, flagAggregation)).toEqual(expected)
+ })
+})
diff --git a/frontend/src/scenes/feature-flags/scheduleOccurrences.ts b/frontend/src/scenes/feature-flags/scheduleOccurrences.ts
index aa77c60cba45..58f3de440303 100644
--- a/frontend/src/scenes/feature-flags/scheduleOccurrences.ts
+++ b/frontend/src/scenes/feature-flags/scheduleOccurrences.ts
@@ -1,6 +1,7 @@
import { Dayjs, dayjs } from 'lib/dayjs'
import {
+ FeatureFlagConfig,
FeatureFlagGroupType,
FeatureFlagType,
RecurrenceInterval,
@@ -9,10 +10,12 @@ import {
ScheduledChangeType,
} from '~/types'
+import { resolveAggregationGroupTypeIndex } from './aggregation'
+
/** Flag state as projected after a scheduled change occurrence has applied. */
export interface ScheduleProjectedState {
active: boolean
- /** Max rollout percentage across release condition sets. Null when no condition sets exist. */
+ /** What the flag reaches on its own aggregation target. See maxUntargetedRolloutPercentage. */
rolloutPercentage: number | null
/** Null for flags with no variants. */
variantCount: number | null
@@ -26,6 +29,12 @@ export interface ScheduleOccurrence {
projected: ScheduleProjectedState
/** Max rollout of the condition this occurrence adds; null for other operations. */
addedRolloutPercentage: number | null
+ /**
+ * True when this occurrence adds a condition on the flag-level target at or below the projected
+ * rollout on that target. The flag does not have to be active. Such a condition reaches nobody new,
+ * so the projected rollout holds its level. False for every other operation.
+ */
+ rolloutUnchanged: boolean
/** The occurrence will be skipped at fire time unless its approval request is approved first. */
needsApproval: boolean
}
@@ -66,6 +75,63 @@ export function maxRolloutPercentage(groups: FeatureFlagGroupType[] | undefined)
return Math.max(...groups.map((group) => group.rollout_percentage ?? 100))
}
+/**
+ * The aggregation target every one of these condition sets buckets on, or undefined when they do
+ * not share one.
+ */
+export function sharedAggregationTarget(
+ groups: FeatureFlagGroupType[] | undefined,
+ flagAggregationGroupTypeIndex: number | null | undefined
+): number | null | undefined {
+ const targets = new Set(
+ (groups ?? []).map((group) =>
+ resolveAggregationGroupTypeIndex(group.aggregation_group_type_index, flagAggregationGroupTypeIndex)
+ )
+ )
+ return targets.size === 1 ? [...targets][0] : undefined
+}
+
+/**
+ * Max rollout across the condition sets that no property filter narrows and that bucket on
+ * `targetAggregationGroupTypeIndex`. The result is a share of everyone that a condition on that
+ * target reaches, not a share of a segment.
+ */
+export function maxUntargetedRolloutPercentage(
+ groups: FeatureFlagGroupType[] | undefined,
+ flagAggregationGroupTypeIndex: number | null | undefined,
+ targetAggregationGroupTypeIndex: number | null | undefined
+): number | null {
+ if (targetAggregationGroupTypeIndex === undefined) {
+ return null
+ }
+ return maxRolloutPercentage(
+ groups?.filter(
+ (group) =>
+ !group.properties?.length &&
+ resolveAggregationGroupTypeIndex(group.aggregation_group_type_index, flagAggregationGroupTypeIndex) ===
+ targetAggregationGroupTypeIndex
+ )
+ )
+}
+
+/**
+ * What the flag reaches on its own aggregation target.
+ *
+ * FeatureFlagSchedule passes this value to ScheduleTimeline as the step line's starting level.
+ * expandScheduleOccurrences starts its projected steps from the same value. Both must call this
+ * function. If one of them counted every condition set, a property-filtered set would lift only that
+ * side. The chart would then draw a gain or a loss of reach that the flag never makes.
+ */
+export function projectedRolloutPercentage(
+ filters: Pick<FeatureFlagConfig, 'groups' | 'aggregation_group_type_index'>
+): number | null {
+ return maxUntargetedRolloutPercentage(
+ filters.groups,
+ filters.aggregation_group_type_index,
+ resolveAggregationGroupTypeIndex(undefined, filters.aggregation_group_type_index)
+ )
+}
+
/** A paused recurring schedule keeps its recurrence config but has is_recurring=false. */
export function isSchedulePaused(sc: ScheduledChangeType): boolean {
return !sc.is_recurring && (!!sc.recurrence_interval || !!sc.cron_expression)
@@ -171,21 +237,32 @@ export function expandScheduleOccurrences(
raw.sort((a, b) => a.at.valueOf() - b.at.valueOf() || a.schedule.id - b.schedule.id)
let active = flag.active
- let rolloutPercentage = maxRolloutPercentage(flag.filters.groups)
+ const flagAggregation = flag.filters.aggregation_group_type_index
+ const flagTarget = resolveAggregationGroupTypeIndex(undefined, flagAggregation)
+ let rolloutPercentage = projectedRolloutPercentage(flag.filters)
let variantCount = flag.filters.multivariate?.variants.length ?? null
return raw.slice(0, OCCURRENCE_CAP).map(({ at, schedule, isFirst }) => {
const { payload } = schedule
let addedRolloutPercentage: number | null = null
+ let rolloutUnchanged = false
if (payload.operation === ScheduledChangeOperationType.UpdateStatus) {
active = payload.value
} else if (payload.operation === ScheduledChangeOperationType.AddReleaseCondition) {
- addedRolloutPercentage = maxRolloutPercentage(payload.value.groups)
- if (addedRolloutPercentage !== null) {
- rolloutPercentage =
- rolloutPercentage === null
- ? addedRolloutPercentage
- : Math.max(rolloutPercentage, addedRolloutPercentage)
+ const addedGroups = payload.value.groups
+ addedRolloutPercentage = maxRolloutPercentage(addedGroups)
+ // Only sets on the added condition's own target can cover it. The backend appends only the
+ // payload's groups. Each group keeps its own target. A payload-level target never applies.
+ // The no-change copy quotes the projected level, which counts only sets on the flag-level
+ // target. A condition on another target is therefore not judged here.
+ rolloutUnchanged =
+ addedRolloutPercentage !== null &&
+ rolloutPercentage !== null &&
+ sharedAggregationTarget(addedGroups, flagAggregation) === flagTarget &&
+ addedRolloutPercentage <= rolloutPercentage
+ const addedLevel = maxUntargetedRolloutPercentage(addedGroups, flagAggregation, flagTarget)
+ if (addedLevel !== null) {
+ rolloutPercentage = rolloutPercentage === null ? addedLevel : Math.max(rolloutPercentage, addedLevel)
}
} else if (payload.operation === ScheduledChangeOperationType.UpdateVariants) {
variantCount = payload.value.variants.length
@@ -196,6 +273,7 @@ export function expandScheduleOccurrences(
schedule,
projected: { active, rolloutPercentage, variantCount },
addedRolloutPercentage,
+ rolloutUnchanged,
// A bound change request covers one occurrence only. The first occurrence needs approval
// when its own request is still pending. Every later occurrence of a gated schedule
// needs one too: regate_recurring_scheduled_change binds a fresh pending request after