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(mcp): match update-feature-flag conditions by condition_id (#121503)

Phil Haack3b099cbcba55
diff --git a/services/mcp/src/lib/plain-object.ts b/services/mcp/src/lib/plain-object.ts
index 450e2e3fb3ee..684309dfa2dd 100644
--- a/services/mcp/src/lib/plain-object.ts
+++ b/services/mcp/src/lib/plain-object.ts
@@ -4,6 +4,22 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
+export function hasKey(obj: Record<string, unknown> | null | undefined, key: string): boolean {
+ return !!obj && Object.prototype.hasOwnProperty.call(obj, key)
+}
+
+/**
+ * Serializes with object keys sorted. Two parsed JSON values that isDeepStrictEqual treats as equal
+ * give the same string.
+ */
+export function canonicalJson(value: unknown): string {
+ const sortKeys = (_key: string, nested: unknown): unknown =>
+ isRecord(nested)
+ ? Object.fromEntries(Object.entries(nested).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
+ : nested
+ return JSON.stringify(value, sortKeys) ?? 'undefined'
+}
+
/**
* Assign a key without triggering the inherited `__proto__` setter. Parsed JSON
* can legitimately carry an own `__proto__` key (e.g. a tool payload being
diff --git a/services/mcp/src/tools/featureFlags/aggregation.ts b/services/mcp/src/tools/featureFlags/aggregation.ts
new file mode 100644
index 000000000000..0b671bcdd5fe
--- /dev/null
+++ b/services/mcp/src/tools/featureFlags/aggregation.ts
@@ -0,0 +1,32 @@
+import { hasKey } from '@/lib/plain-object'
+
+export function isPresentGroupIndex(index: unknown): index is number {
+ return typeof index === 'number' && Number.isFinite(index)
+}
+
+export function flagLevelGroupIndex(filters: Record<string, unknown> | null | undefined): number | undefined {
+ const index = filters?.aggregation_group_type_index
+ return isPresentGroupIndex(index) ? index : undefined
+}
+
+export function explicitlyClearsAggregation(obj: Record<string, unknown> | null | undefined): boolean {
+ return hasKey(obj, 'aggregation_group_type_index') && !isPresentGroupIndex(obj?.aggregation_group_type_index)
+}
+
+/** Callers fold an explicit null into `pinnedToPerson` first. `explicitIndex` cannot tell a
+ * null from an absent key. */
+export function resolveGroupIndex(
+ pinnedToPerson: boolean,
+ explicitIndex: unknown,
+ fallbackIndex: number | undefined
+): number | undefined {
+ if (pinnedToPerson) {
+ return undefined
+ }
+ return isPresentGroupIndex(explicitIndex) ? explicitIndex : fallbackIndex
+}
+
+/** A set with no index of its own aggregates on the flag level, which the API distributes on write. */
+export function storedAggregation(group: Record<string, unknown>, flagLevel: number | undefined): number | null {
+ return resolveGroupIndex(explicitlyClearsAggregation(group), group.aggregation_group_type_index, flagLevel) ?? null
+}
diff --git a/services/mcp/src/tools/featureFlags/conditionIds.ts b/services/mcp/src/tools/featureFlags/conditionIds.ts
new file mode 100644
index 000000000000..aab89169e433
--- /dev/null
+++ b/services/mcp/src/tools/featureFlags/conditionIds.ts
@@ -0,0 +1,68 @@
+import { createHash } from 'node:crypto'
+
+import { canonicalJson, isRecord } from '@/lib/plain-object'
+
+import { flagLevelGroupIndex, storedAggregation } from './aggregation'
+
+/**
+ * The ID covers only what the update merge restores from: the key, type, group_type_index,
+ * operator, and value of each property, and the aggregation the condition uses.
+ * An edit to rollout, variant, or description between an agent's read and its write keeps the ID.
+ * A read-time annotation such as cohort_name does not change it either. Two stored conditions with
+ * the same ID restore the same types, so the merge does not need to tell them apart.
+ *
+ * A condition without an aggregation_group_type_index key aggregates on the flag level. Every API
+ * write that sends filters copies the flag level into each such condition (validate_filters in
+ * products/feature_flags/backend/api/feature_flag.py). Hashing the resolved aggregation keeps that
+ * write from changing the ID.
+ */
+export function conditionId(group: Record<string, unknown>, flagLevel: number | undefined): string {
+ const aggregation = storedAggregation(group, flagLevel)
+ const properties = Array.isArray(group.properties) ? group.properties.filter(isRecord) : []
+ const filters = properties
+ .map((prop) =>
+ canonicalJson([
+ prop.key,
+ prop.type ?? null,
+ prop.group_type_index ?? null,
+ prop.operator ?? null,
+ prop.value ?? null,
+ ])
+ )
+ .sort()
+ return createHash('sha256')
+ .update(canonicalJson([aggregation, filters]))
+ .digest('hex')
+ .slice(0, 16)
+}
+
+/**
+ * Accepts a flag, a record that holds a flag under `feature_flag` (an experiment or a my-flags
+ * row), or a list of either as an array or under `results`. Any other value passes through.
+ */
+export function withConditionIds<T>(value: T): T {
+ if (Array.isArray(value)) {
+ return value.map(withConditionIds) as T
+ }
+ if (!isRecord(value)) {
+ return value
+ }
+ if (Array.isArray(value.results)) {
+ return { ...value, results: value.results.map(withConditionIds) }
+ }
+ if (isRecord(value.feature_flag)) {
+ return { ...value, feature_flag: withConditionIds(value.feature_flag) }
+ }
+ if (!isRecord(value.filters) || !Array.isArray(value.filters.groups)) {
+ return value
+ }
+ const flagLevel = flagLevelGroupIndex(value.filters)
+ const groups = value.filters.groups.map((group: unknown) => {
+ if (!isRecord(group)) {
+ return group
+ }
+ const { condition_id: _stored, ...rest } = group
+ return { condition_id: conditionId(group, flagLevel), ...rest }
+ })
+ return { ...value, filters: { ...value.filters, groups } }
+}
diff --git a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts
index f6120b33a095..ed3b4834898d 100644
--- a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts
+++ b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts
@@ -5,6 +5,15 @@
* flag-level value, so it can lose its group targeting. The merge therefore restores these
* omitted fields from the stored flag (PostHog/posthog#46501).
*
+ * The read tools add a `condition_id` to each condition set (see conditionIds.ts). When the payload
+ * carries any condition_id, each set takes the stored set with the same ID as its source, at any
+ * position. A set without an ID is then new. The merge refuses an ID that matches no stored set.
+ * Such an ID usually means that the flag changed after the agent read it. A property whose key its
+ * source does not hold takes its type from every stored set that holds the key. This also applies
+ * on a flag whose stored sets aggregate on different group types. When that type does not fit the
+ * set's aggregation, the API rejects the write. The rules below that pair sets by position and by
+ * content apply only to a payload without IDs.
+ *
* An incoming condition set takes the stored set at its own index as its source when every stored
* set keeps its property keys at its index. New sets may only follow the stored ones. On a flag
* whose stored sets aggregate on different group types, nothing else tells a moved set from an
@@ -74,7 +83,16 @@
import { isDeepStrictEqual } from 'node:util'
import { ToolInputValidationError } from '@/lib/errors'
-import { isRecord } from '@/lib/plain-object'
+import { canonicalJson, hasKey, isRecord } from '@/lib/plain-object'
+
+import {
+ explicitlyClearsAggregation,
+ flagLevelGroupIndex,
+ isPresentGroupIndex,
+ resolveGroupIndex,
+ storedAggregation,
+} from './aggregation'
+import { conditionId } from './conditionIds'
export type FlagProperty = {
key?: string
@@ -106,10 +124,6 @@ function isPresentType(type: unknown): type is string {
return typeof type === 'string' && type.length > 0
}
-function isPresentGroupIndex(index: unknown): index is number {
- return typeof index === 'number' && Number.isFinite(index)
-}
-
/**
* `!== 'group'` is the complement of PERSON_AGGREGATED_PROPERTY_TYPES in filters_validation.py.
* It holds only while 'group' is the sole type outside that tuple. A Python test asserts that:
@@ -120,14 +134,6 @@ function isPersonAggregatedType(type: unknown): type is string {
return isPresentType(type) && type !== 'group'
}
-function hasKey(obj: Record<string, unknown> | null | undefined, key: string): boolean {
- return !!obj && Object.prototype.hasOwnProperty.call(obj, key)
-}
-
-function explicitlyClearsAggregation(obj: Record<string, unknown> | null | undefined): boolean {
- return hasKey(obj, 'aggregation_group_type_index') && !isPresentGroupIndex(obj?.aggregation_group_type_index)
-}
-
function hasExplicitPersonProperty(group: FlagConditionGroup): boolean {
return Array.isArray(group.properties) && group.properties.some((p) => isPersonAggregatedType(p?.type))
}
@@ -161,23 +167,12 @@ function indexProperties(properties: FlagProperty[] | null | undefined): Map<str
return byKey
}
-/** A set with no index of its own aggregates on the flag level, which the API distributes on write. */
-function storedAggregation(group: FlagConditionGroup, flagLevelGroupIndex: number | undefined): number | null {
- return (
- resolveGroupIndex(
- explicitlyClearsAggregation(group),
- group.aggregation_group_type_index,
- flagLevelGroupIndex
- ) ?? null
- )
-}
-
/** `aggregation` is null for a set that aggregates on persons. */
type ExistingSet = { group: FlagConditionGroup; propsByKey: Map<string, FlagProperty[]>; aggregation: number | null }
function indexExistingSets(
existing: FlagFilters | null | undefined,
- flagLevelGroupIndex: number | undefined
+ flagLevel: number | undefined
): (ExistingSet | undefined)[] {
const groups = existing?.groups
if (!Array.isArray(groups)) {
@@ -188,7 +183,7 @@ function indexExistingSets(
? {
group,
propsByKey: indexProperties(group.properties),
- aggregation: storedAggregation(group, flagLevelGroupIndex),
+ aggregation: storedAggregation(group, flagLevel),
}
: undefined
)
@@ -285,18 +280,6 @@ function keepsCondition(incoming: FlagConditionGroup, source: ExistingSet): bool
)
}
-/**
- * Two values that isDeepStrictEqual treats as equal give the same string. The string only keys a
- * lookup. The exact comparison still runs on what the lookup finds.
- */
-function canonicalJson(value: unknown): string {
- const sortKeys = (_key: string, nested: unknown): unknown =>
- isRecord(nested)
- ? Object.fromEntries(Object.entries(nested).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
- : nested
- return JSON.stringify(value, sortKeys) ?? 'undefined'
-}
-
/** Sets that keepsFilters treats as having the same filters on the same keys share this signature. */
function filterSignature(propsByKey: Map<string, FlagProperty[]>): string {
return JSON.stringify(
@@ -353,19 +336,6 @@ function keepsKeys(incoming: FlagConditionGroup | undefined, existingSet: Existi
return hasSameKeySet(incomingKeys, existingSet?.propsByKey ?? new Map())
}
-/** Callers fold an explicit null into `pinnedToPerson` first. `explicitIndex` cannot tell a
- * null from an absent key. */
-function resolveGroupIndex(
- pinnedToPerson: boolean,
- explicitIndex: unknown,
- fallbackIndex: number | undefined
-): number | undefined {
- if (pinnedToPerson) {
- return undefined
- }
- return isPresentGroupIndex(explicitIndex) ? explicitIndex : fallbackIndex
-}
-
function usableCandidates(
candidates: FlagProperty[] | undefined,
usableType: (type: unknown) => boolean
@@ -522,12 +492,13 @@ function resolveSetAggregation(
function typeSetProperties(
group: FlagConditionGroup,
- typeCandidatesByKey: Map<string, FlagProperty[]> | undefined,
+ sourceSet: ExistingSet | undefined,
+ fallbackCandidatesByKey: Map<string, FlagProperty[]> | undefined,
crossSetPropsByKey: Map<string, FlagProperty[]>,
setGroupTypeIndex: number | undefined,
- source: SourceAggregation | undefined,
matchedSets: ExistingSet[]
): FlagConditionGroup {
+ const source: SourceAggregation | undefined = sourceSet && (sourceSet.aggregation === null ? 'person' : 'group')
const out: FlagConditionGroup = { ...group }
if (Array.isArray(out.properties)) {
out.properties = out.properties.map((prop) => {
@@ -538,9 +509,17 @@ function typeSetProperties(
if (typeof key !== 'string') {
return prop
}
- const candidates = typeCandidatesByKey?.get(key)
+ const candidates = sourceSet?.propsByKey.get(key)
if (matchedSets.length === 0) {
- return mergeProperty(prop, candidates, crossSetPropsByKey.get(key), setGroupTypeIndex, source)
+ // A key the source does not hold takes its type from every stored set, even on a mixed flag.
+ const sourceHoldsKey = candidates !== undefined
+ return mergeProperty(
+ prop,
+ sourceHoldsKey ? candidates : fallbackCandidatesByKey?.get(key),
+ crossSetPropsByKey.get(key),
+ setGroupTypeIndex,
+ sourceHoldsKey ? source : undefined
+ )
}
// The set either moved from one of the matched sets or copies its filters in place. Each
// reading types the property from a different person set. Only a type that every reading
@@ -563,8 +542,12 @@ function typeSetProperties(
return out
}
+function groupPaths(indexes: number[]): string {
+ return indexes.map((index) => `filters.groups[${index}]`).join(', ')
+}
+
function unresolvedAggregationMessage(unresolved: number[]): string {
- const paths = unresolved.map((index) => `filters.groups[${index}]`).join(', ')
+ const paths = groupPaths(unresolved)
return (
"This flag's release conditions don't all target the same thing: some target persons and others a " +
'group type, or they target different group types. This update adds, removes, or reorders conditions, ' +
@@ -574,6 +557,93 @@ function unresolvedAggregationMessage(unresolved: number[]): string {
)
}
+function staleConditionIdMessage(stale: number[]): string {
+ const paths = groupPaths(stale)
+ return (
+ `The condition_id on ${paths} matches no condition on the flag. ` +
+ 'A condition_id only matches conditions on the flag you read it from. If you copied this condition ' +
+ 'from another flag or an experiment, remove its condition_id and send it as a new condition. ' +
+ 'Otherwise the flag may have changed after you read it. Read the flag again, then build the update ' +
+ 'from its current conditions and their condition_id values.'
+ )
+}
+
+function sourcesByConditionId(
+ conditionIds: (string | undefined)[],
+ existingSets: (ExistingSet | undefined)[],
+ existingFlagGroupIndex: number | undefined
+): (ExistingSet | undefined)[] {
+ const storedById = new Map<string, ExistingSet>()
+ for (const existingSet of existingSets) {
+ if (!existingSet) {
+ continue
+ }
+ const id = conditionId(existingSet.group, existingFlagGroupIndex)
+ if (!storedById.has(id)) {
+ storedById.set(id, existingSet)
+ }
+ }
+ const stale = conditionIds.flatMap((id, index) => (id !== undefined && !storedById.has(id) ? [index] : []))
+ if (stale.length > 0) {
+ throw new ToolInputValidationError(staleConditionIdMessage(stale), {
+ fields: ['filters.groups.N.condition_id:stale_condition_id'],
+ })
+ }
+ return conditionIds.map((id) => (id === undefined ? undefined : storedById.get(id)))
+}
+
+type SetSources = { sourceSets: (ExistingSet | undefined)[]; matchedPersonSets: ExistingSet[][] }
+
+function matchSetsByPositionAndContent(
+ incomingGroups: FlagConditionGroup[],
+ existingSets: (ExistingSet | undefined)[],
+ mixedAggregation: boolean
+): SetSources {
+ const keptKeys = existingSets.map((existingSet, index) => keepsKeys(incomingGroups[index], existingSet))
+ // On a single-aggregation flag a positional source cannot carry the wrong aggregation.
+ const positionHolds = !mixedAggregation || (incomingGroups.length >= existingSets.length && keptKeys.every(Boolean))
+ const sourceSets = incomingGroups.map((group, index) => {
+ const existingSet = existingSets[index]
+ const ambiguous =
+ mixedAggregation &&
+ !!existingSet &&
+ isRecord(group) &&
+ existingSets.some(
+ (other) =>
+ !!other &&
+ other.aggregation !== existingSet.aggregation &&
+ hasSameKeySet(other.propsByKey, existingSet.propsByKey)
+ ) &&
+ !keepsFilters(group, existingSet)
+ return positionHolds && keptKeys[index] && !ambiguous ? existingSet : undefined
+ })
+ const keptConditions = existingSets.map((existingSet, index) => {
+ const group = incomingGroups[index]
+ return !!existingSet && isRecord(group) && keepsCondition(group, existingSet)
+ })
+ const personSetsByFilters = groupPersonSetsByFilters(existingSets)
+ const changedTypings = new Set(
+ [...personSetsByFilters.values()]
+ .flat()
+ .filter((sameTyping) => sameTyping.indexes.some((otherIndex) => !keptConditions[otherIndex]))
+ )
+ const matchedPersonSets = sourceSets.map((sourceSet, index) => {
+ const group = incomingGroups[index]
+ if (sourceSet?.aggregation !== null || !isRecord(group)) {
+ return []
+ }
+ return (personSetsByFilters.get(filterSignature(indexProperties(group.properties))) ?? [])
+ .filter(
+ (sameTyping) =>
+ sameTyping.indexes.some((otherIndex) => otherIndex !== index) &&
+ keepsFilters(group, sameTyping.set) &&
+ (!keptConditions[index] || changedTypings.has(sameTyping))
+ )
+ .map((sameTyping) => sameTyping.set)
+ })
+ return { sourceSets, matchedPersonSets }
+}
+
/**
* Merge incoming MCP filters with the flag's current filters. Explicitly set incoming
* values always win, `null` included, and only missing `type`, `group_type_index`, and
@@ -592,9 +662,7 @@ export function preserveGroupTargetingFilters(
const result: FlagFilters = { ...incoming }
- const existingFlagGroupIndex = isPresentGroupIndex(existing?.aggregation_group_type_index)
- ? existing.aggregation_group_type_index
- : undefined
+ const existingFlagGroupIndex = flagLevelGroupIndex(existing)
// An echo of the stored flag level decides nothing new. validate_filters in
// products/feature_flags/backend/api/feature_flag.py re-derives the stored flag level from the
@@ -619,6 +687,17 @@ export function preserveGroupTargetingFilters(
if (Array.isArray(result.groups)) {
const existingSets = indexExistingSets(existing, existingFlagGroupIndex)
const crossSetPropsByKey = indexPropertiesAcrossSets(existingSets)
+ const conditionIds = result.groups.map((group) =>
+ isRecord(group) && typeof group.condition_id === 'string' ? group.condition_id : undefined
+ )
+ result.groups = result.groups.map((group) => {
+ if (!isRecord(group)) {
+ return group
+ }
+ const { condition_id: _conditionId, ...rest } = group
+ return rest
+ })
+ const carriesConditionIds = conditionIds.some((id) => id !== undefined)
const pinnedToPerson = result.groups.map(
(group) => isRecord(group) && isPinnedToPerson(group, incomingClearsAggregation)
)
@@ -626,51 +705,13 @@ export function preserveGroupTargetingFilters(
const storedAggregations = new Set(aggregations.filter((aggregation) => aggregation !== undefined))
const mixedAggregation = storedAggregations.size > 1
const aggregatesOnPersonsOnly = storedAggregations.size === 1 && storedAggregations.has(null)
- const incomingGroups = result.groups
- const keptKeys = existingSets.map((existingSet, index) => keepsKeys(incomingGroups[index], existingSet))
- // On a single-aggregation flag a positional source cannot carry the wrong aggregation.
- const positionHolds =
- !mixedAggregation || (incomingGroups.length >= existingSets.length && keptKeys.every(Boolean))
- const sourceSets = existingSets.map((existingSet, index) => {
- const group = incomingGroups[index]
- const ambiguous =
- mixedAggregation &&
- !!existingSet &&
- isRecord(group) &&
- existingSets.some(
- (other) =>
- !!other &&
- other.aggregation !== existingSet.aggregation &&
- hasSameKeySet(other.propsByKey, existingSet.propsByKey)
- ) &&
- !keepsFilters(group, existingSet)
- return positionHolds && keptKeys[index] && !ambiguous ? existingSet : undefined
- })
+ const { sourceSets, matchedPersonSets }: SetSources = carriesConditionIds
+ ? {
+ sourceSets: sourcesByConditionId(conditionIds, existingSets, existingFlagGroupIndex),
+ matchedPersonSets: [],
+ }
+ : matchSetsByPositionAndContent(result.groups, existingSets, mixedAggregation)
const personSources = sourceSets.map((sourceSet) => (sourceSet?.aggregation === null ? sourceSet : undefined))
- const keptConditions = existingSets.map((existingSet, index) => {
- const group = incomingGroups[index]
- return !!existingSet && isRecord(group) && keepsCondition(group, existingSet)
- })
- const personSetsByFilters = groupPersonSetsByFilters(existingSets)
- const changedTypings = new Set(
- [...personSetsByFilters.values()]
- .flat()
- .filter((sameTyping) => sameTyping.indexes.some((otherIndex) => !keptConditions[otherIndex]))
- )
- const matchedPersonSets = personSources.map((personSource, index) => {
- const group = incomingGroups[index]
- if (!personSource || !isRecord(group)) {
- return []
- }
- return (personSetsByFilters.get(filterSignature(indexProperties(group.properties))) ?? [])
- .filter(
- (sameTyping) =>
- sameTyping.indexes.some((otherIndex) => otherIndex !== index) &&
- keepsFilters(group, sameTyping.set) &&
- (!keptConditions[index] || changedTypings.has(sameTyping))
- )
- .map((sameTyping) => sameTyping.set)
- })
const personSetPropsFor = (index: number): (Map<string, FlagProperty[]> | undefined)[] =>
sourceSets[index]
@@ -707,19 +748,18 @@ export function preserveGroupTargetingFilters(
if (!isRecord(group)) {
return group
}
- const typeCandidatesByKey =
- sourceSets[index]?.propsByKey ??
- (!mixedAggregation || statesOwnGroupType[index] ? crossSetPropsByKey : undefined)
+ const fallbackCandidatesByKey =
+ !mixedAggregation || statesOwnGroupType[index] || sourceSets[index] ? crossSetPropsByKey : undefined
return typeSetProperties(
group,
- typeCandidatesByKey,
+ sourceSets[index],
+ fallbackCandidatesByKey,
crossSetPropsByKey,
resolveGroupIndex(
pinnedToPerson[index] ?? false,
group.aggregation_group_type_index,
effectiveFlagGroupIndex
),
- sourceSets[index] ? (personSources[index] ? 'person' : 'group') : undefined,
matchedPersonSets[index] ?? []
)
})
diff --git a/services/mcp/tests/unit/condition-ids.test.ts b/services/mcp/tests/unit/condition-ids.test.ts
new file mode 100644
index 000000000000..8fef17da00fb
--- /dev/null
+++ b/services/mcp/tests/unit/condition-ids.test.ts
@@ -0,0 +1,439 @@
+import { describe, expect, it } from 'vitest'
+
+import { isRecord } from '@/lib/plain-object'
+import { withConditionIds } from '@/tools/featureFlags/conditionIds'
+import {
+ type FlagConditionGroup,
+ type FlagFilters,
+ preserveGroupTargetingFilters,
+} from '@/tools/featureFlags/preserveGroupTargeting'
+
+const planOn = (group_type_index: number, value: string): FlagConditionGroup => ({
+ properties: [{ key: 'plan', type: 'group', group_type_index, operator: 'exact', value }],
+ rollout_percentage: 100,
+})
+
+const personPlan = (value: string): FlagConditionGroup => ({
+ properties: [
+ { key: 'plan', type: 'person', operator: 'exact', value },
+ { key: 'country', type: 'person', operator: 'exact', value: 'US' },
+ ],
+ rollout_percentage: 100,
+})
+
+function idOnRead(group: FlagConditionGroup, flagLevel?: number | null): unknown {
+ const [read] = conditionsIn(
+ withConditionIds({ filters: { groups: [group], aggregation_group_type_index: flagLevel } })
+ )
+ return read?.condition_id
+}
+
+function readGroups(filters: FlagFilters): FlagConditionGroup[] {
+ return withConditionIds({ filters }).filters.groups ?? []
+}
+
+function echoWithId(read: FlagConditionGroup, overrides: Partial<FlagConditionGroup> = {}): FlagConditionGroup {
+ return {
+ condition_id: read.condition_id,
+ properties: (read.properties ?? []).map(({ key, operator, value }) => ({ key, operator, value })),
+ rollout_percentage: read.rollout_percentage,
+ ...overrides,
+ }
+}
+
+type MergeRow = {
+ name: string
+ flagLevel?: number
+ stored: FlagConditionGroup[]
+ sent: (read: FlagConditionGroup[]) => FlagConditionGroup[]
+ expected: unknown[][]
+}
+
+function personAndCohortInOppositeOrders(aggregation: number | undefined): MergeRow {
+ const ownAggregation = aggregation === undefined ? {} : { aggregation_group_type_index: aggregation }
+ const person = { key: 'id', type: 'person', operator: 'exact', value: 'x' }
+ const cohort = { key: 'id', type: 'cohort', operator: 'exact', value: 7 }
+ return {
+ name: `two ${aggregation === undefined ? 'person' : 'group'} sets with one ID hold a key as person and cohort in opposite orders and the agent edits one value`,
+ stored: [
+ { ...ownAggregation, properties: [person, cohort], rollout_percentage: 100 },
+ { ...ownAggregation, properties: [cohort, person], rollout_percentage: 50 },
+ ],
+ sent: (stored) => [
+ echoWithId(stored[0]!),
+ echoWithId(stored[1]!, {
+ properties: [
+ { key: 'id', operator: 'exact', value: 8 },
+ { key: 'id', operator: 'exact', value: 'x' },
+ ],
+ }),
+ ],
+ expected: [
+ [aggregation ?? null, ['person', undefined], ['cohort', undefined]],
+ [aggregation ?? null, [undefined, undefined], ['person', undefined]],
+ ],
+ }
+}
+
+function typings(filters: FlagFilters | null | undefined): unknown[][] {
+ return (filters?.groups ?? []).map((group) => [
+ group.aggregation_group_type_index ?? null,
+ ...(group.properties ?? []).map((prop) => [prop.type, prop.group_type_index]),
+ ])
+}
+
+const flag = (id: number): Record<string, unknown> => ({
+ id,
+ key: `flag-${id}`,
+ filters: {
+ groups: [{ ...planOn(0, `plan-${id}`), aggregation_group_type_index: 0 }, personPlan('free')],
+ multivariate: null,
+ },
+ active: true,
+})
+
+const experiment = (id: number): Record<string, unknown> => ({
+ id,
+ name: `Experiment ${id}`,
+ feature_flag_key: `flag-${id + 100}`,
+ feature_flag: flag(id + 100),
+ metrics: [],
+ status: 'running',
+})
+
+function conditionsIn(value: unknown): Record<string, unknown>[] {
+ if (Array.isArray(value)) {
+ return value.flatMap(conditionsIn)
+ }
+ if (!isRecord(value)) {
+ return []
+ }
+ return Object.entries(value).flatMap(([key, nested]) =>
+ key === 'filters' && isRecord(nested) && Array.isArray(nested.groups)
+ ? nested.groups.filter(isRecord)
+ : conditionsIn(nested)
+ )
+}
+
+function withoutConditionIds(value: unknown): unknown {
+ return JSON.parse(JSON.stringify(value, (key, nested) => (key === 'condition_id' ? undefined : nested)))
+}
+
+describe('condition ids', () => {
+ it('gives the same ID to one stored condition however the API renders it', () => {
+ const stored = {
+ aggregation_group_type_index: null,
+ properties: [
+ { key: 'id', type: 'cohort', operator: 'in', value: 7 },
+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'pro' },
+ { key: '$group_key', type: 'group', group_type_index: 0, operator: 'exact', value: 'acme' },
+ ],
+ rollout_percentage: 50,
+ }
+ const rendered = {
+ ...stored,
+ properties: [
+ { ...stored.properties[1]! },
+ { ...stored.properties[0]!, cohort_name: 'Paying customers' },
+ { ...stored.properties[2]!, group_key_names: { acme: 'Acme Inc' } },
+ ],
+ rollout_percentage: 75,
+ variant: 'test',
+ description: 'Edited in the UI',
+ sort_key: 'abc-123',
+ }
+
+ expect(idOnRead(rendered)).toBe(idOnRead(stored))
+ })
+
+ it.each([
+ { name: 'key', change: { key: 'tier' } },
+ { name: 'type', change: { type: 'person' } },
+ { name: 'group_type_index', change: { group_type_index: 1 } },
+ { name: 'value', change: { value: 'enterprise' } },
+ { name: 'operator', change: { operator: 'icontains' } },
+ ])('gives a condition a new ID when a property changes its $name', ({ change }) => {
+ const stored = planOn(0, 'pro')
+ const changed = { ...stored, properties: [{ ...stored.properties![0]!, ...change }] }
+
+ expect(idOnRead(changed)).not.toBe(idOnRead(stored))
+ })
+
+ it.each([
+ { name: 'a group type', flagLevel: 0 },
+ { name: 'persons', flagLevel: null },
+ ])(
+ 'keeps the ID of a condition without an aggregation when the API writes a flag level of $name into it',
+ ({ flagLevel }) => {
+ const absent = planOn(0, 'pro')
+
+ expect(idOnRead({ ...absent, aggregation_group_type_index: flagLevel }, flagLevel)).toBe(
+ idOnRead(absent, flagLevel)
+ )
+ }
+ )
+
+ it('tells an explicit null aggregation from an absent one on a flag that aggregates on a group type', () => {
+ const absent = planOn(0, 'pro')
+
+ expect(idOnRead({ ...absent, aggregation_group_type_index: null }, 0)).not.toBe(idOnRead(absent, 0))
+ })
+
+ it.each([
+ { name: 'a flag', value: flag(9) },
+ { name: 'an experiment', value: experiment(5) },
+ {
+ name: 'a page of experiments where one has no flag',
+ value: {
+ count: 2,
+ next: 'https://us.posthog.com/api/projects/42/experiments/?offset=2',
+ results: [experiment(5), { ...experiment(6), feature_flag: null }],
+ _posthogUrl: 'https://us.posthog.com/project/42/experiments',
+ },
+ },
+ {
+ name: 'a list of my-flags rows',
+ value: [
+ { feature_flag: flag(9), value: true },
+ { feature_flag: flag(10), value: 'test' },
+ ],
+ },
+ { name: 'a lookup miss', value: { found: false, key: 'flag-9', message: 'No feature flag' } },
+ {
+ name: 'a flag whose conditions carry a saved condition_id',
+ value: { id: 9, filters: { groups: [{ condition_id: 'saved-by-api', ...personPlan('free') }] } },
+ },
+ ])('adds an ID to each condition of $name and changes nothing else', ({ value }) => {
+ const result = withConditionIds(structuredClone(value))
+
+ expect(conditionsIn(result).map((group) => group.condition_id)).toEqual(
+ conditionsIn(withoutConditionIds(value)).map((group) => idOnRead(group))
+ )
+ expect(withoutConditionIds(result)).toEqual(withoutConditionIds(value))
+ })
+
+ it.each<MergeRow>([
+ {
+ name: 'two person sets on different group types trade places',
+ stored: [planOn(0, 'enterprise'), planOn(1, 'pro')],
+ sent: (stored) => [echoWithId(stored[1]!), echoWithId(stored[0]!)],
+ expected: [
+ [null, ['group', 1]],
+ [null, ['group', 0]],
+ ],
+ },
+ {
+ name: 'the first of two person sets is deleted',
+ stored: [planOn(0, 'pro'), planOn(1, 'pro')],
+ sent: (stored) => [echoWithId(stored[1]!)],
+ expected: [[null, ['group', 1]]],
+ },
+ {
+ name: 'a set moves and changes its value',
+ stored: [planOn(0, 'enterprise'), planOn(1, 'pro')],
+ sent: (stored) => [
+ echoWithId(stored[1]!, {
+ properties: [{ key: 'plan', operator: 'exact', value: 'business' }],
+ }),
+ echoWithId(stored[0]!),
+ ],
+ expected: [
+ [null, ['group', 1]],
+ [null, ['group', 0]],
+ ],
+ },
+ {
+ name: 'two sets with different keys trade places',
+ stored: [planOn(0, 'enterprise'), personPlan('free')],
+ sent: (stored) => [echoWithId(stored[1]!), echoWithId(stored[0]!)],
+ expected: [
+ [null, ['person', undefined], ['person', undefined]],
+ [null, ['group', 0]],
+ ],
+ },
+ {
+ name: 'a person set and a group set on a mixed flag trade places',
+ stored: [
+ { ...personPlan('free'), aggregation_group_type_index: null },
+ { ...planOn(0, 'enterprise'), aggregation_group_type_index: 0 },
+ ],
+ sent: (stored) => [echoWithId(stored[1]!), echoWithId(stored[0]!)],
+ expected: [
+ [0, ['group', 0]],
+ [null, ['person', undefined], ['person', undefined]],
+ ],
+ },
+ {
+ name: 'the agent copies a condition and edits the copy',
+ stored: [planOn(0, 'enterprise'), planOn(1, 'pro')],
+ sent: (stored) => [
+ echoWithId(stored[1]!),
+ echoWithId(stored[1]!, { properties: [{ key: 'plan', operator: 'exact', value: 'business' }] }),
+ echoWithId(stored[0]!),
+ ],
+ expected: [
+ [null, ['group', 1]],
+ [null, ['group', 1]],
+ [null, ['group', 0]],
+ ],
+ },
+ {
+ name: 'a new set without an ID repeats a key that a stored person set holds as a group property',
+ stored: [planOn(0, 'enterprise')],
+ sent: (stored) => [
+ echoWithId(stored[0]!),
+ { properties: [{ key: 'plan', operator: 'exact', value: 'free' }], rollout_percentage: 100 },
+ ],
+ expected: [
+ [null, ['group', 0]],
+ [null, [undefined, undefined]],
+ ],
+ },
+ ...[undefined, 0].map(personAndCohortInOppositeOrders),
+ {
+ name: 'a kept condition gains a key that another stored set holds as a group property',
+ stored: [
+ personPlan('free'),
+ {
+ properties: [{ key: 'region', type: 'group', group_type_index: 1, operator: 'exact', value: 'us' }],
+ rollout_percentage: 100,
+ },
+ ],
+ sent: (stored) => [
+ echoWithId(stored[0]!, {
+ properties: [
+ { key: 'plan', operator: 'exact', value: 'free' },
+ { key: 'country', operator: 'exact', value: 'US' },
+ { key: 'region', operator: 'exact', value: 'eu' },
+ ],
+ }),
+ echoWithId(stored[1]!),
+ ],
+ expected: [
+ [null, ['person', undefined], ['person', undefined], [undefined, undefined]],
+ [null, ['group', 1]],
+ ],
+ },
+ {
+ name: 'a kept group set gains a key that a stored person set holds as a person property',
+ stored: [
+ { ...planOn(0, 'enterprise'), aggregation_group_type_index: 0 },
+ { ...personPlan('free'), aggregation_group_type_index: null },
+ ],
+ sent: (stored) => [
+ echoWithId(stored[0]!, {
+ properties: [
+ { key: 'plan', operator: 'exact', value: 'enterprise' },
+ { key: 'country', operator: 'exact', value: 'US' },
+ ],
+ }),
+ echoWithId(stored[1]!),
+ ],
+ expected: [
+ [0, ['group', 0], ['person', undefined]],
+ [null, ['person', undefined], ['person', undefined]],
+ ],
+ },
+ {
+ name: 'a new set without an ID goes in front of the stored sets',
+ stored: [planOn(0, 'enterprise'), planOn(1, 'pro')],
+ sent: (stored) => [
+ { properties: [{ key: 'plan', operator: 'exact', value: 'free' }], rollout_percentage: 100 },
+ echoWithId(stored[0]!),
+ echoWithId(stored[1]!),
+ ],
+ expected: [
+ [null, [undefined, undefined]],
+ [null, ['group', 0]],
+ [null, ['group', 1]],
+ ],
+ },
+ {
+ name: 'two group sets that take the flag level trade places',
+ flagLevel: 0,
+ stored: [planOn(0, 'enterprise'), planOn(0, 'pro')],
+ sent: (stored) => [echoWithId(stored[1]!), echoWithId(stored[0]!)],
+ expected: [
+ [null, ['group', 0]],
+ [null, ['group', 0]],
+ ],
+ },
+ ])(
+ 'restores each condition from the stored condition with its ID when $name',
+ ({ flagLevel, stored, sent, expected }) => {
+ const existing = { groups: stored, aggregation_group_type_index: flagLevel }
+ const merged = preserveGroupTargetingFilters(existing, { groups: sent(readGroups(existing)) })
+
+ expect(typings(merged)).toEqual(expected)
+ expect(merged?.groups?.every((group) => !('condition_id' in group))).toBe(true)
+ }
+ )
+
+ it('types a key the source does not hold from every stored set when the update retargets a mixed flag', () => {
+ const mixed = [
+ { ...planOn(0, 'enterprise'), aggregation_group_type_index: 0 },
+ { ...personPlan('free'), aggregation_group_type_index: null },
+ ]
+ const [groupSet, personSet] = readGroups({ groups: mixed })
+
+ const merged = preserveGroupTargetingFilters(
+ { groups: mixed },
+ {
+ aggregation_group_type_index: 1,
+ groups: [
+ echoWithId(groupSet!, {
+ properties: [
+ { key: 'plan', operator: 'exact', value: 'enterprise' },
+ { key: 'country', operator: 'exact', value: 'US' },
+ ],
+ }),
+ echoWithId(personSet!),
+ ],
+ }
+ )
+
+ expect(typings(merged)).toEqual([
+ [null, ['group', 1], ['person', undefined]],
+ [null, ['person', undefined], ['person', undefined]],
+ ])
+ })
+
+ it('refuses a condition ID that matches no stored condition', () => {
+ const stored = [planOn(0, 'enterprise'), planOn(1, 'pro')]
+ const [kept] = readGroups({ groups: stored })
+ const [fromAnotherFlag] = readGroups({ groups: [planOn(2, 'pro')] })
+
+ expect(() =>
+ preserveGroupTargetingFilters(
+ { groups: stored },
+ { groups: [echoWithId(kept!), echoWithId(fromAnotherFlag!)] }
+ )
+ ).toThrow(
+ expect.objectContaining({
+ fields: ['filters.groups.N.condition_id:stale_condition_id'],
+ message: expect.stringMatching(
+ /on filters\.groups\[1\] matches no condition.*copied this condition from another flag .* remove its condition_id/
+ ),
+ })
+ )
+ })
+
+ it('refuses a new condition in front of the stored ones on a mixed flag when it states no aggregation', () => {
+ const mixed = [
+ { ...personPlan('free'), aggregation_group_type_index: null },
+ { ...planOn(0, 'enterprise'), aggregation_group_type_index: 0 },
+ ]
+
+ expect(() =>
+ preserveGroupTargetingFilters(
+ { groups: mixed },
+ {
+ groups: [
+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },
+ ...readGroups({ groups: mixed }).map((read) => echoWithId(read)),
+ ],
+ }
+ )
+ ).toThrow(/conditions: filters\.groups\[0\]\. /)
+ })
+})