: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
chore(flags): share the stale flag selection contract (#90171)
James Gill5638cf18cb19
diff --git a/posthog/date_util.py b/posthog/date_util.pyindex 91bc631383b6..9b63e9d52327 100644--- a/posthog/date_util.py+++ b/posthog/date_util.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime, timedelta+from datetime import datetime, timedeltadef start_of_minute(dt: datetime) -> datetime:@@ -24,7 +24,3 @@ def start_of_week(dt: datetime) -> datetime:def start_of_month(dt: datetime) -> datetime:return datetime(year=dt.year, month=dt.month, day=1, tzinfo=dt.tzinfo)---def thirty_days_ago() -> datetime:- return datetime.now(UTC) - timedelta(days=30)diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.pyindex 2519b160c4ce..48b48537ad1e 100644--- a/products/feature_flags/backend/flag_status.py+++ b/products/feature_flags/backend/flag_status.py@@ -6,14 +6,23 @@ from django.db.models import Q, QuerySetimport structlog-from posthog.date_util import thirty_days_ago-from .models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)FeatureFlagStatusReason = str+STALE_FLAG_THRESHOLD_DAYS = 30+++def stale_flag_threshold() -> datetime:+ """The cutoff that both staleness signals compare against.++ A flag with usage data is stale when `last_called_at` is older than this. A flag with no+ usage data is only considered at all when `created_at` is older than this.+ """+ return datetime.now(UTC) - timedelta(days=STALE_FLAG_THRESHOLD_DAYS)+class FeatureFlagStatus(StrEnum):ACTIVE = "active"@@ -48,69 +57,106 @@ def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) ->return queryset+def filter_stale_flags(queryset: QuerySet) -> QuerySet:+ """+ Narrow a FeatureFlag queryset to the flags that count as stale.++ Set-based counterpart to `FeatureFlagStatusChecker.get_status`, which answers the same+ question for one flag and also produces the human-readable reason. The two are meant to+ classify the same flags, so change them together.++ They do not agree yet, on two shapes. First, the checker calls a flag with no release+ conditions fully rolled out, so `filters` of `{"groups": []}` (the model default) is STALE+ to the checker and not stale here; the config branch below matches an empty `filters` only+ as `NULL` or `{}`. Second, the checker reads a group that omits the `properties` key, e.g.+ `{"groups": [{"rollout_percentage": 100}]}`, as an empty targeting list and calls it STALE,+ while the config branch requires a literal `[]` and Postgres `->` returns NULL for the+ absent key, so no branch matches. The editor and the filters serializer now write+ `properties: []`, so only unedited legacy rows hold the second shape.+ `test_stale_filter_agrees_with_status_checker` covers the shapes where the two do agree.++ The caller supplies the scope, so pass a queryset already narrowed to the team.++ The config branch's raw SQL rides on `.extra(where=...)`, and that clause stays on that+ branch when the two querysets are OR-combined below. Applied to the combined query, it+ would narrow the usage-based branch too and drop flags that are stale only by usage.+ `test_filters_stale` covers that case.++ Compose it by chaining `.filter()`, and keep the result a top-level queryset. The raw+ predicate hard-codes the `posthog_featureflag` table name. Nesting the result aliases the+ inner table, so the raw text resolves against the outer row instead.++ `pk__in=<queryset>` survives that, because `id IN (...)` ties the inner row to the outer+ row. A correlated `Exists()` or `Subquery()` joined on anything else, such as `team_id`,+ does not. The config branch then tests the outer flag's `filters` while the inner query+ ranges over the team's other flags, and returns a wrong set of flags with no error.+ Postgres rejects the query only when the outer scope holds no `posthog_featureflag`.+ """+ # 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 = stale_flag_threshold()+ 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++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'slisting 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.+ (from JSON bodies). The STALE branch delegates to `filter_stale_flags`."""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+ return filter_stale_flags(queryset)# Handle both string "true"/"false" (any casing) and boolean True/Falseis_active = str(value).lower() == "true"@@ -129,7 +175,8 @@ def filter_flags_by_active_param(queryset: QuerySet, value: str | bool) -> Query# - DELETED: The feature flag has been soft deleted.# - UNKNOWN: The feature flag is not found in the database.#-# When we update the logic for stale flags, do check/update the function `_filter_request`` in feature_flag.py+# The set-based counterpart is `filter_stale_flags`. Both are meant to classify the same flags as+# stale, with the exceptions recorded in that function's docstring.class FeatureFlagStatusChecker:def __init__(self,@@ -185,8 +232,8 @@ class FeatureFlagStatusChecker:else:# No usage data - fall back to configuration-based detection# Only for flags that are old enough (30+ days) to have had a chance to be called- is_flag_at_least_thirty_days_old = flag.created_at < thirty_days_ago()- if is_flag_at_least_thirty_days_old:+ is_flag_older_than_stale_threshold = flag.created_at < stale_flag_threshold()+ if is_flag_older_than_stale_threshold:is_fully_rolled_out, rolled_out_reason = self.is_flag_fully_rolled_out(flag)if is_fully_rolled_out:return FeatureFlagStatus.STALE, rolled_out_reason@@ -199,7 +246,7 @@ class FeatureFlagStatusChecker:A flag is stale if it hasn't been called in 30+ days."""assert flag.last_called_at is not None, "last_called_at must not be None"- stale_threshold = datetime.now(UTC) - timedelta(days=30)+ stale_threshold = stale_flag_threshold()if flag.last_called_at < stale_threshold:days_since_called = (datetime.now(UTC) - flag.last_called_at).daysdiff --git a/products/feature_flags/backend/test/test_flag_status.py b/products/feature_flags/backend/test/test_flag_status.pyindex 0eb627e86260..d21687dd5ee0 100644--- a/products/feature_flags/backend/test/test_flag_status.py+++ b/products/feature_flags/backend/test/test_flag_status.py@@ -1,4 +1,5 @@from datetime import timedelta+from typing import Anyfrom posthog.test.base import BaseTest@@ -10,6 +11,7 @@ from products.feature_flags.backend.flag_status import (FeatureFlagStatus,FeatureFlagStatusChecker,filter_flags_by_active_param,+ filter_stale_flags,)from products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -99,14 +101,142 @@ class TestFilterFlagsByActiveParam(BaseTest):}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 = {+ def _checker_stale(self) -> set[str]:+ return {flag.keyfor flag in FeatureFlag.objects.filter(team=self.team)if FeatureFlagStatusChecker(feature_flag=flag).get_status()[0] == FeatureFlagStatus.STALE}- assert self._filter("STALE") == checker_stale++ # (flag key, extra FeatureFlag kwargs, whether that flag is stale). Each case creates its+ # flag, then asserts the filter and the checker agree across the whole team, so setUp's four+ # stale flags are re-checked on every case. Most cases add a shape that must not be stale,+ # because setUp already covers the stale ones.+ @parameterized.expand(+ [+ (+ "recently_evaluated",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "last_called_at": timezone.now() - timedelta(days=1),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ },+ False,+ ),+ (+ "boolean_zero_rollout",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 0}]},+ },+ False,+ ),+ (+ "partial_rollout",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},+ },+ False,+ ),+ (+ "targeted_condition_at_full_rollout",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {+ "groups": [{"properties": [{"key": "email", "value": "x"}], "rollout_percentage": 100}]+ },+ },+ False,+ ),+ (+ "multivariate_split_variants",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ]+ },+ "groups": [{"properties": [], "rollout_percentage": 100}],+ },+ },+ False,+ ),+ (+ "young_flag_at_full_rollout",+ {+ "created_at": timezone.now() - timedelta(days=5),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ },+ False,+ ),+ (+ "disabled_flag_at_full_rollout",+ {+ "active": False,+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ },+ False,+ ),+ # Only case that reaches the usage branch's `active=True` guard, because every+ # other disabled case leaves `last_called_at` NULL and stops at the config branch.+ (+ "disabled_flag_with_old_last_called_at",+ {+ "active": False,+ "last_called_at": timezone.now() - timedelta(days=35),+ "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]},+ },+ False,+ ),+ # Only case that reaches the config branch's last OR arm, where `filters` being+ # non-nullable makes `= '{}'` the whole test.+ (+ "empty_filters_object",+ {+ "created_at": timezone.now() - timedelta(days=60),+ "filters": {},+ },+ True,+ ),+ ]+ )+ def test_stale_filter_agrees_with_status_checker(+ self, key: str, flag_kwargs: dict[str, Any], expected_stale: bool+ ) -> None:+ FeatureFlag.objects.create(team=self.team, key=key, created_by=self.user, **flag_kwargs)++ filter_stale = self._filter("STALE")+ assert filter_stale == self._checker_stale()+ assert (key in filter_stale) is expected_stale++ def test_stale_filter_query_count_does_not_grow_with_candidate_count(self) -> None:+ def evaluate() -> list[FeatureFlag]:+ return list(filter_stale_flags(FeatureFlag.objects.filter(team=self.team)))++ with self.assertNumQueries(1):+ baseline = evaluate()++ FeatureFlag.objects.bulk_create(+ FeatureFlag(+ team=self.team,+ key=f"bulk-stale-{index}",+ active=True,+ created_at=timezone.now() - timedelta(days=60),+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ created_by=self.user,+ )+ for index in range(20)+ )++ with self.assertNumQueries(1):+ expanded = evaluate()++ assert len(expanded) == len(baseline) + 20class TestRolloutSummary(BaseTest):