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): report flags that are constant but still called (#100143)

James Gillaceb1c34fd39
diff --git a/products/feature_flags/backend/flag_status.py b/products/feature_flags/backend/flag_status.py
index 29e9220bc2cd..b9999f9e1921 100644
--- a/products/feature_flags/backend/flag_status.py
+++ b/products/feature_flags/backend/flag_status.py
@@ -67,7 +67,47 @@ def exclude_archived_unless_requested(queryset: QuerySet, *, requested: bool) ->
return queryset
-def filter_stale_flags(queryset: QuerySet) -> QuerySet:
+# `jsonb_array_elements` and `jsonb_array_length` raise on a value that is not an array, and the
+# error aborts the whole statement instead of skipping the row. A detection batch covers 250 teams,
+# so one legacy flag storing `groups` as a scalar would take the query down for every team in it.
+# These read a non-array as an empty array. `CASE` is the only construct that guarantees the type
+# test runs before the array function; the planner is free to reorder the arms of `AND` and `OR`.
+# Both predicates below interpolate these, so they are f-strings and every literal `{}` in their
+# SQL is written `{{}}`.
+_GROUPS_ARRAY = (
+ "CASE WHEN jsonb_typeof(posthog_featureflag.filters->'groups') = 'array' "
+ "THEN posthog_featureflag.filters->'groups' ELSE '[]'::jsonb END"
+)
+_VARIANTS_ARRAY = (
+ "CASE WHEN jsonb_typeof(posthog_featureflag.filters->'multivariate'->'variants') = 'array' "
+ "THEN posthog_featureflag.filters->'multivariate'->'variants' ELSE '[]'::jsonb END"
+)
+# A release condition carries no targeting when `properties` is `[]`, absent, or JSON null, which
+# is how `is_group_fully_rolled_out` and `is_boolean_flag_fully_rolled_out` read it. Postgres `->`
+# returns SQL NULL for the absent key and the jsonb scalar `null` for the stored null, so each
+# needs its own test. The editor and the filters serializer write `[]`, so only unedited legacy
+# rows hold the other two.
+_ELEM_HAS_NO_TARGETING = (
+ "("
+ "(elem->'properties')::text = '[]'::text "
+ "OR elem->'properties' IS NULL "
+ "OR jsonb_typeof(elem->'properties') = 'null'"
+ ")"
+)
+# Every branch of `FeatureFlagStatusChecker.is_flag_fully_rolled_out` needs a release condition at
+# an explicit 100% with no targeting, so both predicates below test for one. Keep it in one place,
+# because a change to how the two read that shape has to reach the stale filter and the rollout
+# prefilter together or they classify the same flag differently.
+_HAS_UNTARGETED_FULL_ROLLOUT_GROUP = f"""
+ EXISTS (
+ SELECT 1 FROM jsonb_array_elements({_GROUPS_ARRAY}) AS elem
+ WHERE elem->>'rollout_percentage' = '100'
+ AND {_ELEM_HAS_NO_TARGETING}
+ )
+"""
+
+
+def filter_stale_flags(queryset: QuerySet, *, stale_threshold: datetime | None = None) -> QuerySet:
"""
Narrow a FeatureFlag queryset to the flags that count as stale.
@@ -75,18 +115,18 @@ def filter_stale_flags(queryset: QuerySet) -> QuerySet:
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.
+ They do not agree on one shape: 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, because the config branch below matches an empty `filters` only as `NULL` or
+ `{}`. Matching the model default would make every unconfigured flag in a project stale.
`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.
+ Pass `stale_threshold` to hold one detection run to one cutoff, so the caller can compare
+ its other queries against the same instant. Without it the function reads the clock itself,
+ which is what the `active=STALE` filter wants.
+
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.
@@ -105,7 +145,8 @@ def filter_stale_flags(queryset: QuerySet) -> QuerySet:
# 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()
+ if stale_threshold is None:
+ 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(
@@ -114,42 +155,34 @@ def filter_stale_flags(queryset: QuerySet) -> QuerySet:
created_at__lt=stale_threshold,
).extra(
where=[
- """
+ f"""
(
(
- EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
- WHERE elem->>'rollout_percentage' = '100'
- AND (elem->'properties')::text = '[]'::text
- )
+ {_HAS_UNTARGETED_FULL_ROLLOUT_GROUP}
AND (posthog_featureflag.filters->>'multivariate' IS NULL
- OR posthog_featureflag.filters->'multivariate' = '{}'::jsonb
- OR jsonb_array_length(posthog_featureflag.filters->'multivariate'->'variants') = 0)
+ OR posthog_featureflag.filters->'multivariate' = '{{}}'::jsonb
+ OR jsonb_array_length({_VARIANTS_ARRAY}) = 0)
)
OR
(
EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'multivariate'->'variants') AS variant
+ SELECT 1 FROM jsonb_array_elements({_VARIANTS_ARRAY}) 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
- )
+ AND {_HAS_UNTARGETED_FULL_ROLLOUT_GROUP}
)
OR
(
EXISTS (
- SELECT 1 FROM jsonb_array_elements(posthog_featureflag.filters->'groups') AS elem
+ SELECT 1 FROM jsonb_array_elements({_GROUPS_ARRAY}) AS elem
WHERE elem->>'rollout_percentage' = '100'
- AND (elem->'properties')::text = '[]'::text
+ AND {_ELEM_HAS_NO_TARGETING}
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)
+ AND (posthog_featureflag.filters->>'multivariate' IS NOT NULL AND jsonb_array_length({_VARIANTS_ARRAY}) > 0)
)
- OR (posthog_featureflag.filters IS NULL OR posthog_featureflag.filters = '{}'::jsonb)
+ OR (posthog_featureflag.filters IS NULL OR posthog_featureflag.filters = '{{}}'::jsonb)
)
"""
]
@@ -157,6 +190,39 @@ def filter_stale_flags(queryset: QuerySet) -> QuerySet:
return queryset.filter(usage_based_stale) | config_based_queryset
+def filter_effectively_full_rollout_flags(queryset: QuerySet) -> QuerySet:
+ """
+ Narrow a FeatureFlag queryset to the flags whose configuration can only serve one result.
+
+ Rollout completeness is not staleness. `filter_stale_flags` keeps that job and nothing
+ user-visible reads this.
+
+ The predicate reads configuration only. Which of these flags is a cleanup candidate is the
+ caller's policy, so flag age, call recency and `active` all stay with the caller.
+
+ This is a prefilter, not a verdict. The SQL matches a release condition at an explicit 100%
+ with no properties, which every branch of `FeatureFlagStatusChecker.is_flag_fully_rolled_out`
+ needs, boolean and multivariate alike. A multivariate flag also needs a winning variant or a
+ variant override on that condition, which this does not test, so the caller must confirm each
+ row with `is_flag_fully_rolled_out` before it treats the flag as fully rolled out.
+
+ A group that omits the `properties` key, or stores it as JSON null, counts as having no
+ targeting. See `_ELEM_HAS_NO_TARGETING`.
+
+ A legacy row storing `groups` as something other than an array reads as an empty array and
+ drops out, rather than aborting the batch. See `_GROUPS_ARRAY`.
+
+ Flags with no release conditions at all (`filters` NULL, `{}`, or `{"groups": []}`) stay out,
+ although the checker calls them fully rolled out. `{"groups": []}` is the model default, so
+ matching it would report every flag in a project that nobody has configured.
+
+ See `filter_stale_flags` for the `.extra(where=...)` composition trap, which applies here too.
+ `.filter()` chained onto the result ANDs cleanly and keeps the raw text at the top level.
+ """
+ # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (static SQL, no user input)
+ return queryset.extra(where=[_HAS_UNTARGETED_FULL_ROLLOUT_GROUP])
+
+
def filter_flags_by_active_param(queryset: QuerySet, value: str | bool) -> QuerySet:
"""
Filter a FeatureFlag queryset by the `active` param (STALE / true / false).
@@ -371,7 +437,10 @@ class FeatureFlagStatusChecker:
def is_group_fully_rolled_out(self, group: dict) -> bool:
rollout_percentage = group.get("rollout_percentage")
- properties = group.get("properties", [])
+ # A `properties` key stored as JSON null means no targeting, the same as an absent key.
+ # The matcher's field is `Option<Vec<PropertyFilter>>` and the filters serializer
+ # normalizes null to `[]`, so only legacy rows still hold the null.
+ properties = group.get("properties") or []
return rollout_percentage == 100 and len(properties) == 0
def is_boolean_flag_fully_rolled_out(self, flag: FeatureFlag) -> bool:
@@ -387,7 +456,7 @@ class FeatureFlagStatusChecker:
# The fully rolled out release condition must have no properties set.
for release_condition in release_conditions:
rollout_percentage = release_condition.get("rollout_percentage")
- properties = release_condition.get("properties", [])
+ properties = release_condition.get("properties") or []
if rollout_percentage == 100 and len(properties) == 0:
logger.debug(f"Boolean flag {flag.id} has a release conditions rolled out to 100%")
return True
diff --git a/products/feature_flags/backend/temporal/health_checks/stale_flags.py b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
index 74d49ff91e5f..4759c09288a8 100644
--- a/products/feature_flags/backend/temporal/health_checks/stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/stale_flags.py
@@ -1,6 +1,7 @@
from collections.abc import Collection
from datetime import datetime
+from django.db.models import Q
from django.utils import timezone
import structlog
@@ -20,7 +21,9 @@ from products.feature_flags.backend.flag_status import (
ROLLOUT_NOT_ROLLED_OUT,
ROLLOUT_PARTIAL,
FeatureFlagStatusChecker,
+ filter_effectively_full_rollout_flags,
filter_stale_flags,
+ stale_flag_threshold,
)
from products.feature_flags.backend.flag_version_sync import direct_flag_dependency_ids, flags_with_flag_dependencies
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -36,6 +39,10 @@ EVIDENCE_NOT_CALLED_RECENTLY = "not_called_recently"
# No call evidence at all; the flag is old enough and its configuration serves a fixed
# result. This says nothing about whether SDKs still evaluate the flag.
EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA = "fully_rolled_out_without_usage_data"
+# The configuration serves one fixed result and PostHog received a call inside the stale window.
+# `filter_stale_flags` needs a call older than the threshold or no call data at all, so a flag at
+# 100% that SDKs evaluate every day falls outside both of its branches and only this class sees it.
+EVIDENCE_EFFECTIVELY_FULL_ROLLOUT = "effectively_full_rollout"
_ROLLOUT_STATE_TEXT = {
ROLLOUT_FULLY_ROLLED_OUT: "fully rolled out",
@@ -107,6 +114,8 @@ class StaleFeatureFlagsCheck(HealthCheck):
if isinstance(days, int)
else "PostHog has not received a call for this flag recently"
)
+ elif payload.get("evidence_class") == EVIDENCE_EFFECTIVELY_FULL_ROLLOUT:
+ evidence_text = "PostHog still receives calls for this flag"
else:
evidence_text = "This flag has no usage data and its configuration serves a fixed result"
rollout_text = _ROLLOUT_STATE_TEXT.get(payload.get("rollout_state"))
@@ -122,41 +131,188 @@ class StaleFeatureFlagsCheck(HealthCheck):
)
def detect(self, team_ids: list[int]) -> dict[int, list[HealthCheckResult]]:
- candidates = list(
- filter_stale_flags(
- FeatureFlag.objects.filter(
- team_id__in=team_ids,
- deleted=False,
- archived=False,
- active=True,
- ).exclude(is_remote_configuration=True)
+ reportable_flags = FeatureFlag.objects.filter(
+ team_id__in=team_ids,
+ deleted=False,
+ archived=False,
+ active=True,
+ ).exclude(is_remote_configuration=True)
+
+ # One cutoff for the whole run: both candidate queries and the evidence classification
+ # compare against it. A second clock read would let a flag whose last call sits on the
+ # boundary be selected by one of them and then classified against the other.
+ stale_threshold = stale_flag_threshold()
+
+ stale_candidates = list(filter_stale_flags(reportable_flags, stale_threshold=stale_threshold))
+ # Only a never-called stale flag can come back from the rollout query too: a usage-stale
+ # flag's last call predates the cutoff, which fails the call-recency filter below. Excluding
+ # those ids beats fetching the rows again and dropping them in Python, and
+ # `hash_keys=["flag_id"]` would otherwise give both rows the same issue identity.
+ # The ids go in as a bound list. A subquery looks tidier and is wrong here: the inner
+ # `.extra(where=...)` hard-codes `posthog_featureflag`, the subquery aliases that table,
+ # and the raw text then tests the outer row instead of the inner one.
+ overlap_ids = {flag.id for flag in stale_candidates if flag.last_called_at is None}
+ # The prefilter reads configuration only and returns a superset, so the policy that makes
+ # one of those flags a cleanup candidate is applied here, and the checker settles each
+ # remaining row. A flag created after the cutoff is too new for a constant configuration to
+ # mean the rollout is finished, and one that went cold is already a `filter_stale_flags`
+ # row. Call recency is spelled as a positive filter because
+ # `exclude(last_called_at__lt=...)` on a nullable column drops the rows with no call data,
+ # which have to stay in.
+ full_rollout_query = (
+ filter_effectively_full_rollout_flags(reportable_flags)
+ .filter(
+ Q(last_called_at__isnull=True) | Q(last_called_at__gte=stale_threshold),
+ created_at__lt=stale_threshold,
)
+ .exclude(pk__in=overlap_ids)
)
+ full_rollout_candidates = [
+ flag
+ for flag in full_rollout_query
+ if not _serves_more_than_one_result(flag)
+ and FeatureFlagStatusChecker(feature_flag=flag).is_flag_fully_rolled_out(flag)[0]
+ ]
+ candidates = stale_candidates + full_rollout_candidates
if not candidates:
return {}
excluded_ids = _excluded_flag_ids(candidates)
+ full_rollout_ids = {flag.id for flag in full_rollout_candidates}
now = timezone.now()
issues: dict[int, list[HealthCheckResult]] = {}
for flag in candidates:
if flag.id in excluded_ids:
continue
- issues.setdefault(flag.team_id, []).append(_build_result(flag, now))
+ issues.setdefault(flag.team_id, []).append(_build_result(flag, now, stale_threshold))
if issues:
# Each issue fires its own alert once dry_run flips, so the flip decision needs the
# worst single team, which the framework's batch-wide dry-run summary does not show.
issue_counts = [len(team_issues) for team_issues in issues.values()]
+ evidence_classes = [
+ result.payload["evidence_class"] for team_issues in issues.values() for result in team_issues
+ ]
logger.info(
"stale_feature_flags_detected",
teams_with_issues=len(issues),
issue_count=sum(issue_counts),
max_issues_per_team=max(issue_counts),
+ effectively_full_rollout_evidence_count=evidence_classes.count(EVIDENCE_EFFECTIVELY_FULL_ROLLOUT),
+ full_rollout_query_issue_count=len(full_rollout_ids - excluded_ids),
)
return issues
+def _serves_more_than_one_result(flag: FeatureFlag) -> bool:
+ """Whether the matcher can return more than the one result the checker named.
+
+ `FeatureFlagStatusChecker` reads `groups` and `multivariate` and asks whether some release
+ condition is at 100% with no properties. That is necessary for a fixed result and not
+ sufficient, so this class needs the rest of the runtime model before it calls a flag constant.
+ The checker stays as it is: it backs the flag status endpoint, the stale badge, bulk delete and
+ Max, and the raw SQL behind the public `active=STALE` filter mirrors it. A follow-up has to
+ reconcile the two meanings of full rollout; until then this guard holds the stricter one and
+ only the effectively-full-rollout class reads it.
+
+ The other candidate source is left alone. Its evidence is that PostHog stopped receiving calls,
+ which none of this contradicts.
+ """
+ filters = flag.filters or {}
+ # A holdout is resolved before the release conditions and returns `holdout-<id>` to its share,
+ # legacy super groups short-circuit the same way, and `early_exit` returns false on a failed
+ # rollout check instead of falling through to a later blanket condition.
+ # Two siblings encode part of the same evaluation order. `group_cohort_restriction_blocker` in
+ # `products/feature_flags/backend/facade/filters.py` reads `holdout`, `holdout_groups` and
+ # `super_groups`. `is_unconditionally_fully_rolled_out` in
+ # `products/feature_flags/backend/persisted_flags.py` reads `holdout` and `super_groups`.
+ # Neither reads `early_exit`, so the three lists have never been in parity.
+ if any(filters.get(key) for key in ("holdout", "holdout_groups", "super_groups", "early_exit")):
+ return True
+ # These three decide the result from evaluation context the configuration does not carry, so a
+ # blanket condition does not reach everyone. A group-aggregated condition is skipped for a
+ # request that carries no group of that type. Device-id bucketing skips person-aggregated
+ # conditions when the request has no device id. Feature enrollment evaluates the flag against
+ # the person property `$feature_enrollment/{key}`. An explicit null aggregation index means
+ # person aggregation, so only a set index excludes.
+ if flag.bucketing_identifier == "device_id" or filters.get("feature_enrollment"):
+ return True
+ groups = filters.get("groups") or []
+ if filters.get("aggregation_group_type_index") is not None:
+ return True
+ if any(group.get("aggregation_group_type_index") is not None for group in groups):
+ return True
+ return not _multivariate_results_agree(flag)
+
+
+def _multivariate_results_agree(flag: FeatureFlag) -> bool:
+ """Whether every user a multivariate flag can reach receives the same variant.
+
+ The matcher reads the release conditions in declaration order and stops at the first one that
+ matches, so a condition declared before the blanket one decides the result for the users it
+ matches. A condition carrying a `variant` override serves that variant, and any other condition
+ serves whatever the variant distribution gives. The flag is constant only when every one of
+ those paths lands on the same variant.
+
+ Boolean flags are constant by this test, because every condition that matches returns true.
+ """
+ variants = ((flag.filters or {}).get("multivariate") or {}).get("variants") or []
+ if not variants:
+ return True
+ return _sole_served_variant(flag) is not None
+
+
+def _sole_served_variant(flag: FeatureFlag) -> str | None:
+ """The one variant that every reachable path serves, or None when the paths disagree.
+
+ A boolean flag carries no variants and returns None, so a caller must not read None as "the
+ flag is not constant". `_multivariate_results_agree` holds that distinction.
+ """
+ filters = flag.filters or {}
+ variants = ((filters.get("multivariate") or {}).get("variants")) or []
+
+ groups = filters.get("groups") or []
+ checker = FeatureFlagStatusChecker(feature_flag=flag)
+ decider = next((index for index, group in enumerate(groups) if checker.is_group_fully_rolled_out(group)), None)
+ if decider is None:
+ return None
+
+ distributed = _sole_reachable_variant(variants)
+ variant_keys = {variant.get("key") for variant in variants}
+ results = set()
+ for group in groups[: decider + 1]:
+ # A missing rollout_percentage evaluates to 100% at runtime, matching `get_rollout_summary`.
+ percentage = group.get("rollout_percentage")
+ if percentage is not None and percentage <= 0:
+ continue
+ # The matcher ignores an override naming a variant the flag does not configure, and the
+ # distribution decides instead.
+ override = group.get("variant")
+ results.add(override if override in variant_keys else distributed)
+ # `None` is in the set when a path falls through to a distribution that is not itself constant.
+ if len(results) != 1:
+ return None
+ (served,) = results
+ return served
+
+
+def _sole_reachable_variant(variants: list[dict]) -> str | None:
+ """The only variant the distribution can serve, or None when a user can land on more than one.
+
+ Variants take cumulative slices of the hash space in declaration order, so the first variant
+ with a non-zero rollout takes the low hashes. Only that variant exists when it takes the whole
+ space. A list such as `[40, 100]` is overallocated: the 100 does not make the flag constant,
+ because the 40 still owns the low hashes.
+ """
+ for variant in variants:
+ percentage = variant.get("rollout_percentage") or 0
+ if percentage <= 0:
+ continue
+ return variant.get("key") if percentage >= 100 else None
+ return None
+
+
def _excluded_flag_ids(candidates: list[FeatureFlag]) -> set[int]:
"""Flag ids that known blockers reference, not limited to the candidate ids.
@@ -241,16 +397,32 @@ def _depended_on_flag_ids(project_ids: Collection[int]) -> set[int]:
return depended_on
-def _build_result(flag: FeatureFlag, now: datetime) -> HealthCheckResult:
+def _build_result(flag: FeatureFlag, now: datetime, stale_threshold: datetime) -> HealthCheckResult:
checker = FeatureFlagStatusChecker(feature_flag=flag)
summary = checker.get_rollout_summary(flag)
rollout_state, winning_variant = checker.rollout_state_and_variant(flag, summary)
- if flag.last_called_at is not None:
+ # The checker returns a condition's `variant` override without testing it against the variants
+ # the flag configures, so a legacy row naming an absent key reaches the payload and the
+ # remediation then names a variant nobody receives. Prefer the variant the matcher serves. A
+ # flag whose reachable paths disagree has no such variant, so it keeps the checker's value.
+ served_variant = _sole_served_variant(flag)
+ if served_variant is not None:
+ winning_variant = served_variant
+
+ # Read off the flag rather than off the query that found it, so the payload describes the row
+ # a reader opens. Every candidate is old enough and serves a fixed result or went cold, so the
+ # call column is what separates the three classes.
+ if flag.last_called_at is None:
+ evidence_class = EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA
+ evidence_date = flag.created_at
+ elif flag.last_called_at < stale_threshold:
evidence_class = EVIDENCE_NOT_CALLED_RECENTLY
evidence_date = flag.last_called_at
else:
- evidence_class = EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA
+ evidence_class = EVIDENCE_EFFECTIVELY_FULL_ROLLOUT
+ # No column records when the flag reached 100%, and `last_called_at` reads as about zero
+ # days on a flag that is called every day, which is the opposite of the point.
evidence_date = flag.created_at
return HealthCheckResult(
diff --git a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
index 7ced7baae56c..9a1966004174 100644
--- a/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
+++ b/products/feature_flags/backend/temporal/health_checks/tests/test_stale_flags.py
@@ -24,6 +24,7 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.flag_status import ROLLOUT_FULLY_ROLLED_OUT, ROLLOUT_NOT_ROLLED_OUT, ROLLOUT_PARTIAL
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.temporal.health_checks.stale_flags import (
+ EVIDENCE_EFFECTIVELY_FULL_ROLLOUT,
EVIDENCE_FULLY_ROLLED_OUT_WITHOUT_USAGE_DATA,
EVIDENCE_NOT_CALLED_RECENTLY,
StaleFeatureFlagsCheck,
@@ -46,6 +47,10 @@ def stale_by_usage() -> dict[str, Any]:
}
+def constant_and_called() -> dict[str, Any]:
+ return {**stale_by_config(), "last_called_at": timezone.now()}
+
+
class TestStaleFlagsDetect(BaseTest):
def _create_flag(self, key: str, **kwargs: Any) -> FeatureFlag:
kwargs.setdefault("active", True)
@@ -140,6 +145,322 @@ class TestStaleFlagsDetect(BaseTest):
# Local-evaluation semantics: a disabled dependent still protects its dependency.
("disabled_dependent_still_blocks", stale_by_usage(), "disabled_dependent_flag", False),
("replay_linked", stale_by_config(), "replay_link", False),
+ # The cases below read filter_effectively_full_rollout_flags, which classifies rollout
+ # completeness and not staleness. No flag becomes STALE to either side because of it,
+ # so test_stale_filter_agrees_with_status_checker in
+ # products/feature_flags/backend/test/test_flag_status.py still holds.
+ # Fully rolled out and still called every day: outside both filter_stale_flags branches.
+ ("constant_and_still_called", constant_and_called(), None, True),
+ # The exclusions run over both candidate sources, not just the stale one.
+ ("constant_and_still_called_blocked_by_experiment", constant_and_called(), "experiment", False),
+ # Legacy shape: an absent properties key is no targeting, which is what
+ # is_group_fully_rolled_out reads and what the SQL prefilter has to let through.
+ (
+ "constant_with_properties_key_absent",
+ {**constant_and_called(), "filters": {"groups": [{"rollout_percentage": 100}]}},
+ None,
+ True,
+ ),
+ # Never called and legacy-shaped. Both candidate queries match it, so the overlap
+ # exclusion is what stops it being reported twice under one hash key.
+ (
+ "legacy_shape_never_called",
+ {**stale_by_config(), "filters": {"groups": [{"rollout_percentage": 100}]}},
+ None,
+ True,
+ ),
+ # Legacy shape: `properties` stored as JSON null is no targeting, which neither the
+ # `IS NULL` arm nor the literal `[]` arm of the prefilter matches on its own.
+ (
+ "constant_with_null_properties",
+ {**constant_and_called(), "filters": {"groups": [{"rollout_percentage": 100, "properties": None}]}},
+ None,
+ True,
+ ),
+ (
+ "constant_but_targeted",
+ {
+ **constant_and_called(),
+ "filters": {
+ "groups": [{"properties": [{"key": "email", "value": "x"}], "rollout_percentage": 100}]
+ },
+ },
+ None,
+ False,
+ ),
+ # The model default is fully rolled out to the checker, so only the SQL keeps every
+ # unconfigured flag out of the report.
+ ("constant_with_no_release_conditions", {**constant_and_called(), "filters": {"groups": []}}, None, False),
+ (
+ "constant_but_younger_than_threshold",
+ {**constant_and_called(), "created_at": timezone.now()},
+ None,
+ False,
+ ),
+ (
+ "multivariate_winner_still_called",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ True,
+ ),
+ # The SQL prefilter matches this on its 100% release condition; only the checker
+ # confirmation keeps a flag that still splits traffic between variants out.
+ (
+ "multivariate_without_winner_still_called",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ False,
+ ),
+ # A holdout is resolved before the release conditions, so part of the population never
+ # reaches the 100% group the prefilter matched. The checker never reads the key.
+ (
+ "constant_and_called_behind_holdout",
+ {
+ **constant_and_called(),
+ "filters": {**FULL_ROLLOUT_FILTERS, "holdout": {"id": 1, "exclusion_percentage": 10}},
+ },
+ None,
+ False,
+ ),
+ # Group aggregation, device-id bucketing and feature enrollment decide the result from
+ # evaluation context the configuration does not carry, so the blanket condition does not
+ # reach everyone.
+ (
+ "constant_but_group_aggregated",
+ {**constant_and_called(), "filters": {**FULL_ROLLOUT_FILTERS, "aggregation_group_type_index": 0}},
+ None,
+ False,
+ ),
+ (
+ "constant_but_condition_group_aggregated",
+ {
+ **constant_and_called(),
+ "filters": {
+ "groups": [{"properties": [], "rollout_percentage": 100, "aggregation_group_type_index": 0}]
+ },
+ },
+ None,
+ False,
+ ),
+ # An explicit null index means person aggregation, so it must not be read as a group.
+ (
+ "constant_with_null_aggregation_index",
+ {
+ **constant_and_called(),
+ "filters": {
+ "groups": [{"properties": [], "rollout_percentage": 100, "aggregation_group_type_index": None}]
+ },
+ },
+ None,
+ True,
+ ),
+ (
+ "constant_but_device_id_bucketed",
+ {**constant_and_called(), "bucketing_identifier": "device_id"},
+ None,
+ False,
+ ),
+ (
+ "constant_but_feature_enrollment",
+ {**constant_and_called(), "filters": {**FULL_ROLLOUT_FILTERS, "feature_enrollment": True}},
+ None,
+ False,
+ ),
+ # The matcher ignores an override naming a variant the flag does not configure, so the
+ # distribution decides and a split one is not constant.
+ (
+ "constant_but_unknown_variant_override",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "a", "rollout_percentage": 50},
+ {"key": "b", "rollout_percentage": 50},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100, "variant": "ghost"}],
+ },
+ },
+ None,
+ False,
+ ),
+ # A legacy scalar `groups` makes jsonb_array_elements raise, which aborts the statement
+ # for every team in the batch rather than skipping the row.
+ (
+ "legacy_scalar_groups_does_not_abort_the_batch",
+ {**constant_and_called(), "filters": {"groups": "all"}},
+ None,
+ False,
+ ),
+ # A targeted condition declared before the blanket one decides the result for the users
+ # it matches, so the cohort it pins to "test" never receives the named winner.
+ (
+ "constant_but_targeted_variant_override_first",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 100},
+ {"key": "test", "rollout_percentage": 0},
+ ]
+ },
+ "groups": [
+ {
+ "properties": [{"key": "email", "value": "x"}],
+ "rollout_percentage": 100,
+ "variant": "test",
+ },
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ },
+ },
+ None,
+ False,
+ ),
+ # The same two conditions the other way round. The matcher stops at the blanket one, so
+ # the override below it is unreachable and the flag really does serve one variant.
+ (
+ "constant_when_the_blanket_condition_comes_first",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 100},
+ {"key": "test", "rollout_percentage": 0},
+ ]
+ },
+ "groups": [
+ {"properties": [], "rollout_percentage": 100},
+ {
+ "properties": [{"key": "email", "value": "x"}],
+ "rollout_percentage": 100,
+ "variant": "test",
+ },
+ ],
+ },
+ },
+ None,
+ True,
+ ),
+ # Variants take cumulative slices in order, so the 40 still owns the low hashes and the
+ # flag serves two variants despite the 100.
+ (
+ "constant_but_variants_overallocated",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 40},
+ {"key": "test", "rollout_percentage": 100},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ False,
+ ),
+ # The same pair the other way round is constant: nothing takes a hash before the 100.
+ (
+ "constant_when_the_hundred_comes_first",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 100},
+ {"key": "test", "rollout_percentage": 40},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ True,
+ ),
+ # A variant at zero takes no hashes, so the winner owns the whole space from wherever it
+ # is declared. This is the shape a shipped experiment leaves behind.
+ (
+ "constant_when_the_winner_is_not_the_first_variant",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 0},
+ {"key": "test", "rollout_percentage": 100},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ True,
+ ),
+ # The two escape hatches with no case of their own. Both short-circuit ahead of the
+ # release conditions, the same way the holdout above does.
+ (
+ "constant_and_called_behind_super_groups",
+ {
+ **constant_and_called(),
+ "filters": {
+ **FULL_ROLLOUT_FILTERS,
+ "super_groups": [{"properties": [], "rollout_percentage": 100}],
+ },
+ },
+ None,
+ False,
+ ),
+ (
+ "constant_and_called_behind_holdout_groups",
+ {
+ **constant_and_called(),
+ "filters": {
+ **FULL_ROLLOUT_FILTERS,
+ "holdout_groups": [{"properties": [], "rollout_percentage": 10}],
+ },
+ },
+ None,
+ False,
+ ),
+ # `early_exit` returns false on a failed rollout check instead of falling through to the
+ # blanket group, so the configuration can serve two results.
+ (
+ "constant_and_called_with_early_exit",
+ {
+ **constant_and_called(),
+ "filters": {
+ "groups": [
+ {"properties": [{"key": "email", "value": "x"}], "rollout_percentage": 50},
+ {"properties": [], "rollout_percentage": 100},
+ ],
+ "early_exit": True,
+ },
+ },
+ None,
+ False,
+ ),
# A trigger group gates recording just as the linked-flag column does, so the flag it
# names is not a cleanup candidate either.
("replay_trigger_group_linked", stale_by_config(), "replay_trigger_group", False),
@@ -154,8 +475,8 @@ class TestStaleFlagsDetect(BaseTest):
results = self._detect()
- included = any(result.payload["flag_id"] == flag.id for result in results.get(self.team.id, []))
- assert included is expected_included
+ matching = [result for result in results.get(self.team.id, []) if result.payload["flag_id"] == flag.id]
+ assert len(matching) == (1 if expected_included else 0)
def test_a_gate_stored_in_another_project_still_protects_the_flag(self) -> None:
# Flag ids are globally unique, so a team can store a flag another project owns. Matching
@@ -225,6 +546,20 @@ class TestStaleFlagsDetect(BaseTest):
},
{"rollout_state": ROLLOUT_PARTIAL, "has_targeting_conditions": True, "max_rollout_percentage": 100},
),
+ (
+ "effectively_full_rollout_while_called",
+ constant_and_called(),
+ {
+ "evidence_class": EVIDENCE_EFFECTIVELY_FULL_ROLLOUT,
+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,
+ # The evidence is the configuration, so the date is the flag's age, not its
+ # last call.
+ "days_since_evidence": 60,
+ "has_targeting_conditions": False,
+ "max_rollout_percentage": 100,
+ "winning_variant": None,
+ },
+ ),
(
"multivariate_winning_variant",
{
@@ -240,6 +575,28 @@ class TestStaleFlagsDetect(BaseTest):
"winning_variant": "control",
},
),
+ # The matcher ignores the override and serves the distribution, so the payload must
+ # name `control` and not the key the condition carries.
+ (
+ "multivariate_override_names_an_absent_variant",
+ {
+ **constant_and_called(),
+ "filters": {
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 100},
+ {"key": "test", "rollout_percentage": 0},
+ ]
+ },
+ "groups": [{"properties": [], "rollout_percentage": 100, "variant": "ghost"}],
+ },
+ },
+ {
+ "evidence_class": EVIDENCE_EFFECTIVELY_FULL_ROLLOUT,
+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,
+ "winning_variant": "control",
+ },
+ ),
]
)
def test_payload_evidence_and_rollout(
@@ -249,7 +606,9 @@ class TestStaleFlagsDetect(BaseTest):
results = self._detect()
- result = next(r for r in results[self.team.id] if r.payload["flag_id"] == flag.id)
+ # One result per flag, not the first of several: a flag both candidate sources return
+ # would otherwise report twice under whichever evidence class happened to come first.
+ (result,) = [r for r in results[self.team.id] if r.payload["flag_id"] == flag.id]
assert result.severity == HealthIssue.Severity.INFO
assert result.hash_keys == ["flag_id"]
assert result.payload["flag_key"] == key
@@ -447,6 +806,25 @@ class TestStaleFlagsContract(SimpleTestCase):
assert "serves a fixed result" in content.summary
assert content.link == "/feature_flags/7"
+ def test_render_alert_for_effectively_full_rollout_evidence(self) -> None:
+ content = StaleFeatureFlagsCheck.render_alert(
+ self._issue(
+ {
+ "flag_id": 11,
+ "flag_key": "ga-toggle",
+ "evidence_class": EVIDENCE_EFFECTIVELY_FULL_ROLLOUT,
+ "days_since_evidence": 200,
+ "rollout_state": ROLLOUT_FULLY_ROLLED_OUT,
+ }
+ )
+ )
+ assert "PostHog still receives calls for this flag" in content.summary
+ assert "fully rolled out" in content.summary
+ # days_since_evidence is the flag's age on this class, so it must not be narrated as a
+ # gap since the last call.
+ assert "200" not in content.summary
+ assert content.link == "/feature_flags/11"
+
def test_render_signal_returns_none(self) -> None:
issue = self._issue({"flag_id": 42, "flag_key": "checkout-v2"})
assert StaleFeatureFlagsCheck.render_signal(issue) is None
diff --git a/products/feature_flags/backend/test/test_flag_status.py b/products/feature_flags/backend/test/test_flag_status.py
index d21687dd5ee0..a5ffc333b889 100644
--- a/products/feature_flags/backend/test/test_flag_status.py
+++ b/products/feature_flags/backend/test/test_flag_status.py
@@ -193,6 +193,24 @@ class TestFilterFlagsByActiveParam(BaseTest):
},
False,
),
+ # The two legacy shapes the checker reads as no targeting. Each matches its own arm
+ # of the SQL: an absent key is SQL NULL, a stored null is the jsonb scalar `null`.
+ (
+ "properties_key_absent",
+ {
+ "created_at": timezone.now() - timedelta(days=60),
+ "filters": {"groups": [{"rollout_percentage": 100}]},
+ },
+ True,
+ ),
+ (
+ "null_properties",
+ {
+ "created_at": timezone.now() - timedelta(days=60),
+ "filters": {"groups": [{"properties": None, "rollout_percentage": 100}]},
+ },
+ True,
+ ),
# Only case that reaches the config branch's last OR arm, where `filters` being
# non-nullable makes `= '{}'` the whole test.
(
@@ -214,6 +232,37 @@ class TestFilterFlagsByActiveParam(BaseTest):
assert filter_stale == self._checker_stale()
assert (key in filter_stale) is expected_stale
+ def test_stale_filter_honours_an_explicit_threshold(self) -> None:
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="called-ten-days-ago",
+ active=True,
+ last_called_at=timezone.now() - timedelta(days=10),
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+
+ def stale_keys(**kwargs: Any) -> set[str]:
+ return {flag.key for flag in filter_stale_flags(FeatureFlag.objects.filter(team=self.team), **kwargs)}
+
+ assert "called-ten-days-ago" not in stale_keys()
+ assert "called-ten-days-ago" in stale_keys(stale_threshold=timezone.now() - timedelta(days=5))
+
+ def test_stale_filter_survives_a_legacy_scalar_groups_value(self) -> None:
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="scalar-groups",
+ active=True,
+ created_at=timezone.now() - timedelta(days=60),
+ filters={"groups": "all"},
+ created_by=self.user,
+ )
+
+ # Without the guard `jsonb_array_elements` raises, and the error aborts the statement for
+ # every flag the query covers rather than skipping this row.
+ assert "scalar-groups" not in self._filter("STALE")
+ assert "stale" in self._filter("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)))
@@ -271,6 +320,14 @@ class TestRolloutSummary(BaseTest):
100,
False,
),
+ (
+ "null_group_properties",
+ {"groups": [{"properties": None, "rollout_percentage": 100}]},
+ True,
+ False,
+ 100,
+ False,
+ ),
# A missing rollout_percentage evaluates to 100% at runtime, so max_rollout_percentage
# reflects that. effectively_full_rollout stays stricter (requires an explicit 100), to
# match the staleness detection it shares logic with.
@@ -301,6 +358,20 @@ class TestRolloutSummary(BaseTest):
100,
True,
),
+ # The multivariate path reads the same null `properties` through
+ # is_group_fully_rolled_out, where `len(None)` used to raise. The boolean case above
+ # reaches is_boolean_flag_fully_rolled_out instead.
+ (
+ "multivariate_null_group_properties",
+ {
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ "groups": [{"properties": None, "rollout_percentage": 100}],
+ },
+ True,
+ False,
+ 100,
+ True,
+ ),
(
"multivariate_not_fully_rolled_out",
{