Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): make creator filter a multi-select (#63051)

ruby childs8b39eaf5feed
diff --git a/frontend/src/lib/components/MemberMultiSelect.tsx b/frontend/src/lib/components/MemberMultiSelect.tsx
index 0d63392d5789..629e489905ce 100644
--- a/frontend/src/lib/components/MemberMultiSelect.tsx
+++ b/frontend/src/lib/components/MemberMultiSelect.tsx
@@ -62,17 +62,36 @@ export function MemberMultiSelect({
setShowPopover(false)
}
+ const handleVisibilityChange = (visible: boolean): void => {
+ setShowPopover(visible)
+ if (visible) {
+ ensureAllMembersLoaded()
+ }
+ }
+
+ // Load members when the selection is non-empty even before the popover opens, so a value
+ // pre-populated from the URL resolves to a name rather than falling back to the default label.
useEffect(() => {
- if (showPopover) {
+ if (value?.length) {
ensureAllMembersLoaded()
}
- }, [showPopover]) // oxlint-disable-line react-hooks/exhaustive-deps
+ }, [value?.length]) // oxlint-disable-line react-hooks/exhaustive-deps
const selectableMembers = filteredMembers.filter((m) => !excludedMembers.includes(m.user.id))
const selectedCount = value?.length || 0
const buttonClass = selectedCount > 0 ? 'min-w-26' : 'w-26'
+ const buttonLabel = ((): string => {
+ if (selectedCount === 0) {
+ return defaultLabel
+ }
+ if (selectedCount > 1) {
+ return `${selectedCount} selected`
+ }
+ return selectedMembersAsUsers[0] ? fullName(selectedMembersAsUsers[0]) : defaultLabel
+ })()
+
return (
<LemonDropdown
closeOnClickInside={false}
@@ -80,7 +99,7 @@ export function MemberMultiSelect({
matchWidth={false}
placement="bottom-start"
actionable
- onVisibilityChange={(visible) => setShowPopover(visible)}
+ onVisibilityChange={handleVisibilityChange}
overlay={
<div className="max-w-100 deprecated-space-y-2">
<LemonInput
@@ -96,7 +115,8 @@ export function MemberMultiSelect({
<li key={member.user.uuid}>
<LemonButton
fullWidth
- role="menuitem"
+ role="menuitemcheckbox"
+ aria-checked={value?.includes(member.user.id) || false}
size="small"
icon={<ProfilePicture size="md" user={member.user} />}
onClick={() => handleMemberToggle(member.user.id)}
@@ -108,6 +128,8 @@ export function MemberMultiSelect({
className="cursor-pointer"
checked={value?.includes(member.user.id) || false}
readOnly
+ tabIndex={-1}
+ aria-hidden
/>
<span>{fullName(member.user)}</span>
</span>
@@ -151,7 +173,7 @@ export function MemberMultiSelect({
children(selectedMembersAsUsers)
) : (
<LemonButton size="small" type="secondary" className={buttonClass} {...buttonProps}>
- {selectedCount > 0 ? `${selectedCount} selected` : defaultLabel}
+ {buttonLabel}
</LemonButton>
)}
</LemonDropdown>
diff --git a/frontend/src/lib/utils/url.test.ts b/frontend/src/lib/utils/url.test.ts
index 53089294009f..1503c838c7d4 100644
--- a/frontend/src/lib/utils/url.test.ts
+++ b/frontend/src/lib/utils/url.test.ts
@@ -1,4 +1,11 @@
-import { getRelativeNextPath, isExternalLink, isURL, parseTagsFilter, toParams } from 'lib/utils/url'
+import {
+ getRelativeNextPath,
+ isExternalLink,
+ isURL,
+ parseNumericArrayFilter,
+ parseTagsFilter,
+ toParams,
+} from 'lib/utils/url'
describe('url utils', () => {
describe('toParams', () => {
@@ -297,4 +304,43 @@ describe('url utils', () => {
})
})
})
+
+ describe('parseNumericArrayFilter()', () => {
+ it('handles numeric arrays', () => {
+ expect(parseNumericArrayFilter([1, 2, 3])).toEqual([1, 2, 3])
+ })
+
+ it('parses a JSON-encoded list', () => {
+ expect(parseNumericArrayFilter('[1,2]')).toEqual([1, 2])
+ })
+
+ it('parses a comma-separated string', () => {
+ expect(parseNumericArrayFilter('1,2')).toEqual([1, 2])
+ })
+
+ it('handles a single number', () => {
+ expect(parseNumericArrayFilter(5)).toEqual([5])
+ })
+
+ it('returns undefined for malformed JSON rather than half-applying it', () => {
+ expect(parseNumericArrayFilter('[5')).toBeUndefined()
+ })
+
+ it('returns undefined for a non-numeric string', () => {
+ expect(parseNumericArrayFilter('abc')).toBeUndefined()
+ })
+
+ it('drops non-numeric entries from a comma-separated string', () => {
+ expect(parseNumericArrayFilter('1,abc,3')).toEqual([1, 3])
+ })
+
+ it('returns undefined for empty string', () => {
+ expect(parseNumericArrayFilter('')).toBeUndefined()
+ })
+
+ it('returns undefined for null and undefined', () => {
+ expect(parseNumericArrayFilter(null)).toBeUndefined()
+ expect(parseNumericArrayFilter(undefined)).toBeUndefined()
+ })
+ })
})
diff --git a/frontend/src/lib/utils/url.ts b/frontend/src/lib/utils/url.ts
index 60bffc458f7a..c80eb7ef4c85 100644
--- a/frontend/src/lib/utils/url.ts
+++ b/frontend/src/lib/utils/url.ts
@@ -93,6 +93,40 @@ export function parseTagsFilter(raw: unknown): string[] | undefined {
return undefined
}
+/** Parse a URL/query param into a list of numeric IDs. Accepts an array, a JSON-encoded list, or a comma-separated string. */
+export function parseNumericArrayFilter(raw: unknown): number[] | undefined {
+ const toNumbers = (values: unknown[]): number[] => values.map((v) => Number(v)).filter((n) => Number.isFinite(n))
+
+ let values: unknown[] | undefined
+
+ if (Array.isArray(raw)) {
+ values = raw
+ } else if (typeof raw === 'number') {
+ values = [raw]
+ } else if (typeof raw === 'string') {
+ const text = raw.trim()
+ if (text.startsWith('[')) {
+ try {
+ const parsed = JSON.parse(text)
+ values = Array.isArray(parsed) ? parsed : [parsed]
+ } catch {
+ // Looks like a JSON list but doesn't parse — treat as no valid IDs rather than
+ // comma-splitting, which would half-apply malformed input (e.g. "[1,2" -> [2]).
+ return undefined
+ }
+ } else {
+ values = text.split(',').map((s) => s.trim())
+ }
+ }
+
+ if (!values) {
+ return undefined
+ }
+
+ const numbers = toNumbers(values.filter((v) => v !== '' && v !== null && v !== undefined))
+ return numbers.length ? numbers : undefined
+}
+
export function stripHTTP(url: string): string {
url = url.replace(/(^[0-9]+_)/, '')
url = url.replace(/(^\w+:|^)\/\//, '')
diff --git a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
index 3c303588ad25..146ae5ece575 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.ts
@@ -11,16 +11,11 @@ import { teamLogic } from 'scenes/teamLogic'
import { FeatureFlagType } from '~/types'
+import type { FeatureFlagModalFilters } from '../experimentsLogic'
import type { selectExistingFeatureFlagModalLogicType } from './selectExistingFeatureFlagModalLogicType'
-export interface FeatureFlagModalFilters {
- active?: string
- created_by_id?: number
- search?: string
- order?: string
- page?: number
- evaluation_runtime?: string
-}
+// Canonical definition lives in experimentsLogic; re-exported so existing importers keep working.
+export type { FeatureFlagModalFilters }
const DEFAULT_FILTERS: FeatureFlagModalFilters = {
active: undefined,
diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsx
index 0ed70e803127..7329327f0f77 100644
--- a/frontend/src/scenes/experiments/Experiments.tsx
+++ b/frontend/src/scenes/experiments/Experiments.tsx
@@ -10,7 +10,7 @@ import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'
import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'
import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'
import { ExperimentsHog } from 'lib/components/hedgehogs'
-import { MemberSelect } from 'lib/components/MemberSelect'
+import { MemberMultiSelect } from 'lib/components/MemberMultiSelect'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
import { dayjs } from 'lib/dayjs'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
@@ -155,16 +155,16 @@ const ExperimentsTableFilters = ({
<span className="ml-1">
<b>Created by</b>
</span>
- <MemberSelect
+ <MemberMultiSelect
defaultLabel="Any user"
- value={filters.created_by_id ?? null}
+ value={filters.created_by_id ?? []}
size="xsmall"
- onChange={(user) => {
- if (!user) {
+ onChange={(userIds) => {
+ if (!userIds.length) {
const { created_by_id, ...restFilters } = filters
onFiltersChange({ ...restFilters, page: 1 }, true)
} else {
- onFiltersChange({ created_by_id: user.id, page: 1 })
+ onFiltersChange({ created_by_id: userIds, page: 1 })
}
}}
/>
diff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.ts
index d901beaa0ddd..6a22401e9ca7 100644
--- a/frontend/src/scenes/experiments/experimentsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentsLogic.ts
@@ -7,7 +7,7 @@ import { LemonTagType, PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
-import { toParams } from 'lib/utils/url'
+import { parseNumericArrayFilter, toParams } from 'lib/utils/url'
import { FLAGS_PER_PAGE, type FeatureFlagsResult, featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'
import { projectLogic } from 'scenes/projectLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -37,7 +37,7 @@ export interface ExperimentsResult extends CountedPaginatedResponse<Experiment>
export interface ExperimentsFilters {
search?: string
status?: ExperimentStatus | 'all'
- created_by_id?: number
+ created_by_id?: number[]
archived?: boolean
page?: number
order?: string
@@ -45,7 +45,7 @@ export interface ExperimentsFilters {
export interface FeatureFlagModalFilters {
active?: string
- created_by_id?: number
+ created_by_id?: number[]
search?: string
order?: string
page?: number
@@ -532,7 +532,7 @@ export const experimentsLogic = kea<experimentsLogicType>([
},
]
| void => {
- const searchParams: Record<string, string | number | boolean> = {
+ const searchParams: Record<string, string | number | boolean | number[]> = {
...values.filters,
}
@@ -559,7 +559,7 @@ export const experimentsLogic = kea<experimentsLogicType>([
},
]
| void => {
- const searchParams: Record<string, string | number | boolean> = {
+ const searchParams: Record<string, string | number | boolean | number[]> = {
...values.filters,
}
@@ -598,7 +598,7 @@ export const experimentsLogic = kea<experimentsLogicType>([
const { page, search, status, created_by_id, order, archived } = searchParams
const pageFiltersFromUrl: Partial<ExperimentsFilters> = {
search,
- created_by_id,
+ created_by_id: parseNumericArrayFilter(created_by_id),
order,
}
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
index af2ec61653c8..0c4a03d41831 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagFilters.tsx
@@ -1,6 +1,6 @@
import { LemonInput, LemonSelect } from '@posthog/lemon-ui'
-import { MemberSelect } from 'lib/components/MemberSelect'
+import { MemberMultiSelect } from 'lib/components/MemberMultiSelect'
import { TagSelect } from 'lib/components/TagSelect'
import { FeatureFlagEvaluationRuntime } from '~/types'
@@ -135,17 +135,15 @@ export function FeatureFlagFiltersSection({
<span className="ml-1">
<b>Created by</b>
</span>
- <MemberSelect
+ <MemberMultiSelect
defaultLabel="Any user"
- value={filters.created_by_id ?? null}
- onChange={(user) => {
- if (!user) {
- if (filters) {
- const { created_by_id, ...restFilters } = filters
- setFeatureFlagsFilters({ ...restFilters, page: 1 }, true)
- }
+ value={filters.created_by_id ?? []}
+ onChange={(userIds) => {
+ if (!userIds.length) {
+ const { created_by_id, ...restFilters } = filters
+ setFeatureFlagsFilters({ ...restFilters, page: 1 }, true)
} else {
- setFeatureFlagsFilters({ created_by_id: user.id, page: 1 })
+ setFeatureFlagsFilters({ created_by_id: userIds, page: 1 })
}
}}
data-attr="feature-flag-select-created-by"
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
index f98dd04477d0..169e2b08713b 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
@@ -7,6 +7,7 @@ import { NEW_FLAG } from 'scenes/feature-flags/featureFlagLogic'
import {
FeatureFlagsTab,
featureFlagsLogic,
+ flagMatchesFilters,
flagMatchesSearch,
flagMatchesStatus,
flagMatchesType,
@@ -156,6 +157,28 @@ describe('flagMatchesType', () => {
})
})
+describe('flagMatchesFilters creator filter', () => {
+ const flagByUser = (id: number | null): FeatureFlagType =>
+ ({
+ ...NEW_FLAG,
+ id: 1,
+ key: 'test',
+ created_by: id == null ? null : ({ id } as FeatureFlagType['created_by']),
+ }) as FeatureFlagType
+
+ it.each<[string, number | null, number[] | undefined, boolean]>([
+ ['no filter set matches any flag', 7, undefined, true],
+ ['no filter set matches a creatorless flag', null, undefined, true],
+ ['no filter set matches a creatorless flag with empty list', null, [], true],
+ ['author in the list matches', 7, [7], true],
+ ['author in a multi-id list matches', 7, [3, 7], true],
+ ['author absent from the list does not match', 7, [3, 5], false],
+ ['creatorless flag is excluded once a filter is set', null, [7], false],
+ ])('%s', (_name, createdById, createdByIdFilter, expected) => {
+ expect(flagMatchesFilters(flagByUser(createdById), { created_by_id: createdByIdFilter })).toBe(expected)
+ })
+})
+
describe('the feature flags logic', () => {
let logic: ReturnType<typeof featureFlagsLogic.build>
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
index 45d08b72016d..aa222ed3d996 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
@@ -7,7 +7,7 @@ import { PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { objectsEqual } from 'lib/utils/objects'
-import { parseTagsFilter, toParams } from 'lib/utils/url'
+import { parseNumericArrayFilter, parseTagsFilter, toParams } from 'lib/utils/url'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { dispatchChangeRequestCreated } from 'scenes/approvals/utils'
import { projectLogic } from 'scenes/projectLogic'
@@ -96,7 +96,8 @@ export function flagMatchesFilters(flag: FeatureFlagType, filters: FeatureFlagsF
flagMatchesSearch(flag, filters.search) &&
flagMatchesStatus(flag, filters.active) &&
flagMatchesType(flag, filters.type) &&
- (!filters.created_by_id || flag.created_by?.id === filters.created_by_id) &&
+ (!filters.created_by_id?.length ||
+ (flag.created_by != null && filters.created_by_id.includes(flag.created_by.id))) &&
(!filters.tags?.length || filters.tags.some((tag) => flag.tags?.includes(tag))) &&
(!filters.evaluation_runtime || flag.evaluation_runtime === filters.evaluation_runtime)
)
@@ -125,7 +126,7 @@ export interface FeatureFlagsResult extends CountedPaginatedResponse<FeatureFlag
export interface FeatureFlagsFilters {
active?: string
- created_by_id?: number
+ created_by_id?: number[]
type?: string
search?: string
order?: string
@@ -381,7 +382,7 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
},
]
| void => {
- const searchParams: Record<string, string | number | string[]> = {
+ const searchParams: Record<string, string | number | string[] | number[]> = {
...values.filters,
}
@@ -420,7 +421,7 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
const { page, created_by_id, active, type, search, order, evaluation_runtime, tags } = searchParams
const pageFiltersFromUrl: Partial<FeatureFlagsFilters> = {
- created_by_id,
+ created_by_id: parseNumericArrayFilter(created_by_id),
type,
order,
evaluation_runtime,
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index ff8fe57aaf1c..180c67c559ed 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -46,7 +46,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.result_serialization import strip_step_sessions
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, parse_created_by_ids
from products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notifications.backend.facade.api import (
@@ -2466,7 +2466,9 @@ class ExperimentService:
created_by_id = query_params.get("created_by_id")
if created_by_id:
- queryset = queryset.filter(created_by_id=created_by_id)
+ user_ids = parse_created_by_ids(created_by_id)
+ if user_ids:
+ queryset = queryset.filter(created_by_id__in=user_ids)
archived = query_params.get("archived")
if archived is not None:
@@ -2607,7 +2609,9 @@ class ExperimentService:
queryset = queryset.filter(active=active_bool)
if created_by_id:
- queryset = queryset.filter(created_by_id=created_by_id)
+ user_ids = parse_created_by_ids(created_by_id)
+ if user_ids:
+ queryset = queryset.filter(created_by_id__in=user_ids)
if evaluation_runtime:
queryset = queryset.filter(evaluation_runtime=evaluation_runtime)
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index f939513d6486..9343e85d46af 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -176,8 +176,11 @@ def _slugify_feature_flag_key(name: str, *, team_id: int) -> str:
OpenApiParameter(
name="created_by_id",
location=OpenApiParameter.QUERY,
- type=int,
- description="Filter to experiments created by the given user ID.",
+ type=str,
+ description=(
+ "Filter to experiments created by the given user(s). Accepts a single user ID, "
+ "or a JSON-encoded / comma-separated list of user IDs to match any of them."
+ ),
required=False,
),
OpenApiParameter(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 45007ec49ac5..ba99d3c8c16f 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -1,3 +1,4 @@
+import json
from copy import deepcopy
from datetime import timedelta
from decimal import Decimal
@@ -3405,6 +3406,41 @@ class TestExperimentService(APIBaseTest):
assert set(queryset.values_list("name", flat=True)) == expected_names
+ @parameterized.expand(
+ [
+ # (name, format_filter, expected_names)
+ ("json_list", lambda ids: json.dumps([ids[0], ids[1]]), {"Creator self", "Creator other"}),
+ ("comma_separated", lambda ids: f"{ids[0]},{ids[2]}", {"Creator self", "Creator third"}),
+ ("single_id", lambda ids: str(ids[1]), {"Creator other"}),
+ ("no_match", lambda ids: json.dumps([ids[3]]), set()),
+ ]
+ )
+ def test_filter_experiments_queryset_filters_by_multiple_created_by_ids(
+ self, _name, format_filter, expected_names
+ ) -> None:
+ service = self._service()
+ other_user = self._create_user("[email protected]")
+ third_user = self._create_user("[email protected]")
+ unrelated_user = self._create_user("[email protected]")
+
+ service.create_experiment(name="Creator self", feature_flag_key="created-by-self")
+ ExperimentService(team=self.team, user=other_user).create_experiment(
+ name="Creator other",
+ feature_flag_key="created-by-other",
+ )
+ ExperimentService(team=self.team, user=third_user).create_experiment(
+ name="Creator third",
+ feature_flag_key="created-by-third",
+ )
+
+ ids = [self.user.id, other_user.id, third_user.id, unrelated_user.id]
+ queryset = service.filter_experiments_queryset(
+ Experiment.objects.filter(team=self.team),
+ action="list",
+ query_params={"created_by_id": format_filter(ids)},
+ )
+ assert set(queryset.values_list("name", flat=True)) == expected_names
+
@parameterized.expand(
[
("ascending", "duration", ["Short", "Long"]),
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index c3b0c1c1e352..5d37f6b09af1 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -990,9 +990,9 @@ export type ExperimentsListParams = {
*/
archived?: boolean
/**
- * Filter to experiments created by the given user ID.
+ * Filter to experiments created by the given user(s). Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
- created_by_id?: number
+ created_by_id?: string
/**
* Filter to experiments whose metrics reference this event name. Matches events used directly in metric queries as well as events behind any actions those metrics reference.
*/
diff --git a/products/experiments/mcp/tools.yaml b/products/experiments/mcp/tools.yaml
index 3703c0fcd0a5..adf76e4869cf 100644
--- a/products/experiments/mcp/tools.yaml
+++ b/products/experiments/mcp/tools.yaml
@@ -405,8 +405,6 @@ tools:
cast: string-int
offset:
cast: string-int
- created_by_id:
- cast: string-int
feature_flag_id:
cast: string-int
ui_app: experiment-list
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 04aad64686c5..19530f573646 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -103,6 +103,46 @@ BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"
REALTIME_COHORT_FLAG_TARGETING_FLAG = "realtime-cohort-flag-targeting"
EARLY_EXIT_FLAG = "feature-flag-early-exit"
+
+def parse_created_by_ids(value: Any) -> list[int]:
+ """Parse a `created_by_id` filter value into a list of user IDs.
+
+ Accepts a single int/str, a comma-separated string, or a JSON-encoded list
+ (as sent by the frontend creator multi-select). Keeps the original
+ single-value query param working for existing API consumers.
+ """
+ if value is None:
+ return []
+ if isinstance(value, bool):
+ return []
+ if isinstance(value, int):
+ return [value]
+ if isinstance(value, str):
+ text = value.strip()
+ if not text:
+ return []
+ if text.startswith("["):
+ try:
+ value = json.loads(text)
+ except (json.JSONDecodeError, ValueError, RecursionError):
+ # Looks like a JSON list but doesn't parse — treat as no valid IDs
+ # rather than comma-splitting, which would half-apply malformed input
+ # (e.g. "[1,2" -> ["[1", "2"] -> silently filters by user 2).
+ return []
+ else:
+ value = text.split(",")
+ if not isinstance(value, list):
+ value = [value]
+
+ ids: list[int] = []
+ for item in value:
+ try:
+ ids.append(int(item))
+ except (TypeError, ValueError):
+ continue
+ return ids
+
+
# Fields that Rust's FeatureFlag struct expects for historical evaluation
RUST_FLAG_FIELDS = (
"name",
@@ -2553,7 +2593,10 @@ class FeatureFlagViewSet(
OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
required=False,
- description="The User ID which initially created the feature flag.",
+ description=(
+ "Filter by the user(s) who created the feature flag. Accepts a single user ID, "
+ "or a JSON-encoded / comma-separated list of user IDs to match any of them."
+ ),
),
OpenApiParameter(
"search",
@@ -3234,7 +3277,9 @@ class FeatureFlagViewSet(
if key == "active":
queryset = filter_flags_by_active_param(queryset, value)
elif key == "created_by_id":
- queryset = queryset.filter(created_by_id=value)
+ user_ids = parse_created_by_ids(value)
+ if user_ids:
+ queryset = queryset.filter(created_by_id__in=user_ids)
elif key == "search":
if isinstance(value, str):
value = value.strip()
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index d5d7e1601f7b..3bf0ac41228c 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -46,7 +46,7 @@ from products.cohorts.backend.models.util import CohortErrorCode, get_friendly_e
from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
-from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, parse_created_by_ids
from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload
from products.feature_flags.backend.flag_status import FeatureFlagStatus
from products.feature_flags.backend.models.feature_flag import (
@@ -5651,6 +5651,44 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert len(response["results"]) == 1
assert response["results"][0]["key"] == "green_button"
+ @parameterized.expand(
+ [
+ # (name, format_filter, expected_keys)
+ ("json_list", lambda ids: json.dumps([ids[0], ids[1]]), {"red_button", "blue_button"}),
+ ("comma_separated", lambda ids: f"{ids[0]},{ids[2]}", {"red_button", "orange_button"}),
+ ("single_id", lambda ids: str(ids[1]), {"blue_button"}),
+ ("no_match", lambda ids: json.dumps([ids[3]]), set()),
+ ]
+ )
+ def test_get_flags_with_multiple_created_by_id_filter(self, _name, format_filter, expected_keys):
+ another_user = User.objects.create(email="[email protected]")
+ third_user = User.objects.create(email="[email protected]")
+ unrelated_user = User.objects.create(email="[email protected]")
+ FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
+ FeatureFlag.objects.create(team=self.team, created_by=another_user, key="blue_button")
+ FeatureFlag.objects.create(team=self.team, created_by=third_user, key="orange_button")
+
+ ids = [self.user.id, another_user.id, third_user.id, unrelated_user.id]
+ response = self.client.get(f"/api/projects/@current/feature_flags?created_by_id={format_filter(ids)}")
+ assert {flag["key"] for flag in response.json()["results"]} == expected_keys
+
+ @parameterized.expand(
+ [
+ ("none", None, []),
+ ("bool_true", True, []),
+ ("int", 42, [42]),
+ ("single_str", "42", [42]),
+ ("empty_str", "", []),
+ ("comma_separated", "1,2", [1, 2]),
+ ("comma_with_invalid", "1,abc,3", [1, 3]),
+ ("json_list", "[1, 2]", [1, 2]),
+ ("non_numeric", "abc", []),
+ ("malformed_json", "[5", []),
+ ]
+ )
+ def test_parse_created_by_ids(self, _name, value, expected):
+ assert parse_created_by_ids(value) == expected
+
def test_get_flags_with_type_filters(self):
feature_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="red_button")
Experiment.objects.create(
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index f9f21a06fc88..1e26dff7cb5e 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1388,7 +1388,7 @@ export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive
/**
- * The User ID which initially created the feature flag.
+ * Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
created_by_id?: string
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d7522ee85dea..f6b8898dd7a1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -55832,9 +55832,9 @@ export namespace Schemas {
*/
archived?: boolean;
/**
- * Filter to experiments created by the given user ID.
+ * Filter to experiments created by the given user(s). Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
- created_by_id?: number;
+ created_by_id?: string;
/**
* Filter to experiments whose metrics reference this event name. Matches events used directly in metric queries as well as events behind any actions those metrics reference.
*/
@@ -55995,7 +55995,7 @@ export namespace Schemas {
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive;
/**
- * The User ID which initially created the feature flag.
+ * Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.
*/
created_by_id?: string;
/**
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 0d0366951152..5fd01ba2b72c 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -120,7 +120,12 @@ export const ExperimentsListParams = /* @__PURE__ */ zod.object({
export const ExperimentsListQueryParams = /* @__PURE__ */ zod.object({
archived: zod.boolean().optional().describe('Filter by archived state. Defaults to non-archived experiments only.'),
- created_by_id: zod.number().optional().describe('Filter to experiments created by the given user ID.'),
+ created_by_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Filter to experiments created by the given user(s). Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.'
+ ),
event: zod
.string()
.optional()
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index 7cb2f1411722..dadd0fdc011b 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -55,7 +55,12 @@ export const FeatureFlagsListParams = /* @__PURE__ */ zod.object({
export const FeatureFlagsListQueryParams = /* @__PURE__ */ zod.object({
active: zod.enum(['STALE', 'false', 'true']).optional(),
- created_by_id: zod.string().optional().describe('The User ID which initially created the feature flag.'),
+ created_by_id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.'
+ ),
evaluation_runtime: zod
.enum(['all', 'client', 'server'])
.optional()
diff --git a/services/mcp/src/tools/generated/experiments.ts b/services/mcp/src/tools/generated/experiments.ts
index 9b81efb97869..766ff3471aa7 100644
--- a/services/mcp/src/tools/generated/experiments.ts
+++ b/services/mcp/src/tools/generated/experiments.ts
@@ -387,7 +387,6 @@ const ExperimentListSchema = ExperimentsListQueryParams.extend({
),
limit: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['limit']).optional(),
offset: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['offset']).optional(),
- created_by_id: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['created_by_id']).optional(),
feature_flag_id: z.preprocess(castStringToInt, ExperimentsListQueryParams.shape['feature_flag_id']).optional(),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json
index 27bf6e934c48..7671593fbf8e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-get-all.json
@@ -6,8 +6,8 @@
"type": "boolean"
},
"created_by_id": {
- "description": "Filter to experiments created by the given user ID.",
- "type": "number"
+ "description": "Filter to experiments created by the given user(s). Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.",
+ "type": "string"
},
"event": {
"description": "Filter to experiments whose metrics reference this event name. Matches events used directly in metric queries as well as events behind any actions those metrics reference.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json
index 27bf6e934c48..7671593fbf8e 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-list.json
@@ -6,8 +6,8 @@
"type": "boolean"
},
"created_by_id": {
- "description": "Filter to experiments created by the given user ID.",
- "type": "number"
+ "description": "Filter to experiments created by the given user(s). Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.",
+ "type": "string"
},
"event": {
"description": "Filter to experiments whose metrics reference this event name. Matches events used directly in metric queries as well as events behind any actions those metrics reference.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
index edb7dda5f18a..1b10662e4769 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json
@@ -6,7 +6,7 @@
"type": "string"
},
"created_by_id": {
- "description": "The User ID which initially created the feature flag.",
+ "description": "Filter by the user(s) who created the feature flag. Accepts a single user ID, or a JSON-encoded / comma-separated list of user IDs to match any of them.",
"type": "string"
},
"evaluation_runtime": {
diff --git a/services/mcp/tests/unit/experiments-schema-cast.test.ts b/services/mcp/tests/unit/experiments-schema-cast.test.ts
index e30443708d40..ed16d7c2b2c8 100644
--- a/services/mcp/tests/unit/experiments-schema-cast.test.ts
+++ b/services/mcp/tests/unit/experiments-schema-cast.test.ts
@@ -99,11 +99,21 @@ describe('experiment-list — query-param casts', () => {
it.each([
['limit', '50', 50],
['offset', '100', 100],
- ['created_by_id', '42', 42],
['feature_flag_id', '7', 7],
] as const)('casts stringified %s', (field, raw, expected) => {
const parsed = parseWith(schema, { [field]: raw })
expect(parsed[field]).toBe(expected)
expect(typeof parsed[field]).toBe('number')
})
+
+ // `created_by_id` accepts a single user ID or a comma-separated / JSON-encoded
+ // list, so it stays a string rather than casting to a number.
+ it.each([
+ ['single id', '42'],
+ ['comma-separated list', '42,7'],
+ ] as const)('passes through created_by_id as a string: %s', (_label, raw) => {
+ const parsed = parseWith(schema, { created_by_id: raw })
+ expect(parsed.created_by_id).toBe(raw)
+ expect(typeof parsed.created_by_id).toBe('string')
+ })
})