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(llma): let Max list stale feature flags in one filtered call (#62749)

Patricio7e9c7747f1a2
diff --git a/ee/hogai/chat_agent/toolkit.py b/ee/hogai/chat_agent/toolkit.py
index d17209560fc2..5ccbe471a771 100644
--- a/ee/hogai/chat_agent/toolkit.py
+++ b/ee/hogai/chat_agent/toolkit.py
@@ -24,6 +24,7 @@ from ee.hogai.tools import (
CreateFormTool,
CreateNotebookTool,
ListDataTool,
+ ListFeatureFlagsTool,
ManageMemoriesTool,
ReadDataTool,
ReadTaxonomyTool,
@@ -48,6 +49,7 @@ DEFAULT_TOOLS: list[type[MaxTool]] = [
ReadDataTool,
SearchTool,
ListDataTool,
+ ListFeatureFlagsTool,
TodoWriteTool,
SwitchModeTool,
CreateFormTool,
diff --git a/ee/hogai/context/entity_search/context.py b/ee/hogai/context/entity_search/context.py
index ad48524a55f7..4a965559b02c 100644
--- a/ee/hogai/context/entity_search/context.py
+++ b/ee/hogai/context/entity_search/context.py
@@ -26,6 +26,11 @@ from products.cohorts.backend.models.cohort import Cohort
from products.customer_analytics.backend.models import Account
from products.dashboards.backend.models.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.flag_status import (
+ FeatureFlagStatus,
+ FeatureFlagStatusChecker,
+ filter_flags_by_active_param,
+)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
from products.product_analytics.backend.models.insight import Insight
@@ -240,6 +245,9 @@ class EntitySearchContext:
elif entity_type == "account":
# Account uses a fail-closed manager, so it can't go through the shared FTS path
return await self._list_accounts(limit, offset)
+ elif entity_type == "feature_flag":
+ # Specialized queryset so we can surface each flag's status
+ return await self.list_feature_flags(limit, offset)
else:
# Fetch database entities
db_results, _, maybe_count = await database_sync_to_async(search_entities_fts, thread_sensitive=False)(
@@ -378,6 +386,69 @@ class EntitySearchContext:
for account in accounts
]
+ async def list_feature_flags(
+ self, limit: int = 100, offset: int = 0, active_filter: str | None = None
+ ) -> tuple[list[dict[str, Any]], int]:
+ """
+ List feature flags, newest first, surfacing each flag's status so stale flags can be
+ identified without reading them one by one. `active_filter` ("STALE"/"true"/"false")
+ reuses the same backend filter as the feature_flags API.
+ """
+ return await database_sync_to_async(self._list_feature_flags_sync, thread_sensitive=False)(
+ limit, offset, active_filter
+ )
+
+ def _list_feature_flags_sync(
+ self, limit: int = 100, offset: int = 0, active_filter: str | None = None
+ ) -> tuple[list[dict[str, Any]], int]:
+ # Resource-level gate: filter_queryset_by_access_level only prunes object-level denials, so a
+ # role without feature flag access would still see flags here (also reachable via list_data).
+ if not self.user_access_control.check_access_level_for_resource("feature_flag", "viewer"):
+ return [], 0
+
+ queryset = self.user_access_control.filter_queryset_by_access_level(
+ FeatureFlag.objects.filter(team=self._team, deleted=False)
+ )
+ if active_filter is not None:
+ queryset = filter_flags_by_active_param(queryset, active_filter)
+ queryset = queryset.order_by("-updated_at")
+
+ total_count = queryset.count()
+ flags = list(queryset[offset : offset + limit])
+
+ all_entities: list[dict[str, Any]] = []
+ for flag in flags:
+ status, _ = FeatureFlagStatusChecker(feature_flag=flag).get_status()
+ # Map to the tool's stale/enabled/disabled vocabulary. The checker reports ACTIVE for
+ # disabled flags (it skips staleness for them) and "active" isn't a value the tool
+ # exposes, so derive the label from `active` + STALE instead of using status.value.
+ if not flag.active:
+ display_status = "disabled"
+ elif status == FeatureFlagStatus.STALE:
+ display_status = "stale"
+ else:
+ display_status = "enabled"
+ all_entities.append(
+ {
+ "type": "feature_flag",
+ "result_id": str(flag.id),
+ "extra_fields": {
+ "key": flag.key,
+ "name": flag.name,
+ "status": display_status,
+ "active": flag.active,
+ "rollout": self._flag_rollout_summary(flag),
+ },
+ }
+ )
+ return all_entities, total_count
+
+ def _flag_rollout_summary(self, flag: FeatureFlag) -> str | None:
+ """Highest release-condition rollout percentage, as a display hint (not staleness logic)."""
+ groups = (flag.filters or {}).get("groups", [])
+ percentages = [g.get("rollout_percentage") for g in groups if g.get("rollout_percentage") is not None]
+ return f"{max(percentages)}%" if percentages else None
+
async def _search_accounts(self, query: str) -> tuple[list[dict[str, Any]], int]:
"""Search accounts by name or external id."""
return await database_sync_to_async(self._search_accounts_sync, thread_sensitive=False)(query)
diff --git a/ee/hogai/context/entity_search/test/test_context.py b/ee/hogai/context/entity_search/test/test_context.py
index 229362f8066e..6c5f0b99c23b 100644
--- a/ee/hogai/context/entity_search/test/test_context.py
+++ b/ee/hogai/context/entity_search/test/test_context.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
import pytest
from posthog.test.base import NonAtomicBaseTest
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
@@ -405,6 +407,109 @@ class TestEntitySearchContext(NonAtomicBaseTest):
assert entities == []
assert total == 0
+ async def test_list_entities_feature_flag_surfaces_status(self):
+ await FeatureFlag.objects.acreate(
+ team=self.team, key="my-flag", name="My flag", active=True, created_by=self.user
+ )
+
+ entities, total = await self.context.list_entities("feature_flag", limit=10, offset=0)
+
+ assert total == 1
+ assert len(entities) == 1
+ assert entities[0]["type"] == "feature_flag"
+ assert entities[0]["extra_fields"]["key"] == "my-flag"
+ # A fresh flag with no usage data is enabled (status uses the tool's vocabulary, not "active")
+ assert entities[0]["extra_fields"]["status"] == "enabled"
+ assert entities[0]["extra_fields"]["active"] is True
+
+ # Status shows up as a column in the formatted output (assert the rendered boolean, since
+ # the literal "active" also appears as the status value)
+ formatted = self.context.format_entities(entities)
+ assert "status" in formatted
+ assert "True" in formatted
+
+ async def test_list_feature_flags_stale_filter(self):
+ # Config-based stale: 30+ days old, no usage data, fully rolled out to 100%
+ stale_flag = await FeatureFlag.objects.acreate(
+ team=self.team,
+ key="stale-flag",
+ active=True,
+ created_at=timezone.now() - timedelta(days=60),
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ created_by=self.user,
+ )
+ # Active: freshly created, no usage data yet
+ await FeatureFlag.objects.acreate(team=self.team, key="fresh-flag", active=True, created_by=self.user)
+
+ entities, total = await self.context.list_feature_flags(limit=10, offset=0, active_filter="STALE")
+
+ assert total == 1
+ assert len(entities) == 1
+ assert entities[0]["result_id"] == str(stale_flag.id)
+ assert entities[0]["extra_fields"]["status"] == "stale"
+ assert entities[0]["extra_fields"]["rollout"] == "100%"
+
+ async def test_list_entities_feature_flag_pagination(self):
+ for i in range(5):
+ await FeatureFlag.objects.acreate(team=self.team, key=f"flag-{i}", active=True, created_by=self.user)
+
+ entities, total = await self.context.list_entities("feature_flag", limit=2, offset=2)
+
+ assert total == 5
+ # Newest-first: offset=2 of the descending list is flag-2, flag-1
+ assert [e["extra_fields"]["key"] for e in entities] == ["flag-2", "flag-1"]
+
+ async def test_list_feature_flags_disabled_shows_disabled_status(self):
+ # The status checker reports ACTIVE for disabled flags; the listing should show "disabled"
+ await FeatureFlag.objects.acreate(team=self.team, key="off-flag", active=False, created_by=self.user)
+
+ entities, _ = await self.context.list_feature_flags(limit=10, offset=0, active_filter="false")
+
+ assert len(entities) == 1
+ assert entities[0]["extra_fields"]["status"] == "disabled"
+ assert entities[0]["extra_fields"]["active"] is False
+
+ async def test_list_feature_flags_denied_without_resource_access(self):
+ # A role without feature flag viewer access must not receive any flag metadata
+ await FeatureFlag.objects.acreate(team=self.team, key="some-flag", active=True, created_by=self.user)
+
+ with patch.object(
+ EntitySearchContext,
+ "user_access_control",
+ new_callable=PropertyMock,
+ ) as mock_uac:
+ mock_uac.return_value.check_access_level_for_resource.return_value = False
+
+ entities, total = await self.context.list_feature_flags(limit=10, offset=0)
+
+ assert entities == []
+ assert total == 0
+
+ async def test_list_entities_feature_flag_applies_access_control(self):
+ flag1 = await FeatureFlag.objects.acreate(
+ team=self.team, key="accessible-flag", active=True, created_by=self.user
+ )
+ flag2 = await FeatureFlag.objects.acreate(
+ team=self.team, key="restricted-flag", active=True, created_by=self.user
+ )
+
+ # Mock filter_queryset_by_access_level to filter out flag2
+ def mock_filter(qs):
+ return qs.exclude(id=flag2.id)
+
+ with patch.object(
+ EntitySearchContext,
+ "user_access_control",
+ new_callable=PropertyMock,
+ ) as mock_uac:
+ mock_uac.return_value.filter_queryset_by_access_level = mock_filter
+
+ entities, total = await self.context.list_entities("feature_flag", limit=10, offset=0)
+
+ assert len(entities) == 1
+ assert total == 1
+ assert entities[0]["result_id"] == str(flag1.id)
+
async def test_search_entities_account_by_partial_name(self):
account = await Account.objects.unscoped().acreate(team=self.team, name="Globex", external_id="globex-1")
await Account.objects.unscoped().acreate(team=self.team, name="Acme Corp", external_id="acme-1")
diff --git a/ee/hogai/tools/__init__.py b/ee/hogai/tools/__init__.py
index 2c6100410004..2a9807f11808 100644
--- a/ee/hogai/tools/__init__.py
+++ b/ee/hogai/tools/__init__.py
@@ -14,6 +14,7 @@ _TOOL_MODULES: dict[str, str] = {
"ExecuteSQLMCPTool": ".execute_sql.mcp_tool",
"ExecuteSQLTool": ".execute_sql.tool",
"ListDataTool": ".list_data",
+ "ListFeatureFlagsTool": ".list_feature_flags",
"ManageMemoriesTool": ".manage_memories",
"ReadDataTool": ".read_data",
"ReadDataWarehouseSchemaMCPTool": ".read_data_warehouse_schema.mcp_tool",
@@ -31,6 +32,7 @@ __all__ = [
"CreateFormTool",
"ManageMemoriesTool",
"ListDataTool",
+ "ListFeatureFlagsTool",
"ReadDataTool",
"ReadTaxonomyTool",
"SearchTool",
@@ -70,6 +72,7 @@ if TYPE_CHECKING:
from .execute_sql.mcp_tool import ExecuteSQLMCPTool as ExecuteSQLMCPTool
from .execute_sql.tool import ExecuteSQLTool as ExecuteSQLTool
from .list_data import ListDataTool as ListDataTool
+ from .list_feature_flags import ListFeatureFlagsTool as ListFeatureFlagsTool
from .manage_memories import ManageMemoriesTool as ManageMemoriesTool
from .read_data import ReadDataTool as ReadDataTool
from .read_data_warehouse_schema.mcp_tool import ReadDataWarehouseSchemaMCPTool as ReadDataWarehouseSchemaMCPTool
diff --git a/ee/hogai/tools/list_feature_flags.py b/ee/hogai/tools/list_feature_flags.py
new file mode 100644
index 000000000000..ca9341f49fbc
--- /dev/null
+++ b/ee/hogai/tools/list_feature_flags.py
@@ -0,0 +1,73 @@
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from ee.hogai.context.entity_search.context import EntitySearchContext
+from ee.hogai.tool import MaxTool, ToolMessagesArtifact
+from ee.hogai.tools.list_data import LIST_RESULT_PROMPT
+from ee.hogai.utils.prompt import format_prompt_string
+
+LIST_FEATURE_FLAGS_TOOL_PROMPT = """
+Use this tool to list feature flags with their status, optionally filtered by status, with pagination.
+
+Prefer this over listing all flags and reading them one by one — results already include each
+flag's status, so you never need to inspect flags individually to find stale ones.
+
+# Parameters:
+- status: Optional status filter:
+ - "stale": enabled flags safe to remove (not evaluated in 30+ days, or never evaluated but 100% rolled out and 30+ days old)
+ - "enabled": currently enabled flags
+ - "disabled": currently disabled flags
+ - omit to list all flags
+- limit: Results per page (1-100, default 100)
+- offset: Number to skip for pagination (default 0)
+
+# Examples:
+- "Show me all stale feature flags" → status="stale"
+- "Which flags are disabled?" → status="disabled"
+- "List my feature flags" → no status
+""".strip()
+
+# Maps the user-facing status filter to the backend `active` query param values.
+_STATUS_TO_ACTIVE_FILTER: dict[str, str] = {"stale": "STALE", "enabled": "true", "disabled": "false"}
+
+
+class ListFeatureFlagsToolArgs(BaseModel):
+ status: Literal["stale", "enabled", "disabled"] | None = Field(
+ default=None, description="Filter flags by status. Omit to list all flags."
+ )
+ limit: int = Field(default=100, ge=1, le=100, description="Number of feature flags to return per page")
+ offset: int = Field(default=0, ge=0, description="Number of feature flags to skip for pagination")
+
+
+class ListFeatureFlagsTool(MaxTool):
+ name: Literal["list_feature_flags"] = "list_feature_flags"
+ description: str = LIST_FEATURE_FLAGS_TOOL_PROMPT
+ context_prompt_template: str = "Lists feature flags with their status, filterable by stale/enabled/disabled"
+ args_schema: type[BaseModel] = ListFeatureFlagsToolArgs
+
+ def get_required_resource_access(self):
+ return [("feature_flag", "viewer")]
+
+ async def _arun_impl(
+ self, *, status: str | None = None, limit: int = 100, offset: int = 0
+ ) -> tuple[str, ToolMessagesArtifact | None]:
+ active_filter = _STATUS_TO_ACTIVE_FILTER[status] if status else None
+
+ entities_context = EntitySearchContext(team=self._team, user=self._user, context_manager=self._context_manager)
+ all_entities, total_count = await entities_context.list_feature_flags(
+ limit, offset, active_filter=active_filter
+ )
+
+ formatted_entities = entities_context.format_entities(all_entities)
+
+ has_more = total_count > offset + limit
+ next_offset = offset + limit if has_more else None
+
+ return format_prompt_string(
+ LIST_RESULT_PROMPT,
+ results=formatted_entities,
+ offset=offset,
+ limit=limit,
+ next_offset=next_offset,
+ ), None
diff --git a/ee/hogai/tools/test/test_list_feature_flags.py b/ee/hogai/tools/test/test_list_feature_flags.py
new file mode 100644
index 000000000000..7efc51bfaff5
--- /dev/null
+++ b/ee/hogai/tools/test/test_list_feature_flags.py
@@ -0,0 +1,88 @@
+from uuid import uuid4
+
+from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from ee.hogai.context.context import AssistantContextManager
+from ee.hogai.tools.list_feature_flags import ListFeatureFlagsTool
+from ee.hogai.utils.types import AssistantState
+from ee.hogai.utils.types.base import NodePath
+
+
+class TestListFeatureFlagsTool(ClickhouseTestMixin, NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self):
+ super().setUp()
+ self.tool_call_id = "test_tool_call_id"
+ self.state = AssistantState(messages=[], root_tool_call_id=str(uuid4()))
+ self.context_manager = AssistantContextManager(self.team, self.user, {})
+ self.tool = ListFeatureFlagsTool(
+ team=self.team,
+ user=self.user,
+ state=self.state,
+ context_manager=self.context_manager,
+ node_path=(NodePath(name="test_node", tool_call_id=self.tool_call_id, message_id="test"),),
+ )
+
+ @parameterized.expand(
+ [
+ ("stale", "STALE"),
+ ("enabled", "true"),
+ ("disabled", "false"),
+ (None, None),
+ ]
+ )
+ async def test_status_maps_to_active_filter(self, status, expected_active_filter):
+ """The user-facing status maps to the backend `active` query param."""
+ # autospec validates calls against the real EntitySearchContext signature
+ with patch("ee.hogai.tools.list_feature_flags.EntitySearchContext", autospec=True) as MockEntitySearchContext:
+ mock_instance = MockEntitySearchContext.return_value
+ mock_instance.list_feature_flags.return_value = ([], 0)
+ mock_instance.format_entities.return_value = ""
+
+ await self.tool._arun_impl(status=status, limit=100, offset=0)
+
+ MockEntitySearchContext.assert_called_once_with(
+ team=self.team, user=self.user, context_manager=self.context_manager
+ )
+ mock_instance.list_feature_flags.assert_called_once_with(100, 0, active_filter=expected_active_filter)
+
+ async def test_returns_formatted_data_with_status(self):
+ """Results carry each flag's status so stale flags are identifiable without per-flag reads."""
+ entities_data = [
+ {
+ "type": "feature_flag",
+ "result_id": "123",
+ "extra_fields": {"key": "my-flag", "name": "My flag", "status": "stale", "active": True},
+ }
+ ]
+ formatted_str = (
+ "entity_type: feature_flag\nfeature_flag_id|name|active|key|status|url\n123|My flag|True|my-flag|stale|-"
+ )
+
+ with patch("ee.hogai.tools.list_feature_flags.EntitySearchContext", autospec=True) as MockEntitySearchContext:
+ mock_instance = MockEntitySearchContext.return_value
+ mock_instance.list_feature_flags.return_value = (entities_data, 1)
+ mock_instance.format_entities.return_value = formatted_str
+
+ result, _ = await self.tool._arun_impl(status="stale", limit=100, offset=0)
+
+ mock_instance.format_entities.assert_called_once_with(entities_data)
+ self.assertIn("Offset 0, limit 100", result)
+ self.assertIn("my-flag", result)
+ self.assertIn("stale", result)
+ self.assertIn("You reached the end of results", result)
+
+ async def test_pagination_indicates_more_results(self):
+ """When there are more flags than the page, the next offset is surfaced."""
+ with patch("ee.hogai.tools.list_feature_flags.EntitySearchContext", autospec=True) as MockEntitySearchContext:
+ mock_instance = MockEntitySearchContext.return_value
+ mock_instance.list_feature_flags.return_value = ([], 5)
+ mock_instance.format_entities.return_value = ""
+
+ result, _ = await self.tool._arun_impl(status=None, limit=2, offset=0)
+
+ self.assertIn("To see more results, use offset=2", result)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d3ee8d25c845..a4187de38a5c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -3841,6 +3841,7 @@
"manage_memories",
"create_notebook",
"list_data",
+ "list_feature_flags",
"upsert_alert",
"finalize_plan",
"call_mcp_server",
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index 510e6aec0326..2213e9c1a589 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -494,6 +494,7 @@ export type AssistantTool =
| 'manage_memories'
| 'create_notebook'
| 'list_data'
+ | 'list_feature_flags'
| 'upsert_alert'
| 'finalize_plan'
| 'call_mcp_server'
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index 7d54e3afeed6..84a1d2c153c0 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -134,6 +134,7 @@ export const DEFAULT_TOOL_KEYS: (keyof typeof TOOL_DEFINITIONS)[] = [
'read_taxonomy',
'read_data',
'list_data',
+ 'list_feature_flags',
'search',
'switch_mode',
'list_llm_skills',
@@ -499,6 +500,18 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return `Listing ${entityLabel}${pageInfo}...`
},
},
+ list_feature_flags: {
+ name: 'List feature flags',
+ description: 'List feature flags with their status, filterable by stale/enabled/disabled',
+ icon: <IconSearch />,
+ displayFormatter: (toolCall) => {
+ const status = typeof toolCall.args?.status === 'string' ? toolCall.args.status : null
+ const offset = typeof toolCall.args?.offset === 'number' ? toolCall.args.offset : 0
+ const pageInfo = offset > 0 ? ` (page ${Math.floor(offset / 100) + 1})` : ''
+ const label = status ? `${status} feature flags` : 'feature flags'
+ return toolCall.status === 'completed' ? `Listed ${label}${pageInfo}` : `Listing ${label}${pageInfo}...`
+ },
+ },
create_insight: {
name: 'Create an insight or edit an existing one',
description: "Create an insight or edit an existing one you're viewing",
diff --git a/posthog/schema.py b/posthog/schema.py
index 64bafa485db3..3aa49f551146 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -788,6 +788,7 @@ class AssistantTool(StrEnum):
MANAGE_MEMORIES = "manage_memories"
CREATE_NOTEBOOK = "create_notebook"
LIST_DATA = "list_data"
+ LIST_FEATURE_FLAGS = "list_feature_flags"
UPSERT_ALERT = "upsert_alert"
FINALIZE_PLAN = "finalize_plan"
CALL_MCP_SERVER = "call_mcp_server"
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index a16bb720754c..fcde0eff4e89 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -40,7 +40,6 @@ from posthog.approvals.mixins import ApprovalHandlingMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.constants import FlagRequestType
-from posthog.date_util import thirty_days_ago
from posthog.event_usage import report_user_action
from posthog.exceptions import Conflict
from posthog.exceptions_capture import capture_exception
@@ -73,7 +72,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
get_decrypted_flag_payloads_protected,
)
from products.feature_flags.backend.flag_analytics import increment_request_count
-from products.feature_flags.backend.flag_status import FeatureFlagStatusChecker
+from products.feature_flags.backend.flag_status import FeatureFlagStatusChecker, filter_flags_by_active_param
from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filters
from products.feature_flags.backend.models.evaluation_context import normalize_context_name
from products.feature_flags.backend.models.feature_flag import (
@@ -3220,64 +3219,7 @@ class FeatureFlagViewSet(
for key, value in filters.items():
if key == "active":
- if value == "STALE":
- # Get stale flags using the best available signal:
- # 1. If last_called_at exists: flag hasn't been called in 30+ days
- # 2. If last_called_at is NULL: flag is 100% rolled out and 30+ days old
- stale_threshold = thirty_days_ago()
- usage_based_stale = Q(last_called_at__lt=stale_threshold, active=True)
- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static SQL, no user input)
- config_based_queryset = queryset.filter(
- last_called_at__isnull=True,
- active=True,
- created_at__lt=stale_threshold,
- ).extra(
- where=[
- """
- (
- (
- EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
- WHERE elem->>'rollout_percentage' = '100'
- AND (elem->'properties')::text = '[]'::text
- )
- AND (posthog_featureflag.filters->>'multivariate' IS NULL
- OR posthog_featureflag.filters->'multivariate' = '{}'::jsonb
- OR jsonb_array_length(posthog_featureflag.filters->'multivariate'->'variants') = 0)
- )
- OR
- (
- EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'multivariate'->'variants') AS variant
- WHERE variant->>'rollout_percentage' = '100'
- )
- AND EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
- WHERE elem->>'rollout_percentage' = '100'
- AND (elem->'properties')::text = '[]'::text
- )
- )
- OR
- (
- EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
- WHERE elem->>'rollout_percentage' = '100'
- AND (elem->'properties')::text = '[]'::text
- AND elem->'variant' IS NOT NULL
- AND elem->>'variant' IS NOT NULL
- )
- AND (posthog_featureflag.filters->>'multivariate' IS NOT NULL AND jsonb_array_length(posthog_featureflag.filters->'multivariate'->'variants') > 0)
- )
- OR (posthog_featureflag.filters IS NULL OR posthog_featureflag.filters = '{}'::jsonb)
- )
- """
- ]
- )
- queryset = queryset.filter(usage_based_stale) | config_based_queryset
- else:
- # Handle both string "true"/"false" and boolean True/False
- is_active = value == "true" or value is True
- queryset = queryset.filter(active=is_active)
+ queryset = filter_flags_by_active_param(queryset, value)
elif key == "created_by_id":
queryset = queryset.filter(created_by_id=value)
elif key == "search":
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index a4a6b19c92f4..f5fe4b6f44f3 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -1,6 +1,8 @@
from datetime import UTC, datetime, timedelta
from enum import StrEnum
+from django.db.models import Q, QuerySet
+
import structlog
from posthog.date_util import thirty_days_ago
@@ -19,6 +21,75 @@ class FeatureFlagStatus(StrEnum):
UNKNOWN = "unknown"
+def filter_flags_by_active_param(queryset: QuerySet, value: str | bool) -> QuerySet:
+ """
+ Filter a FeatureFlag queryset by the `active` param (STALE / true / false).
+
+ Source of truth for both the feature_flags viewset (`_apply_filters`) and Max's
+ listing path. Handles string values (from URL query params) and native booleans
+ (from JSON bodies). When updating the STALE logic, also update
+ `FeatureFlagStatusChecker.get_status` so the filter and the per-flag status agree.
+ """
+ if value == "STALE":
+ # Get stale flags using the best available signal:
+ # 1. If last_called_at exists: flag hasn't been called in 30+ days
+ # 2. If last_called_at is NULL: flag is 100% rolled out and 30+ days old
+ stale_threshold = thirty_days_ago()
+ usage_based_stale = Q(last_called_at__lt=stale_threshold, active=True)
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static SQL, no user input)
+ config_based_queryset = queryset.filter(
+ last_called_at__isnull=True,
+ active=True,
+ created_at__lt=stale_threshold,
+ ).extra(
+ where=[
+ """
+ (
+ (
+ EXISTS (
+ SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
+ WHERE elem->>'rollout_percentage' = '100'
+ AND (elem->'properties')::text = '[]'::text
+ )
+ AND (posthog_featureflag.filters->>'multivariate' IS NULL
+ OR posthog_featureflag.filters->'multivariate' = '{}'::jsonb
+ OR jsonb_array_length(posthog_featureflag.filters->'multivariate'->'variants') = 0)
+ )
+ OR
+ (
+ EXISTS (
+ SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'multivariate'->'variants') AS variant
+ WHERE variant->>'rollout_percentage' = '100'
+ )
+ AND EXISTS (
+ SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
+ WHERE elem->>'rollout_percentage' = '100'
+ AND (elem->'properties')::text = '[]'::text
+ )
+ )
+ OR
+ (
+ EXISTS (
+ SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
+ WHERE elem->>'rollout_percentage' = '100'
+ AND (elem->'properties')::text = '[]'::text
+ AND elem->'variant' IS NOT NULL
+ AND elem->>'variant' IS NOT NULL
+ )
+ AND (posthog_featureflag.filters->>'multivariate' IS NOT NULL AND jsonb_array_length(posthog_featureflag.filters->'multivariate'->'variants') > 0)
+ )
+ OR (posthog_featureflag.filters IS NULL OR posthog_featureflag.filters = '{}'::jsonb)
+ )
+ """
+ ]
+ )
+ return queryset.filter(usage_based_stale) | config_based_queryset
+
+ # Handle both string "true"/"false" and boolean True/False
+ is_active = value == "true" or value is True
+ return queryset.filter(active=is_active)
+
+
# FeatureFlagStatusChecker is used to determine the status of a feature flag for a given user.
# Eventually, this may be used to automatically archive old flags that are no longer in use.
#
diff --git a/products/feature_flags/backend/test/test_flag_status.py b/products/feature_flags/backend/test/test_flag_status.py
new file mode 100644
index 000000000000..57dc021b3a44
--- /dev/null
+++ b/products/feature_flags/backend/test/test_flag_status.py
@@ -0,0 +1,78 @@
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+
+from django.utils import timezone
+
+from products.feature_flags.backend.flag_status import (
+ FeatureFlagStatus,
+ FeatureFlagStatusChecker,
+ filter_flags_by_active_param,
+)
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+class TestFilterFlagsByActiveParam(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.enabled = FeatureFlag.objects.create(team=self.team, key="enabled", active=True, created_by=self.user)
+ self.disabled = FeatureFlag.objects.create(team=self.team, key="disabled", active=False, created_by=self.user)
+ # Config-based stale: 30+ days old, no usage data, fully rolled out to 100%
+ self.stale = FeatureFlag.objects.create(
+ team=self.team,
+ key="stale",
+ active=True,
+ created_at=timezone.now() - timedelta(days=60),
+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
+ created_by=self.user,
+ )
+ # Usage-based stale: active but not evaluated in 30+ days
+ self.stale_by_usage = FeatureFlag.objects.create(
+ team=self.team,
+ key="stale-by-usage",
+ active=True,
+ last_called_at=timezone.now() - timedelta(days=35),
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+ # Multivariate stale: one variant at 100% plus a fully rolled out release condition
+ self.stale_multivariate = FeatureFlag.objects.create(
+ team=self.team,
+ key="stale-multivariate",
+ active=True,
+ created_at=timezone.now() - timedelta(days=60),
+ filters={
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ created_by=self.user,
+ )
+
+ def _filter(self, value):
+ return set(
+ filter_flags_by_active_param(FeatureFlag.objects.filter(team=self.team), value).values_list(
+ "key", flat=True
+ )
+ )
+
+ def test_filters_enabled(self):
+ assert self._filter("true") == {"enabled", "stale", "stale-by-usage", "stale-multivariate"}
+
+ def test_filters_disabled(self):
+ assert self._filter("false") == {"disabled"}
+
+ def test_filters_stale(self):
+ assert self._filter("STALE") == {"stale", "stale-by-usage", "stale-multivariate"}
+
+ def test_accepts_native_booleans(self):
+ assert self._filter(True) == {"enabled", "stale", "stale-by-usage", "stale-multivariate"}
+ assert self._filter(False) == {"disabled"}
+
+ def test_stale_filter_agrees_with_status_checker(self):
+ """The SQL filter and the per-flag status checker must classify the same flags as stale."""
+ checker_stale = {
+ flag.key
+ for flag in FeatureFlag.objects.filter(team=self.team)
+ if FeatureFlagStatusChecker(feature_flag=flag).get_status()[0] == FeatureFlagStatus.STALE
+ }
+ assert self._filter("STALE") == checker_stale