: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): refuse ambiguous condition set edits on mixed-aggregation flags (#113494)
Phil Haackcc363203701a
diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.pyindex bbb577e8b473..60897cba0a52 100644--- a/products/feature_flags/backend/test/test_filters_validation.py+++ b/products/feature_flags/backend/test/test_filters_validation.py@@ -362,7 +362,7 @@ class TestFiltersValidation(SimpleTestCase):def test_group_is_the_only_property_type_outside_person_aggregation(self) -> None:assert set(FEATURE_FLAG_PROPERTY_TYPES) - set(PERSON_AGGREGATED_PROPERTY_TYPES) == {"group"}, ("services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts encodes the person-aggregation rule as "- "`type !== 'group'` (in mergeConditionGroup and mergeProperty). That is the complement of "+ "`type !== 'group'` (in isPersonAggregatedType). That is the complement of ""PERSON_AGGREGATED_PROPERTY_TYPES only while 'group' is the sole type outside it. A group-side type ""that slips through as person-aggregated lets that merge helper silently clear a flag's group ""targeting. If the new type belongs under person aggregation, add it to "diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex afd9d98ae0b9..57b4a2230b05 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -848,9 +848,13 @@ tools:replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep`type: "group"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if youomit them this tool restores them from the existing flag so group targeting is not silently converted to- person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the- numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the- ID. To apply a change at a future time instead, use `scheduled-changes-create`.+ person targeting. When the flag's conditions don't all target the same thing (some target persons and others+ a group type, or they target different group types), set `aggregation_group_type_index` on every condition+ whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise+ this tool can't tell which target each condition keeps, and it refuses the update. Use+ `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full+ definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at+ a future time instead, use `scheduled-changes-create`.include_params:- key- name@@ -876,7 +880,10 @@ tools:Full release-condition object (replaces filters at the API). For group flags setaggregation_group_type_index and property type "group" + group_type_index. Omitted type /group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent- person demotion (see #46501).+ person demotion (see #46501). When conditions don't all target the same thing (persons and a group+ type, or different group types) and you add, remove, reorder, or change the properties of+ conditions, set aggregation_group_type_index on each condition (null for persons), or the update is+ refused.is_remote_configuration:description:Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set thediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9168c1c2285c..01be6559467c 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -13259,7 +13259,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ccde7b646b62..ca7f33410dfc 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -13934,7 +13934,7 @@"feature_flag": "tasks"},"update-feature-flag": {- "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.",+ "description": "Update a feature flag by numeric ID (partial update: only the fields you include are changed). Use this for edits that have no dedicated tool, such as property filters, adding and removing release conditions, variant definitions, payloads, tags and the description.\n\nPrefer a dedicated tool whenever the request matches one. `feature-flag-enable`, `feature-flag-disable`, `feature-flag-archive` and `feature-flag-unarchive` each change one state field and send no `filters`. A targeting change someone else made between your read and your write is therefore not overwritten. Send `active` or `archived` here only when the same request also changes targeting or another field, so the whole edit lands in one write.\n\n`feature-flag-set-release-condition-rollout` changes one release condition's percentage and `feature-flag-roll-out-to-everyone` serves the flag to its whole audience. Both send no `filters` and both refuse the write when the flag changed after the version you read, so a concurrent edit cannot be lost. This tool sends no `version`, so it writes even when the flag changed after your read. It replaces the whole `filters` object with your copy of it. Use it for a rollout change only when those two tools cannot express it, such as changing the split between variants while leaving the audience alone.\n\nRollout conditions, variants, and payloads live in the structured `filters` param, and sending `filters` replaces the whole object, so read the flag first and merge your change. When the flag targets groups, keep `type: \"group\"`, `group_type_index`, and `filters.aggregation_group_type_index` in what you send; if you omit them this tool restores them from the existing flag so group targeting is not silently converted to person targeting. When the flag's conditions don't all target the same thing (some target persons and others a group type, or they target different group types), set `aggregation_group_type_index` on every condition whenever you add, remove, reorder, or change the properties of conditions. Use null for persons. Otherwise this tool can't tell which target each condition keeps, and it refuses the update. Use `feature-flag-get-definition-by-key` when you have the string key: it returns the numeric ID and the full definition in one call. Use `feature-flag-get-definition` when you already have the ID. To apply a change at a future time instead, use `scheduled-changes-create`.","category": "Feature flags","feature": "flags","summary": "Update feature flag",diff --git a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.tsindex 3c499a59a934..2c7d6935efe7 100644--- a/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts+++ b/services/mcp/src/tools/featureFlags/preserveGroupTargeting.ts@@ -4,20 +4,45 @@* reads an omitted property `type` as person, which silently converts a group flag to a* person flag (PostHog/posthog#46501).*+ * 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+ * edited one. The merge therefore refuses any other edit to such a flag, unless the payload changes+ * the flag-level aggregation or each set without a source states, clears, or implies its own: it+ * sends aggregation_group_type_index, carries an explicit person-aggregated property, or carries a+ * group property with a group_type_index. A set loses its source on such a flag when another stored+ * set on a different aggregation has the same keys and the incoming operators or values differ from+ * the stored ones, because a swap of the two sets and an in-place edit of their filters send the+ * same payload. On a flag whose sets all aggregate the same way, a set that keeps its keys at its+ * index keeps its source even when other sets change.+ *+ * A set's aggregation then decides its property types. A group-aggregated set restores a+ * person-aggregated type that its source holds for the key. A group-aggregated set with no source+ * looks the key up in every stored set instead when the stored sets all aggregate the same way, or+ * when the set states or implies its own group type. It types every other untyped property as+ * `group` against the set's own group type index. A person-aggregated set restores every stored+ * type except `group`.+ * check_property_types_match_aggregation in products/feature_flags/backend/filters_validation.py+ * reports a person-aggregated property in a group set. The flag evaluator reads each property by+ * its own type, so a group set keeps the stored type of a person-aggregated property it holds.+ ** `aggregation_group_type_index: null` means person aggregation. Only a missing key is* filled from the existing flag.** A condition set pinned to person aggregation never gains group targeting. A set is- * pinned when the payload clears aggregation with an explicit null, or when it carries an- * explicit person, cohort, or flag property without setting a group index itself. This- * mirrors check_property_types_match_aggregation in- * products/feature_flags/backend/filters_validation.py, which rejects a group-aggregated- * set holding a non-group property.+ * pinned when it clears its own aggregation, when the payload changes the flag level to null, or+ * when it carries an explicit property of any type except `group` without setting a group index+ * itself.** `super_groups` is ignored: the flags API drops it from writes* (LEGACY_UNKNOWN_FILTER_KEYS in products/feature_flags/backend/api/filters_schema.py).*/+import { isDeepStrictEqual } from 'node:util'++import { ToolInputValidationError } from '@/lib/errors'+import { isRecord } from '@/lib/plain-object'+export type FlagProperty = {key?: stringtype?: string | null@@ -52,54 +77,124 @@ 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:+ * products/feature_flags/backend/test/test_filters_validation.py. The complement also accepts a+ * stored type the backend tuples omit, such as `person_metadata`, which a hardcoded list drops.+ */+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))+}++/**+ * A set that carries its own group index is never pinned, which matches the backend's per-set+ * fallback in filters_validation.py. Any other set is pinned when it clears its own aggregation,+ * when the payload changes the flag level to null, or when it carries an explicit person-aggregated+ * property.+ */+function isPinnedToPerson(group: FlagConditionGroup, flagClearsAggregation: boolean): boolean {return (- !!obj &&- Object.prototype.hasOwnProperty.call(obj, 'aggregation_group_type_index') &&- !isPresentGroupIndex(obj.aggregation_group_type_index)+ !isPresentGroupIndex(group.aggregation_group_type_index) &&+ (hasKey(group, 'aggregation_group_type_index') || flagClearsAggregation || hasExplicitPersonProperty(group)))}-/** Indexed across all groups so a reordered or collapsed group can still be matched. */-function indexExistingProperties(existing: FlagFilters | null | undefined): Map<string, FlagProperty[]> {- const map = new Map<string, FlagProperty[]>()- const groups = existing?.groups- if (!Array.isArray(groups)) {- return map+function indexProperties(properties: FlagProperty[] | null | undefined): Map<string, FlagProperty[]> {+ const byKey = new Map<string, FlagProperty[]>()+ if (!Array.isArray(properties)) {+ return byKey}- for (const group of groups) {- const props = group?.properties- if (!Array.isArray(props)) {+ for (const prop of properties) {+ if (!prop || typeof prop.key !== 'string' || prop.key.length === 0) {continue}- for (const prop of props) {- if (!prop || typeof prop.key !== 'string' || prop.key.length === 0) {- continue- }- const list = map.get(prop.key) ?? []- list.push(prop)- map.set(prop.key, list)- }+ const list = byKey.get(prop.key) ?? []+ list.push(prop)+ byKey.set(prop.key, list)}- return map+ return byKey}-function pickMatchingExisting(- candidates: FlagProperty[] | undefined,- incoming: FlagProperty-): FlagProperty | undefined {- if (!candidates || candidates.length === 0) {- return undefined- }- if (incoming.operator) {- const byOp = candidates.find((c) => c.operator === incoming.operator)- if (byOp) {- return byOp- }+type ExistingSet = { group: FlagConditionGroup; propsByKey: Map<string, FlagProperty[]> }++function indexExistingSets(existing: FlagFilters | null | undefined): (ExistingSet | undefined)[] {+ const groups = existing?.groups+ if (!Array.isArray(groups)) {+ return []}- return candidates.find((c) => c.type === 'group') ?? candidates[0]+ return groups.map((group) =>+ isRecord(group) ? { group, propsByKey: indexProperties(group.properties) } : undefined+ )}+function indexPropertiesAcrossSets(existingSets: (ExistingSet | undefined)[]): Map<string, FlagProperty[]> {+ return indexProperties(+ existingSets.flatMap((existingSet) =>+ Array.isArray(existingSet?.group.properties) ? existingSet.group.properties : []+ )+ )+}++function hasSameKeySet(incoming: ReadonlyMap<string, unknown>, existing: ReadonlyMap<string, unknown>): boolean {+ return incoming.size === existing.size && [...incoming.keys()].every((key) => existing.has(key))+}++/** 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+ )+}++/**+ * The filters under each key compare as a multiset of operator and value pairs, so a removed, added,+ * or changed filter on a key is a change. The flag evaluator reads a missing operator as `exact`.+ */+function keepsFilters(incoming: FlagConditionGroup, source: ExistingSet): boolean {+ return [...indexProperties(incoming.properties)].every(([key, props]) => {+ const unmatched = [...(source.propsByKey.get(key) ?? [])]+ return (+ props.length === unmatched.length &&+ props.every((prop) => {+ const match = unmatched.findIndex(+ (stored) =>+ (stored.operator ?? 'exact') === (prop.operator ?? 'exact') &&+ isDeepStrictEqual(stored.value, prop.value)+ )+ if (match === -1) {+ return false+ }+ unmatched.splice(match, 1)+ return true+ })+ )+ })+}++function keepsKeys(incoming: FlagConditionGroup | undefined, existingSet: ExistingSet | undefined): boolean {+ const incomingKeys = isRecord(incoming) ? indexProperties(incoming.properties) : new Map()+ 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,@@ -111,97 +206,111 @@ function resolveGroupIndex(return isPresentGroupIndex(explicitIndex) ? explicitIndex : fallbackIndex}+function pickPersonAggregatedCandidate(+ candidates: FlagProperty[] | undefined,+ incoming: FlagProperty+): FlagProperty | undefined {+ const usable = (candidates ?? []).filter((candidate) => isPersonAggregatedType(candidate.type))+ if (incoming.operator) {+ const byOperator = usable.find((candidate) => candidate.operator === incoming.operator)+ if (byOperator) {+ return byOperator+ }+ }+ return usable[0]+}+function mergeProperty(incoming: FlagProperty,- existingProp: FlagProperty | undefined,- fallbackGroupTypeIndex: number | undefined,- canCarryGroupTargeting: boolean+ candidates: FlagProperty[] | undefined,+ otherCandidates: FlagProperty[] | undefined,+ setGroupTypeIndex: number | undefined): FlagProperty {const out: FlagProperty = { ...incoming }- if (!isPresentType(out.type) && existingProp && isPresentType(existingProp.type)) {- // Leaving the type unset makes the API report the property the agent actually- // sent. Restoring `group` here would name fields the agent never sent.- // `!== 'group'` relies on the same complement rule. See mergeConditionGroup.- if (canCarryGroupTargeting || existingProp.type !== 'group') {- out.type = existingProp.type+ if (!isPresentType(out.type)) {+ if (isPresentGroupIndex(setGroupTypeIndex)) {+ // Candidates that also hold the key as a group property leave the type ambiguous.+ out.type = candidates?.some((candidate) => candidate.type === 'group')+ ? 'group'+ : (pickPersonAggregatedCandidate(candidates, out)?.type ?? 'group')+ } else {+ // Leaving the type unset makes the API report the property the agent actually+ // sent. Restoring `group` here would name fields the agent never sent.+ // A source set can lack the key, or hold it only as a group property that a person+ // set cannot use. The type then comes from another set that holds the key.+ const restored =+ pickPersonAggregatedCandidate(candidates, out) ?? pickPersonAggregatedCandidate(otherCandidates, out)+ if (restored) {+ out.type = restored.type+ }}}- if (canCarryGroupTargeting && !isPresentType(out.type) && isPresentGroupIndex(fallbackGroupTypeIndex)) {- out.type = 'group'- }-- if (out.type === 'group' && !isPresentGroupIndex(out.group_type_index)) {- if (existingProp && isPresentGroupIndex(existingProp.group_type_index)) {- out.group_type_index = existingProp.group_type_index- } else if (isPresentGroupIndex(fallbackGroupTypeIndex)) {- out.group_type_index = fallbackGroupTypeIndex- }+ // A group property carries the index its own set aggregates on. The set's index therefore+ // replaces an index the agent echoed back from the group type it retargets away from.+ if (out.type === 'group' && isPresentGroupIndex(setGroupTypeIndex)) {+ out.group_type_index = setGroupTypeIndex}return out}type MergeConditionOptions = {- /** Restore set-level aggregation only from a same-index existing group (not a fallback group). */- allowAggregationRestore: boolean- /** The payload cleared aggregation with an explicit null, so no group index is restored. */- incomingClearsAggregation: boolean+ /** The payload changes the flag-level aggregation, which decides every set that sends none. */+ payloadChangesFlagAggregation: boolean+ /** This set never gains group targeting. See isPinnedToPerson. */+ pinnedToPerson: boolean}-function mergeConditionGroup(+function explicitGroupPropertyIndex(group: FlagConditionGroup): number | undefined {+ const properties = Array.isArray(group.properties) ? group.properties : []+ const indexes = properties.flatMap((prop) =>+ prop?.type === 'group' && isPresentGroupIndex(prop.group_type_index) ? [prop.group_type_index] : []+ )+ const unique = [...new Set(indexes)]+ return unique.length === 1 ? unique[0] : undefined+}++function resolveSetAggregation(incoming: FlagConditionGroup,- propertySourceGroup: FlagConditionGroup | undefined,- flagLevelGroupIndex: number | undefined,- crossGroupPropsByKey: Map<string, FlagProperty[]>,+ sourceSet: ExistingSet | undefined,options: MergeConditionOptions): FlagConditionGroup {const out: FlagConditionGroup = { ...incoming }- // One explicit person, cohort, or flag property stops this set from keeping or- // gaining group targeting. An explicit incoming group index still wins, and the API- // then reports the contradiction in the agent's own payload.- // `!== '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:- // products/feature_flags/backend/test/test_filters_validation.py- const hasExplicitNonGroupProperty =- Array.isArray(incoming.properties) &&- incoming.properties.some((p) => isPresentType(p?.type) && p.type !== 'group')- const propertiesPinSetToPerson =- hasExplicitNonGroupProperty && !isPresentGroupIndex(out.aggregation_group_type_index)- if (propertiesPinSetToPerson) {+ // One explicit property of a person-aggregated type stops this set from keeping or+ // gaining group targeting. An explicit incoming group index still wins. The API then+ // reports the contradiction in the agent's own payload.+ if (hasExplicitPersonProperty(incoming) && !isPresentGroupIndex(out.aggregation_group_type_index)) {out.aggregation_group_type_index = null}- const pinnedToPerson = options.incomingClearsAggregation || propertiesPinSetToPerson-- // Fill only when the key is absent. An explicit null means person aggregation.- if (- options.allowAggregationRestore &&- !pinnedToPerson &&- !Object.prototype.hasOwnProperty.call(out, 'aggregation_group_type_index') &&- propertySourceGroup &&- isPresentGroupIndex(propertySourceGroup.aggregation_group_type_index)- ) {- out.aggregation_group_type_index = propertySourceGroup.aggregation_group_type_index+ const { pinnedToPerson, payloadChangesFlagAggregation } = options++ // Fill only when the key is absent. An explicit null means person aggregation. A payload+ // that changes the flag level already decides this set, the same way the API distributes+ // the flag level into every set that sends no index of its own. A group property that the+ // agent typed with an index names the group type of its own set. A retarget that the agent+ // sends only on the property therefore survives.+ if (!pinnedToPerson && !payloadChangesFlagAggregation && !hasKey(out, 'aggregation_group_type_index')) {+ const restored = explicitGroupPropertyIndex(incoming) ?? sourceSet?.group.aggregation_group_type_index+ if (isPresentGroupIndex(restored)) {+ out.aggregation_group_type_index = restored+ }}- const effectiveGroupIndex = resolveGroupIndex(pinnedToPerson, out.aggregation_group_type_index, flagLevelGroupIndex)+ return out+}+function typeSetProperties(+ group: FlagConditionGroup,+ typeCandidatesByKey: Map<string, FlagProperty[]> | undefined,+ crossSetPropsByKey: Map<string, FlagProperty[]>,+ setGroupTypeIndex: number | undefined+): FlagConditionGroup {+ const out: FlagConditionGroup = { ...group }if (Array.isArray(out.properties)) {- const sameGroupByKey = new Map<string, FlagProperty[]>()- if (Array.isArray(propertySourceGroup?.properties)) {- for (const p of propertySourceGroup.properties) {- if (p && typeof p.key === 'string') {- const list = sameGroupByKey.get(p.key) ?? []- list.push(p)- sameGroupByKey.set(p.key, list)- }- }- }-out.properties = out.properties.map((prop) => {if (!prop || typeof prop !== 'object') {return prop@@ -209,21 +318,36 @@ function mergeConditionGroup(if (typeof prop.key !== 'string') {return prop}- // Cross-group matching covers groups the payload reordered or collapsed.- const existingProp =- pickMatchingExisting(sameGroupByKey.get(prop.key), prop) ??- pickMatchingExisting(crossGroupPropsByKey.get(prop.key), prop)- return mergeProperty(prop, existingProp, effectiveGroupIndex, !pinnedToPerson)+ return mergeProperty(+ prop,+ typeCandidatesByKey?.get(prop.key),+ crossSetPropsByKey.get(prop.key),+ setGroupTypeIndex+ )})}return out}+function unresolvedAggregationMessage(unresolved: number[]): string {+ const paths = unresolved.map((index) => `filters.groups[${index}]`).join(', ')+ 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, ' ++ "or changes the properties they filter on, so the tool can't tell which target each condition should keep. " ++ `Set aggregation_group_type_index on each of these conditions: ${paths}. ` ++ 'Use a group type index to target that group type, or null to target persons. Then send the update again.'+ )+}+/*** Merge incoming MCP filters with the flag's current filters. Explicitly set incoming- * values always win, `null` included. Only missing `type`, `group_type_index`, and- * `aggregation_group_type_index` keys are filled from the existing flag.+ * values always win, `null` included, and only missing `type`, `group_type_index`, and+ * `aggregation_group_type_index` keys are filled from the existing flag. The one exception+ * is a group property's `group_type_index`, which follows the index its own condition set+ * aggregates on. Any other index contradicts the set. The API reports that contradiction as+ * `group_property_type_index_mismatch`.*/export function preserveGroupTargetingFilters(existing: FlagFilters | null | undefined,@@ -236,17 +360,20 @@ export function preserveGroupTargetingFilters(const result: FlagFilters = { ...incoming }const existingFlagGroupIndex = isPresentGroupIndex(existing?.aggregation_group_type_index)- ? existing!.aggregation_group_type_index!+ ? existing.aggregation_group_type_index: undefined- const incomingClearsAggregation = explicitlyClearsAggregation(incoming as Record<string, unknown>)+ // 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+ // condition sets on every write. It sets the flag level to null when the sets disagree. A+ // stored numeric flag level therefore equals the aggregation of every set the merge restores.+ const payloadChangesFlagAggregation =+ hasKey(incoming, 'aggregation_group_type_index') &&+ incoming.aggregation_group_type_index !== existing?.aggregation_group_type_index+ const incomingClearsAggregation = payloadChangesFlagAggregation && explicitlyClearsAggregation(incoming)// The flag-level index is the UI's "Target by" group type.- if (- !incomingClearsAggregation &&- !Object.prototype.hasOwnProperty.call(result, 'aggregation_group_type_index') &&- isPresentGroupIndex(existingFlagGroupIndex)- ) {+ if (!payloadChangesFlagAggregation && isPresentGroupIndex(existingFlagGroupIndex)) {result.aggregation_group_type_index = existingFlagGroupIndex}@@ -257,31 +384,79 @@ export function preserveGroupTargetingFilters()if (Array.isArray(result.groups)) {- const crossGroupPropsByKey = indexExistingProperties(existing)- const existingGroups = Array.isArray(existing?.groups) ? existing!.groups! : []- result.groups = result.groups.map((group, index) => {- if (!group || typeof group !== 'object') {- return group+ const existingSets = indexExistingSets(existing)+ const crossSetPropsByKey = indexPropertiesAcrossSets(existingSets)+ const pinnedToPerson = result.groups.map(+ (group) => isRecord(group) && isPinnedToPerson(group, incomingClearsAggregation)+ )+ const aggregations = existingSets.map((existingSet) =>+ existingSet ? storedAggregation(existingSet.group, existingFlagGroupIndex) : undefined+ )+ const mixedAggregation = new Set(aggregations.filter((aggregation) => aggregation !== undefined)).size > 1+ const incomingGroups = result.groups+ const sharesKeysAcrossAggregations = (existingSet: ExistingSet, index: number): boolean =>+ existingSets.some(+ (other, otherIndex) =>+ !!other &&+ aggregations[otherIndex] !== aggregations[index] &&+ hasSameKeySet(other.propsByKey, existingSet.propsByKey)+ )+ 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 =+ !!existingSet &&+ isRecord(group) &&+ sharesKeysAcrossAggregations(existingSet, index) &&+ !keepsFilters(group, existingSet)+ return positionHolds && keptKeys[index] && !ambiguous ? existingSet : undefined+ })++ const resolvedGroups = result.groups.map((group, index) =>+ isRecord(group)+ ? resolveSetAggregation(group, sourceSets[index], {+ payloadChangesFlagAggregation,+ pinnedToPerson: pinnedToPerson[index] ?? false,+ })+ : group+ )+ const statesOwnGroupType = resolvedGroups.map(+ (group) => isRecord(group) && isPresentGroupIndex(group.aggregation_group_type_index)+ )++ if (mixedAggregation && !payloadChangesFlagAggregation) {+ const unresolved = resolvedGroups.flatMap((group, index) =>+ isRecord(group) && !sourceSets[index] && !pinnedToPerson[index] && !statesOwnGroupType[index]+ ? [index]+ : []+ )+ if (unresolved.length > 0) {+ throw new ToolInputValidationError(unresolvedAggregationMessage(unresolved), {+ fields: ['filters.groups.N.aggregation_group_type_index:unresolved_aggregation'],+ })}+ }- const sameIndexGroup = existingGroups[index]- // Aggregation restores only from the same index, so appending a person set- // cannot inherit another set's group index. Property restore is looser.- const propertySourceGroup =- sameIndexGroup ??- existingGroups.find((g) => isPresentGroupIndex(g?.aggregation_group_type_index)) ??- existingGroups[0]-- const groupClearsAggregation = explicitlyClearsAggregation(group as Record<string, unknown>)-- return mergeConditionGroup(group, propertySourceGroup, effectiveFlagGroupIndex, crossGroupPropsByKey, {- allowAggregationRestore: sameIndexGroup !== undefined,- // A flag-level clear only pins sets that omit the key. A set that carries its own- // index keeps it, which matches the backend's per-set fallback in filters_validation.py.- incomingClearsAggregation:- groupClearsAggregation ||- (incomingClearsAggregation && !isPresentGroupIndex(group.aggregation_group_type_index)),- })+ result.groups = resolvedGroups.map((group, index) => {+ if (!isRecord(group)) {+ return group+ }+ const typeCandidatesByKey =+ sourceSets[index]?.propsByKey ??+ (!mixedAggregation || statesOwnGroupType[index] ? crossSetPropsByKey : undefined)+ return typeSetProperties(+ group,+ typeCandidatesByKey,+ crossSetPropsByKey,+ resolveGroupIndex(+ pinnedToPerson[index] ?? false,+ group.aggregation_group_type_index,+ effectiveFlagGroupIndex+ )+ )})}diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex 88d8df12dd49..cf60f16158bb 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -983,7 +983,7 @@ const UpdateFeatureFlagSchema = () => {.extend({id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams.shape['id']),filters: FeatureFlagsPartialUpdateBody.shape['filters'].describe(- 'Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type "group" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501).'+ 'Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type "group" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501). When conditions don\'t all target the same thing (persons and a group type, or different group types) and you add, remove, reorder, or change the properties of conditions, set aggregation_group_type_index on each condition (null for persons), or the update is refused.'),is_remote_configuration: FeatureFlagsPartialUpdateBody.shape['is_remote_configuration'].describe('Whether this flag delivers a payload instead of gating a feature (Remote Config mode). When true, set the delivered payload through the `filters` param under `filters.payloads.true` as a JSON-encoded string. There is no dedicated payload parameter.'diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.jsonindex c64396aef173..9b1b54f9dd06 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/update-feature-flag.json@@ -54,7 +54,7 @@"description": "Where this flag is allowed to evaluate — `server` (server-side SDKs only), `client` (client-side SDKs only), or `all` (both). Defaults to `all`."},"filters": {- "description": "Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type \"group\" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501).",+ "description": "Full release-condition object (replaces filters at the API). For group flags set aggregation_group_type_index and property type \"group\" + group_type_index. Omitted type / group_type_index / aggregation_group_type_index are filled from the existing flag to prevent silent person demotion (see #46501). When conditions don't all target the same thing (persons and a group type, or different group types) and you add, remove, reorder, or change the properties of conditions, set aggregation_group_type_index on each condition (null for persons), or the update is refused.","properties": {"aggregation_group_type_index": {"anyOf": [diff --git a/services/mcp/tests/unit/preserve-group-targeting.test.ts b/services/mcp/tests/unit/preserve-group-targeting.test.tsindex 8482bffb45fa..dc182d9c0641 100644--- a/services/mcp/tests/unit/preserve-group-targeting.test.ts+++ b/services/mcp/tests/unit/preserve-group-targeting.test.ts@@ -1,6 +1,57 @@import { describe, expect, it } from 'vitest'-import { preserveGroupTargetingFilters } from '@/tools/featureFlags/preserveGroupTargeting'+import { ToolInputValidationError } from '@/lib/errors'+import { type FlagFilters, preserveGroupTargetingFilters } from '@/tools/featureFlags/preserveGroupTargeting'++const PERSON_AGGREGATED_PROPERTY_TYPES = ['person', 'cohort', 'flag']++/**+ * Mirrors check_property_types_match_aggregation in+ * products/feature_flags/backend/filters_validation.py, over the state that validator sees:+ * the flag level the backend keeps when the payload omits it, then each set's own key. This helper+ * skips a property with no type, which the backend rule reports. A test asserts the fields of a+ * property left untyped instead.+ */+function aggregationViolations(existing: FlagFilters, merged: FlagFilters | null | undefined): string[] {+ const violations: string[] = []+ const flagLevel =+ merged && 'aggregation_group_type_index' in merged+ ? merged.aggregation_group_type_index+ : existing.aggregation_group_type_index+ for (const [groupIndex, group] of (merged?.groups ?? []).entries()) {+ const aggregation = 'aggregation_group_type_index' in group ? group.aggregation_group_type_index : flagLevel+ for (const [propertyIndex, property] of (group.properties ?? []).entries()) {+ const path = `groups[${groupIndex}].properties[${propertyIndex}]`+ if (typeof property.type !== 'string') {+ continue+ }+ if (aggregation === undefined || aggregation === null) {+ if (!PERSON_AGGREGATED_PROPERTY_TYPES.includes(property.type)) {+ violations.push(`${path}: person_aggregation_property_type`)+ }+ } else if (property.type !== 'group') {+ violations.push(`${path}: group_aggregation_property_type`)+ } else if (property.group_type_index !== aggregation) {+ violations.push(`${path}: group_property_type_index_mismatch`)+ }+ }+ }+ return violations+}++/** The condition set paths a refusal names, or none when the merge goes through. */+function refusedSets(merge: () => unknown): string[] {+ try {+ merge()+ } catch (error) {+ if (error instanceof ToolInputValidationError) {+ expect(error.fields).toEqual(['filters.groups.N.aggregation_group_type_index:unresolved_aggregation'])+ return [...error.message.matchAll(/filters\.groups\[\d+\]/g)].map((match) => match[0])+ }+ throw error+ }+ return []+}describe('preserveGroupTargetingFilters', () => {const existingGroupFlag = {@@ -22,6 +73,85 @@ describe('preserveGroupTargetingFilters', () => {],}+ const existingMixedFlag = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const existingTwoGroupTypeFlag = {+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'name', type: 'group', group_type_index: 1, operator: 'exact', value: 'acme' }],+ rollout_percentage: 100,+ },+ ],+ }++ const existingSameKeyMixedFlag = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'plan', type: 'person', operator: 'exact', value: 'free' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const existingPersonThenTwoGroupTypesFlag = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 1, operator: 'exact', value: 'pro' },+ { key: 'seats', type: 'group', group_type_index: 1, operator: 'gt', value: 10 },+ ],+ rollout_percentage: 100,+ },+ ],+ }+it('preserves aggregation_group_type_index when omitted on update', () => {const incoming = {groups: [@@ -88,24 +218,6 @@ describe('preserveGroupTargetingFilters', () => {// A mixed-aggregation flag is stored with a null flag level and per-set indices, and// the tool tells agents to echo that back. The null must not pin a set sending its own index.it('keeps group targeting on a set carrying its own index when the flag level is null', () => {- const existingMixedFlag = {- aggregation_group_type_index: null,- groups: [- {- aggregation_group_type_index: 0,- properties: [- { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },- ],- rollout_percentage: 100,- },- {- aggregation_group_type_index: null,- properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],- rollout_percentage: 100,- },- ],- }-const merged = preserveGroupTargetingFilters(existingMixedFlag, {aggregation_group_type_index: null,groups: [@@ -139,24 +251,7 @@ describe('preserveGroupTargetingFilters', () => {})it('restores each condition set aggregation from the existing set at the same index', () => {- const existingTwoGroupFlag = {- groups: [- {- aggregation_group_type_index: 0,- properties: [- { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },- ],- rollout_percentage: 100,- },- {- aggregation_group_type_index: 1,- properties: [{ key: 'name', type: 'group', group_type_index: 1, operator: 'exact', value: 'acme' }],- rollout_percentage: 100,- },- ],- }-- const merged = preserveGroupTargetingFilters(existingTwoGroupFlag, {+ const merged = preserveGroupTargetingFilters(existingTwoGroupTypeFlag, {groups: [{ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },{ properties: [{ key: 'name', operator: 'exact', value: 'globex' }], rollout_percentage: 100 },@@ -200,32 +295,42 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[0]?.properties?.[1]?.group_type_index).toBeUndefined()})- it('still restores a non-group property type in a set pinned to person aggregation', () => {- const existingPersonSetFlag = {- aggregation_group_type_index: 0,- groups: [- {- aggregation_group_type_index: null,- properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],- rollout_percentage: 100,- },- ],- }- const incoming = {- aggregation_group_type_index: null,- groups: [- {- aggregation_group_type_index: null,- properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],- rollout_percentage: 100,- },- ],- }+ // `person_metadata` guards the restore against a hardcoded type list. Rust accepts that type+ // and FEATURE_FLAG_PROPERTY_TYPES does not list it, so a list copied from the backend drops it.+ it.each([+ { type: 'person', key: 'email', operator: 'icontains', value: '@acme.com' },+ { type: 'cohort', key: 'id', operator: 'in', value: 42 },+ { type: 'flag', key: 'other-flag', operator: 'flag_evaluates_to', value: true },+ { type: 'person_metadata', key: 'created_at', operator: 'is_date_after', value: '2026-01-01' },+ ])(+ 'still restores a $type property type in a set pinned to person aggregation',+ ({ type, key, operator, value }) => {+ const existingPersonSetFlag = {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key, type, operator, value }],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key, operator, value }],+ rollout_percentage: 100,+ },+ ],+ }- const merged = preserveGroupTargetingFilters(existingPersonSetFlag, incoming)+ const merged = preserveGroupTargetingFilters(existingPersonSetFlag, incoming)- expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('person')- })+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe(type)+ }+ )it('keeps explicit group type and index from the agent', () => {const incoming = {@@ -251,6 +356,7 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.aggregation_group_type_index).toBe(1)expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(1)expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')+ expect(aggregationViolations(existingGroupFlag, merged)).toEqual([])})it('infers type group from flag-level aggregation when property type omitted', () => {@@ -287,8 +393,8 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[0]?.properties?.[0]?.type).toBeUndefined()})- it('restores group type via cross-group key match when condition groups collapse', () => {- // Collapsing two sets into one forces the cross-group fallback.+ // Collapsing two sets into one leaves every set without a source. The flag level decides the type.+ it('types a collapsed set from the flag-level aggregation', () => {const existing = {aggregation_group_type_index: 0,groups: [@@ -327,10 +433,9 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe('pro')})- it.each([- { name: 'the operator matches the group-typed candidate', operator: 'exact', value: 'New Name' },- { name: 'the operator matches neither candidate', operator: 'regex', value: '.*' },- ])('restores group type and index for a duplicate key when $name', ({ operator, value }) => {+ // The source holds the key as both a person and a group property, so the stored type is+ // ambiguous. The set's group type then decides the property type, whichever operator the agent sends.+ it('restores group type and index for a duplicate key', () => {const existing = {aggregation_group_type_index: 0,groups: [@@ -352,7 +457,7 @@ describe('preserveGroupTargetingFilters', () => {const incoming = {groups: [{- properties: [{ key: 'name', operator, value }],+ properties: [{ key: 'name', operator: 'regex', value: '.*' }],rollout_percentage: 100,},],@@ -362,7 +467,40 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(0)- expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe(value)+ expect(merged?.groups?.[0]?.properties?.[0]?.value).toBe('.*')+ })++ // The set aggregates on person, so the candidates decide the type. The operator picks+ // between two candidates that share a key. Without an operator match, the first one wins.+ it.each([+ { name: 'the operator matches the cohort candidate', operator: 'in', expectedType: 'cohort' },+ { name: 'the operator matches the person candidate', operator: 'icontains', expectedType: 'person' },+ { name: 'the operator matches neither candidate', operator: 'regex', expectedType: 'person' },+ ])('picks a duplicate-key candidate by operator when $name', ({ operator, expectedType }) => {+ const existing = {+ groups: [+ {+ properties: [+ { key: 'name', type: 'person', operator: 'icontains', value: 'acme' },+ { key: 'name', type: 'cohort', operator: 'in', value: 42 },+ ],+ rollout_percentage: 100,+ },+ ],+ }+ const incoming = {+ groups: [+ {+ properties: [{ key: 'name', operator, value: 'acme' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe(expectedType)+ expect(aggregationViolations(existing, merged)).toEqual([])})it('does not copy set-level aggregation onto a newly appended condition set', () => {@@ -412,7 +550,9 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[1]?.properties?.[0]?.type).toBe('person')})- it('restores property group_type_index from matched existing property over flag aggregation', () => {+ // The existing flag holds a group property with no aggregation index anywhere, which the+ // backend validator reports. Restoring the type would carry that contradiction into the new payload.+ it('does not restore a group property type into a set with no group aggregation', () => {const existing = {groups: [{@@ -440,8 +580,8 @@ describe('preserveGroupTargetingFilters', () => {const merged = preserveGroupTargetingFilters(existing, incoming)- expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')- expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBe(1)+ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBeUndefined()+ expect(merged?.groups?.[0]?.properties?.[0]?.group_type_index).toBeUndefined()})it('passes through multivariate and payloads without restoring from existing', () => {@@ -470,6 +610,695 @@ describe('preserveGroupTargetingFilters', () => {expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('group')})+ // On a flag whose sets aggregate differently, only position tells a moved set from an edited+ // one. Position holds while every stored set keeps its keys at its own index.+ it.each([+ {+ name: 'two sets swap places',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [0, 1],+ },+ {+ name: 'the last set is deleted',+ existing: existingPersonThenTwoGroupTypesFlag,+ incoming: {+ groups: [+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [0, 1],+ },+ // Plain rollouts have no keys, so nothing tells which of the two survived.+ {+ name: 'one of two plain rollouts on different group types is deleted',+ existing: {+ aggregation_group_type_index: null,+ groups: [+ { aggregation_group_type_index: 0, properties: [], rollout_percentage: 50 },+ { aggregation_group_type_index: 1, properties: [], rollout_percentage: 20 },+ ],+ },+ incoming: { groups: [{ properties: [], rollout_percentage: 20 }] },+ unresolved: [0],+ },+ {+ name: 'a set is inserted before the stored sets',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'country', operator: 'exact', value: 'US' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ },+ unresolved: [0, 1, 2],+ },+ {+ name: 'a set gains a property key in place',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ {+ properties: [+ { key: 'plan', operator: 'exact', value: 'pro' },+ { key: 'seats', operator: 'gt', value: 10 },+ ],+ rollout_percentage: 100,+ },+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ },+ unresolved: [0, 1],+ },+ {+ name: 'a set is appended after the stored sets',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'country', operator: 'exact', value: 'US' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [2],+ },+ {+ name: 'moved sets state, clear, or imply their own aggregation',+ existing: existingTwoGroupTypeFlag,+ incoming: {+ groups: [+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'name', operator: 'exact', value: 'acme' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ {+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'pro' },+ ],+ rollout_percentage: 100,+ },+ {+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@globex.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'region', operator: 'exact', value: 'eu' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [4],+ },+ {+ name: 'the payload echoes the stored null flag level',+ existing: existingMixedFlag,+ incoming: {+ aggregation_group_type_index: null,+ groups: [+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [0, 1],+ },+ // A swap of these two sets and an in-place exchange of their values send the same payload.+ {+ name: 'two sets on different aggregations filter on the same key and exchange values',+ existing: existingSameKeyMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'free' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [0, 1],+ },+ {+ name: 'one of two sets that filter on the same key changes its value',+ existing: existingSameKeyMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'free' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [1],+ },+ // Moving the second set first and dropping its upper bound sends the same first set as+ // dropping the upper bound of the first set in place.+ {+ name: 'a moved set drops one of two filters on a key that both sets share',+ existing: {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'seats', type: 'group', group_type_index: 0, operator: 'gte', value: 5 },+ { key: 'seats', type: 'group', group_type_index: 0, operator: 'lte', value: 10 },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [+ { key: 'seats', type: 'group', group_type_index: 1, operator: 'gte', value: 5 },+ { key: 'seats', type: 'group', group_type_index: 1, operator: 'lte', value: 20 },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ incoming: {+ groups: [+ { properties: [{ key: 'seats', operator: 'gte', value: 5 }], rollout_percentage: 100 },+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'seats', operator: 'gte', value: 5 },+ { key: 'seats', operator: 'lte', value: 10 },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ unresolved: [0],+ },+ {+ name: 'two sets on different aggregations filter on the same key and value and exchange operators',+ existing: {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'plan', type: 'person', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'icontains', value: 'pro' },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'icontains', value: 'pro' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ },+ unresolved: [0, 1],+ },+ ])('names each condition set it cannot resolve when $name', ({ existing, incoming, unresolved }) => {+ expect(refusedSets(() => preserveGroupTargetingFilters(existing, incoming))).toEqual(+ unresolved.map((index) => `filters.groups[${index}]`)+ )+ })++ it.each([+ {+ name: 'the payload echoes the stored null flag level',+ existing: existingMixedFlag,+ incoming: {+ aggregation_group_type_index: null,+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@globex.com' }],+ rollout_percentage: 100,+ },+ ],+ },+ expected: [+ [0, 'group', 0],+ [undefined, 'person', undefined],+ ],+ },+ {+ name: 'two sets that filter on the same key keep their values and omit the exact operator',+ existing: existingSameKeyMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', value: 'free' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', value: 'enterprise' }], rollout_percentage: 100 },+ ],+ },+ expected: [+ [undefined, 'person', undefined],+ [0, 'group', 0],+ ],+ },+ {+ name: 'two sets that filter on the same key keep their values',+ existing: existingSameKeyMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'free' }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ ],+ },+ expected: [+ [undefined, 'person', undefined],+ [0, 'group', 0],+ ],+ },+ {+ name: 'the sets of a flag on one group type are reordered',+ existing: {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'seats', type: 'group', group_type_index: 0, operator: 'gt', value: 10 }],+ rollout_percentage: 100,+ },+ ],+ },+ incoming: {+ groups: [+ { properties: [{ key: 'seats', operator: 'gt', value: 10 }], rollout_percentage: 100 },+ { properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }], rollout_percentage: 100 },+ ],+ },+ expected: [+ [undefined, 'group', 0],+ [undefined, 'group', 0],+ ],+ },+ {+ name: 'a set is appended with its own aggregation',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@globex.com' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'region', operator: 'exact', value: 'eu' }],+ rollout_percentage: 100,+ },+ ],+ },+ expected: [+ [0, 'group', 0],+ [undefined, 'person', undefined],+ [1, 'group', 1],+ ],+ },+ {+ name: 'two swapped sets state their aggregation',+ existing: existingMixedFlag,+ incoming: {+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }],+ rollout_percentage: 100,+ },+ ],+ },+ expected: [+ [null, 'person', undefined],+ [0, 'group', 0],+ ],+ },+ {+ name: 'the sets left after a delete state their aggregation',+ existing: existingPersonThenTwoGroupTypesFlag,+ incoming: {+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [+ { key: 'plan', operator: 'exact', value: 'pro' },+ { key: 'seats', operator: 'gt', value: 10 },+ ],+ rollout_percentage: 100,+ },+ ],+ },+ expected: [+ [0, 'group', 0],+ [1, 'group', 1],+ ],+ },+ {+ name: 'the payload changes the flag level',+ existing: existingMixedFlag,+ incoming: {+ aggregation_group_type_index: 1,+ groups: [+ {+ properties: [{ key: 'email', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ { properties: [{ key: 'plan', operator: 'exact', value: 'pro' }], rollout_percentage: 100 },+ ],+ },+ expected: [+ [undefined, 'group', 1],+ [undefined, 'group', 1],+ ],+ },+ ])('keeps each condition set on its own aggregation when $name', ({ existing, incoming, expected }) => {+ const merged = preserveGroupTargetingFilters(existing, incoming)++ expect(+ merged?.groups?.map((group) => [+ group.aggregation_group_type_index,+ group.properties?.[0]?.type,+ group.properties?.[0]?.group_type_index,+ ])+ ).toEqual(expected)+ expect(aggregationViolations(existing, merged)).toEqual([])+ })++ // The flag evaluator reads each property by its own type, so a group set can hold a person+ // property or a flag dependency. The backend rule only logs that shape, so this test skips the+ // oracle that copies the rule.+ it.each([+ {+ name: 'a person property',+ stored: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ incoming: { key: 'email', operator: 'icontains', value: '@globex.com' },+ expected: { type: 'person' },+ },+ {+ name: 'a flag dependency',+ stored: [{ key: '42', type: 'flag', operator: 'flag_evaluates_to', value: true }],+ incoming: { key: '42', operator: 'flag_evaluates_to', value: false },+ expected: { type: 'flag' },+ },+ // A new key leaves the set with no source, so the type comes from the stored sets.+ {+ name: 'a flag dependency next to a new key',+ stored: [{ key: '42', type: 'flag', operator: 'flag_evaluates_to', value: true }],+ incoming: { key: '42', operator: 'flag_evaluates_to', value: true },+ added: [{ key: 'seats', operator: 'gt', value: 10 }],+ expected: { type: 'flag' },+ },+ ])('restores the stored type of $name in a group set', ({ stored, incoming, added = [], expected }) => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [{ aggregation_group_type_index: 0, properties: stored, rollout_percentage: 100 }],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [{ properties: [incoming, ...added], rollout_percentage: 100 }],+ })++ expect(merged?.groups?.[0]?.properties?.[0]).toEqual({ ...incoming, ...expected })+ })++ // The property index has to follow the set, not the property it matched in the old group+ // type.+ it.each([+ {+ name: 'the set carries the new index',+ flag: { aggregation_group_type_index: 1 },+ group: { aggregation_group_type_index: 1 },+ property: {},+ },+ { name: 'only the flag level carries it', flag: { aggregation_group_type_index: 1 }, group: {}, property: {} },+ {+ name: 'the agent echoes back the old property index',+ flag: { aggregation_group_type_index: 1 },+ group: { aggregation_group_type_index: 1 },+ property: { type: 'group', group_type_index: 0 },+ },+ {+ name: 'only the property carries it',+ flag: {},+ group: {},+ property: { type: 'group', group_type_index: 1 },+ },+ {+ name: 'the payload echoes the stored flag level and only the property carries it',+ flag: { aggregation_group_type_index: 0 },+ group: {},+ property: { type: 'group', group_type_index: 1 },+ },+ ])('retargets a condition set to another group type when $name', ({ flag, group, property }) => {+ const merged = preserveGroupTargetingFilters(existingGroupFlag, {+ ...flag,+ groups: [+ {+ ...group,+ properties: [{ key: 'plan', operator: 'exact', value: 'pro', ...property }],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties?.[0]).toEqual({+ key: 'plan',+ type: 'group',+ group_type_index: 1,+ operator: 'exact',+ value: 'pro',+ })+ expect(aggregationViolations(existingGroupFlag, merged)).toEqual([])+ })++ // The merge walks both sides by index. A malformed entry on either side must not throw.+ it.each([+ { name: 'null groups on the existing flag', existing: { groups: null } },+ { name: 'a null condition set', existing: { groups: [null] } },+ { name: 'a condition set that is an array', existing: { groups: [[]] } },+ { name: 'null properties', existing: { groups: [{ properties: null }] } },+ ])('passes an incoming payload through unchanged when the existing flag has $name', ({ existing }) => {+ const incoming = { groups: [{ properties: [{ key: 'plan', operator: 'exact', value: 'pro' }] }] }++ expect(preserveGroupTargetingFilters(existing as FlagFilters, incoming)).toEqual(incoming)+ })++ // A collapse leaves every set without a source. Each property takes its type from the stored+ // set that holds its key.+ it('restores a property type from another set when two sets collapse into one', () => {+ const existing = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'seats', type: 'person', operator: 'gt', value: 10 }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [+ {+ properties: [+ { key: 'seats', operator: 'gt', value: 25 },+ { key: 'email', operator: 'icontains', value: '@globex.com' },+ ],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('person')+ expect(merged?.groups?.[0]?.properties?.[1]?.type).toBe('person')+ expect(aggregationViolations(existing, merged)).toEqual([])+ })++ it('restores a person type from another set when the source holds the key only as a group property', () => {+ const existing = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: null,+ properties: [+ { key: 'plan', type: 'person', operator: 'exact', value: 'free' },+ { key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' },+ ],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [+ {+ aggregation_group_type_index: null,+ properties: [{ key: 'plan', operator: 'exact', value: 'enterprise' }],+ rollout_percentage: 100,+ },+ {+ properties: [+ { key: 'plan', operator: 'exact', value: 'free' },+ { key: 'email', operator: 'icontains', value: '@acme.com' },+ ],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties?.[0]?.type).toBe('person')+ expect(aggregationViolations(existing, merged)).toEqual([])+ })++ it('restores a person type in a moved set that states its own group type', () => {+ const existing = {+ aggregation_group_type_index: null,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ { key: 'email', type: 'person', operator: 'icontains', value: '@acme.com' },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'seats', type: 'group', group_type_index: 1, operator: 'gt', value: 10 }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [+ {+ aggregation_group_type_index: 1,+ properties: [{ key: 'seats', operator: 'gt', value: 10 }],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', operator: 'exact', value: 'enterprise' },+ { key: 'email', operator: 'icontains', value: '@acme.com' },+ ],+ rollout_percentage: 100,+ },+ ],+ })++ expect(+ merged?.groups?.map((group) =>+ group.properties?.map((property) => [property.key, property.type, property.group_type_index])+ )+ ).toEqual([+ [['seats', 'group', 1]],+ [+ ['plan', 'group', 0],+ ['email', 'person', undefined],+ ],+ ])+ })++ it('restores a flag dependency in a group set when another set changes its keys', () => {+ const existing = {+ aggregation_group_type_index: 0,+ groups: [+ {+ aggregation_group_type_index: 0,+ properties: [+ { key: 'plan', type: 'group', group_type_index: 0, operator: 'exact', value: 'enterprise' },+ { key: '42', type: 'flag', operator: 'flag_evaluates_to', value: true },+ ],+ rollout_percentage: 100,+ },+ {+ aggregation_group_type_index: 0,+ properties: [{ key: 'seats', type: 'group', group_type_index: 0, operator: 'gt', value: 10 }],+ rollout_percentage: 100,+ },+ ],+ }++ const merged = preserveGroupTargetingFilters(existing, {+ groups: [+ {+ properties: [+ { key: 'plan', operator: 'exact', value: 'enterprise' },+ { key: '42', operator: 'flag_evaluates_to', value: true },+ ],+ rollout_percentage: 100,+ },+ {+ properties: [+ { key: 'seats', operator: 'gt', value: 10 },+ { key: 'region', operator: 'exact', value: 'eu' },+ ],+ rollout_percentage: 100,+ },+ ],+ })++ expect(merged?.groups?.[0]?.properties?.[1]).toEqual({+ key: '42',+ type: 'flag',+ operator: 'flag_evaluates_to',+ value: true,+ })+ })+it('accepts group properties when both type and index are present (no strip)', () => {const incoming = {aggregation_group_type_index: 0,