: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(flags): match underscores and hyphens in flag list search (#111665)
posthog[bot]3bfacc7f0ebd
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.tsindex 611458808b23..c726ba677305 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts@@ -72,6 +72,9 @@ describe('flagMatchesSearch', () => {[webUnderscoreFlag, 'web dash', true], // "web dash" matches "web_dashboard"[webSpaceFlag, 'web ana', true], // "web ana" matches "web analytics"[webAnalyticsFlag, 'web analytics', true], // Should match name+ [webAnalyticsFlag, 'WEB_ANALYTICS', true], // Pasted code constant matches hyphenated key+ [webUnderscoreFlag, 'web-dashboard', true],+ [webAnalyticsFlag, 'web_-analytics', true], // Mixed separator runs collapse// Experiment name searches[flagWithExperiment, 'experiment test', true], // Should match experiment name@@ -82,6 +85,12 @@ describe('flagMatchesSearch', () => {[webAnalyticsFlag, 'web mobile', false], // "mobile" not in "web-analytics"[webUnderscoreFlag, 'web mobile', false], // "mobile" not in flag[flagWithExperiment, 'mobile test', false], // "mobile" not in flag or experiment+ [webAnalyticsFlag, 'WEB_MOBILE', false],+ [webAnalyticsFlag, '_', false], // Separator-only query matches literally, not every flag+ [webUnderscoreFlag, '_', true],+ [webAnalyticsFlag, 'ana_', false], // A trailing separator stays required+ [webAnalyticsFlag, '_lytics', false], // A leading separator stays required+ [webUnderscoreFlag, '-dashboard', true],// Single word searches (existing behavior)[webAnalyticsFlag, 'web', true],diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex ed68c749fb7b..fff10989b255 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -50,9 +50,16 @@ export function flagMatchesSearch(flag: FeatureFlagType, search?: string): boole.filter(Boolean).join(' ') || ''- // Use regex pattern matching like the backend - escape metacharacters then replace spaces with word boundary pattern- const escapedSearchValue = searchValue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')- const regexPattern = escapedSearchValue.replace(/\s+/g, '[\\s\\-_]*')+ // Match the backend: spaces, hyphens, and underscores are one separator class, so MY_FLAG finds my-flag+ // A query of only separators has no parts, so match it literally rather than with a pattern that matches every flag+ // A leading or trailing separator stays required, so _prod does not find production+ const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+ const parts = searchValue.split(/[\s\-_]+/).filter(Boolean)+ const leadingSeparator = /^[\s\-_]/.test(searchValue) ? '[\\s\\-_]' : ''+ const trailingSeparator = /[\s\-_]$/.test(searchValue) ? '[\\s\\-_]' : ''+ const regexPattern = parts.length+ ? leadingSeparator + parts.map(escapeRegex).join('[\\s\\-_]*') + trailingSeparator+ : escapeRegex(searchValue)try {const regex = new RegExp(regexPattern, 'i')diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex ddd3878dfb85..5a29b0090e1a 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -3567,7 +3567,10 @@ class BulkDeleteFiltersSerializer(serializers.Serializer):)search = serializers.CharField(required=False,- help_text="Search by feature flag key or name (case-insensitive).",+ help_text=(+ "Search by feature flag key or name (case-insensitive). "+ "Spaces, underscores, and hyphens count as the same separator."+ ),)type = serializers.ChoiceField(choices=["boolean", "multivariant", "experiment", "remote_config"],@@ -4121,7 +4124,10 @@ class FeatureFlagViewSet(OpenApiTypes.STR,location=OpenApiParameter.QUERY,required=False,- description="Search by feature flag key or name. Case insensitive.",+ description=(+ "Search by feature flag key or name. Case insensitive. "+ "Spaces, underscores, and hyphens count as the same separator."+ ),),OpenApiParameter("key",@@ -5397,9 +5403,19 @@ class FeatureFlagViewSet(if len(value) > 200:raise serializers.ValidationError("Search term cannot exceed 200 characters")- # Escape regex metacharacters first, then replace spaces with word boundary pattern- escaped_value = re.escape(value)- regex_pattern = escaped_value.replace(r"\ ", r"[\s\-_]*")+ # Treat spaces, hyphens, and underscores as one separator class, so a pasted+ # MY_FLAG_KEY finds my-flag-key. A query of only separators has no parts, and an empty+ # join matches every flag, which bulk_delete would then delete, so match it literally.+ # A leading or trailing separator stays required, so _prod does not find production.+ parts = [part for part in re.split(r"[\s\-_]+", value) if part]+ if parts:+ regex_pattern = r"[\s\-_]*".join(re.escape(part) for part in parts)+ if re.match(r"[\s\-_]", value):+ regex_pattern = r"[\s\-_]" + regex_pattern+ if re.search(r"[\s\-_]$", value):+ regex_pattern += r"[\s\-_]"+ else:+ regex_pattern = re.escape(value)queryset = queryset.filter(Q(key__iregex=regex_pattern)| Q(name__iregex=regex_pattern)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 652ba8a2d4b8..78dfb4dd6aaa 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -7249,6 +7249,26 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):matched_keys = {result["key"] for result in data["results"]}assert "web_dashboard" in matched_keys, f"Expected 'web_dashboard' in {matched_keys}"+ # Underscores and hyphens in the query match any separator, e.g. a pasted code constant+ response = self.client.get(f"/api/projects/@current/feature_flags?search=WEB_ANALYTICS")+ matched_keys = {result["key"] for result in response.json()["results"]}+ assert {"web-analytics", "web analytics"}.issubset(matched_keys), matched_keys+ assert "mobile-analytics" not in matched_keys++ response = self.client.get(f"/api/projects/@current/feature_flags?search=web-dash")+ matched_keys = {result["key"] for result in response.json()["results"]}+ assert "web_dashboard" in matched_keys, matched_keys++ # A separator-only query matches that separator literally instead of matching every flag+ response = self.client.get(f"/api/projects/@current/feature_flags?search=_")+ matched_keys = {result["key"] for result in response.json()["results"]}+ assert "web_dashboard" in matched_keys, matched_keys+ assert not {"web-analytics", "mobile-analytics"} & matched_keys, matched_keys++ for search, expected in (("ana_", set()), ("_lytics", set()), ("-dashboard", {"web_dashboard"})):+ response = self.client.get(f"/api/projects/@current/feature_flags?search={search}")+ assert {flag["key"] for flag in response.json()["results"]} == expected, search+# Test single word still worksresponse = self.client.get(f"/api/projects/@current/feature_flags?search=web")data = response.json()diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 3c334e3cc42d..a243901f07ee 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1617,7 +1617,7 @@ export interface BulkDeleteFiltersApi {active?: ActiveEnumApi/** Filter to flags created by a specific user ID. */created_by_id?: number- /** Search by feature flag key or name (case-insensitive). */+ /** Search by feature flag key or name (case-insensitive). Spaces, underscores, and hyphens count as the same separator. */search?: string/** Filter by flag type.*@@ -2174,7 +2174,7 @@ export type FeatureFlagsListParams = {*/offset?: number/**- * Search by feature flag key or name. Case insensitive.+ * Search by feature flag key or name. Case insensitive. Spaces, underscores, and hyphens count as the same separator.*/search?: string/**diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 13279a3733df..44d5b066010a 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -1228,7 +1228,12 @@ export const FeatureFlagsBulkDeleteCreateBody = /* @__PURE__ */ zod.object({"'true' and 'false' filter on serving state, the flag's `active` column. 'STALE' returns enabled flags only, so a disabled flag is never STALE. An enabled flag matches when its last recorded `$feature_flag_called` event is more than 30 days old. With no recorded event, it matches when it is at least 30 days old and either stores `filters` as `{}` or serves one result to everyone through a release condition at 100% with no property filters. A flag with no recorded event and an empty `groups` list does not match, even when its `status` reads STALE. The reverse also happens: a multivariate flag matches when a variant is at 100% under a release condition at 100% with no property filters, or when that condition names a variant. Its `status` can still read ACTIVE, because an earlier variant in the list or an earlier targeted condition can serve a different result. In a flag of either type that mixes person and group aggregation, the filter also counts a group-aggregated condition at 100% with no property filters, which `status` does not. An SDK that sends no `$feature_flag_called` event leaves no record, so a STALE flag can still be in use.\n\n\* `true` - true\n\* `false` - false\n\* `STALE` - STALE"),created_by_id: zod.number().optional().describe('Filter to flags created by a specific user ID.'),- search: zod.string().optional().describe('Search by feature flag key or name (case-insensitive).'),+ search: zod+ .string()+ .optional()+ .describe(+ 'Search by feature flag key or name (case-insensitive). Spaces, underscores, and hyphens count as the same separator.'+ ),type: zod.enum(['boolean', 'multivariant', 'experiment', 'remote_config']).describe(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0dbb5d977db5..e13f3fd217cf 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19100,7 +19100,7 @@ export namespace Schemas {active?: ActiveEnum;/** Filter to flags created by a specific user ID. */created_by_id?: number;- /** Search by feature flag key or name (case-insensitive). */+ /** Search by feature flag key or name (case-insensitive). Spaces, underscores, and hyphens count as the same separator. */search?: string;/** Filter by flag type.*@@ -120800,7 +120800,7 @@ export namespace Schemas {*/offset?: number;/**- * Search by feature flag key or name. Case insensitive.+ * Search by feature flag key or name. Case insensitive. Spaces, underscores, and hyphens count as the same separator.*/search?: string;/**diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex edc16267ad4c..fc68f92bd901 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -123,7 +123,12 @@ export const FeatureFlagsListQueryParams = () => zod.object({key: zod.string().optional().describe('Filter by exact feature flag key match. Case insensitive.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),- search: zod.string().optional().describe('Search by feature flag key or name. Case insensitive.'),+ search: zod+ .string()+ .optional()+ .describe(+ 'Search by feature flag key or name. Case insensitive. Spaces, underscores, and hyphens count as the same separator.'+ ),tags: zod.string().optional().describe('JSON-encoded list of tag names to filter feature flags by.'),type: zod.enum(['boolean', 'experiment', 'multivariant', 'remote_config']).optional(),})@@ -1182,7 +1187,12 @@ export const FeatureFlagsBulkDeleteCreateBody = () => zod.object({"'true' and 'false' filter on serving state, the flag's `active` column. 'STALE' returns enabled flags only, so a disabled flag is never STALE. An enabled flag matches when its last recorded `$feature_flag_called` event is more than 30 days old. With no recorded event, it matches when it is at least 30 days old and either stores `filters` as `{}` or serves one result to everyone through a release condition at 100% with no property filters. A flag with no recorded event and an empty `groups` list does not match, even when its `status` reads STALE. The reverse also happens: a multivariate flag matches when a variant is at 100% under a release condition at 100% with no property filters, or when that condition names a variant. Its `status` can still read ACTIVE, because an earlier variant in the list or an earlier targeted condition can serve a different result. In a flag of either type that mixes person and group aggregation, the filter also counts a group-aggregated condition at 100% with no property filters, which `status` does not. An SDK that sends no `$feature_flag_called` event leaves no record, so a STALE flag can still be in use.\n\n\* `true` - true\n\* `false` - false\n\* `STALE` - STALE"),created_by_id: zod.number().optional().describe('Filter to flags created by a specific user ID.'),- search: zod.string().optional().describe('Search by feature flag key or name (case-insensitive).'),+ search: zod+ .string()+ .optional()+ .describe(+ 'Search by feature flag key or name (case-insensitive). Spaces, underscores, and hyphens count as the same separator.'+ ),type: zod.enum(['boolean', 'multivariant', 'experiment', 'remote_config']).describe(diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.jsonindex 0b4f7fa72f96..726b3bdf9240 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flags-bulk-delete-create.json@@ -38,7 +38,7 @@"type": "boolean"},"search": {- "description": "Search by feature flag key or name (case-insensitive).",+ "description": "Search by feature flag key or name (case-insensitive). Spaces, underscores, and hyphens count as the same separator.","type": "string"},"tags": {