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.

chore(flags): drop the without-cohorts flag definitions cache (#69535)

Phil Haackc90aca384b22
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index fc1f1307b329..8558500a5d67 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -151,27 +151,18 @@ This matches the Rust fallback path's petgraph-based cycle handling, where all c
## Local evaluation caching
-Feature flag local evaluation uses two separate HyperCache instances in `posthog/models/feature_flag/local_evaluation.py`:
+Feature flag local evaluation uses a HyperCache instance in `products/feature_flags/backend/local_evaluation.py`:
```python
-# Full flags with cohort definitions (for smart clients)
flag_definitions_hypercache = HyperCache(
namespace="feature_flags",
value="flags_with_cohorts.json",
- load_fn=lambda key: _get_flags_response_for_local_evaluation(team, include_cohorts=True),
- enable_etag=True,
-)
-
-# Simplified flags without cohorts (legacy)
-flag_definitions_without_cohorts_hypercache = HyperCache(
- namespace="feature_flags",
- value="flags_without_cohorts.json",
- load_fn=lambda key: _get_flags_response_for_local_evaluation(team, include_cohorts=False),
+ load_fn=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key)),
enable_etag=True,
)
```
-All current SDKs support cohort evaluation locally, so the dual-cache strategy is legacy. The `flag_definitions_without_cohorts_hypercache` cache exists for older SDK versions that couldn't handle cohort definitions. Once requests for flags without cohorts decline sufficiently, this cache can be removed.
+It includes full cohort definitions and group type mappings, since all current SDKs support cohort evaluation locally. A legacy `flag_definitions_without_cohorts_hypercache` variant — pre-flattened cohort filters for SDKs too old to evaluate cohorts locally — was removed once nothing served it to real clients anymore.
### Cache invalidation
@@ -358,12 +349,11 @@ The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache u
Cache freshness is maintained through scheduled Celery tasks.
-| Task | Schedule | Purpose |
-| ------------------------------------------------------------ | ---------------- | ---------------------------------------------------------------- |
-| `refresh_expiring_flags_cache_entries` | Hourly at :15 | Refresh caches with TTL < 24h before they expire |
-| `cleanup_stale_flags_expiry_tracking_task` | Daily at 3:15 AM | Remove expired team entries from tracking sorted set |
-| `verify_and_fix_flag_definitions_cache_task` | Hourly at :50 | Verify flag definitions cache (with cohorts) against database |
-| `verify_and_fix_flag_definitions_without_cohorts_cache_task` | Hourly at :10 | Verify flag definitions cache (without cohorts) against database |
+| Task | Schedule | Purpose |
+| -------------------------------------------- | ---------------- | ---------------------------------------------------- |
+| `refresh_expiring_flags_cache_entries` | Hourly at :15 | Refresh caches with TTL < 24h before they expire |
+| `cleanup_stale_flags_expiry_tracking_task` | Daily at 3:15 AM | Remove expired team entries from tracking sorted set |
+| `verify_and_fix_flag_definitions_cache_task` | Hourly at :50 | Verify flag definitions cache against database |
### Refresh task
@@ -383,15 +373,15 @@ The task uses a Redis sorted set (`flags_cache_expiry`) to efficiently find expi
### Verification tasks
-Two independent verification tasks compare cached flag definitions against the database and fix discrepancies — one for the with-cohorts variant (runs at :50) and one for the without-cohorts variant (runs at :10). Each task:
+The flag definitions verification task (runs hourly at :50) compares cached flag definitions against the database and fixes discrepancies:
-1. Acquires its own distributed lock (so one variant can't block the other)
+1. Acquires a distributed lock so overlapping scheduled runs skip instead of duplicating work
2. Samples teams from the cache
3. Compares cached flags to current database state
4. Auto-fixes mismatches by refreshing the cache
5. Reports metrics on match/mismatch/miss rates
-Each task has a 25-minute soft / 30-minute hard time limit, since each only handles one variant.
+The task has a 25-minute soft / 30-minute hard time limit.
Configuration:
diff --git a/posthog/management/commands/verify_flag_definitions_cache.py b/posthog/management/commands/verify_flag_definitions_cache.py
index 471b8fe3a0cd..d8fbca539b9b 100644
--- a/posthog/management/commands/verify_flag_definitions_cache.py
+++ b/posthog/management/commands/verify_flag_definitions_cache.py
@@ -2,8 +2,7 @@
Management command to verify flag definitions cache consistency.
Compares cached flag definitions data against database to detect discrepancies.
-Verifies both cache variants (with-cohorts and without-cohorts). When --fix is
-used, each variant's cache is updated independently.
+When --fix is used, the cache is updated to match the database.
Usage:
# Verify all teams
@@ -29,7 +28,6 @@ from posthog.models.team import Team
from products.feature_flags.backend.local_evaluation import (
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
verify_team_flag_definitions,
)
@@ -83,38 +81,21 @@ class Command(BaseHyperCacheCommand):
if not self.validate_sample_size(sample_size):
return
- configs_to_verify = [
- (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG, True, "with cohorts"),
- (FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG, False, "without cohorts"),
- ]
-
- for config, include_cohorts, variant_name in configs_to_verify:
- self.stdout.write(f"\n{'=' * 70}")
- self.stdout.write(self.style.SUCCESS(f"Verifying flag definitions cache ({variant_name})"))
- self.stdout.write("=" * 70)
-
- # Store config and include_cohorts for the verify_team method
- # Note: Not thread-safe, but management commands run single-threaded
- self._current_config = config
- self._include_cohorts = include_cohorts
-
- self.run_verification(
- team_ids=team_ids,
- sample_size=sample_size,
- verbose=verbose,
- fix=fix,
- )
+ self.run_verification(
+ team_ids=team_ids,
+ sample_size=sample_size,
+ verbose=verbose,
+ fix=fix,
+ )
def get_hypercache_config(self):
"""Return the HyperCache management configuration."""
- return getattr(self, "_current_config", FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG)
+ return FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG
def verify_team(self, team: Team, verbose: bool, batch_data: dict[int, Any] | None = None) -> dict[str, Any]:
"""Verify a single team's flag definitions cache against the database."""
- include_cohorts = getattr(self, "_include_cohorts", True)
return verify_team_flag_definitions(
team,
db_batch_data=batch_data,
- include_cohorts=include_cohorts,
verbose=verbose,
)
diff --git a/posthog/management/commands/warm_flag_definitions_cache.py b/posthog/management/commands/warm_flag_definitions_cache.py
index a3e43ec57c60..9a74242e4ace 100644
--- a/posthog/management/commands/warm_flag_definitions_cache.py
+++ b/posthog/management/commands/warm_flag_definitions_cache.py
@@ -1,7 +1,5 @@
"""
-Management command to warm the flag definitions cache.
-
-This warms both cache variants (with and without cohorts) used for SDK local evaluation.
+Management command to warm the flag definitions cache used for SDK local evaluation.
Usage:
# Initial cache warm (preserves existing caches)
@@ -10,20 +8,13 @@ Usage:
# Warm specific teams
python manage.py warm_flag_definitions_cache --team-ids 12345 67890
- # Warm only one variant
- python manage.py warm_flag_definitions_cache --variant with-cohorts
- python manage.py warm_flag_definitions_cache --variant without-cohorts
-
# Custom batch size and TTL range
python manage.py warm_flag_definitions_cache --batch-size 200 --min-ttl-days 6 --max-ttl-days 8
"""
from posthog.management.commands._base_hypercache_command import BaseHyperCacheCommand
-from products.feature_flags.backend.local_evaluation import (
- FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
-)
+from products.feature_flags.backend.local_evaluation import FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG
class Command(BaseHyperCacheCommand):
@@ -32,12 +23,6 @@ class Command(BaseHyperCacheCommand):
def add_arguments(self, parser):
self.add_common_team_arguments(parser)
self.add_warm_arguments(parser)
- parser.add_argument(
- "--variant",
- type=str,
- choices=["with-cohorts", "without-cohorts"],
- help="Warm only the specified variant (default: both)",
- )
def handle(self, *args, **options):
# No check_dedicated_cache_configured() needed — flag definitions use the
@@ -47,7 +32,6 @@ class Command(BaseHyperCacheCommand):
stagger_ttl = not options["no_stagger"]
min_ttl_days = options["min_ttl_days"]
max_ttl_days = options["max_ttl_days"]
- variant = options.get("variant")
# Validate input arguments to prevent resource exhaustion
if not self.validate_batch_size(batch_size):
@@ -55,37 +39,14 @@ class Command(BaseHyperCacheCommand):
if not self.validate_ttl_range(min_ttl_days, max_ttl_days):
return
- # Determine which configs to warm
- configs_to_warm = []
- if variant == "with-cohorts":
- configs_to_warm = [(FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG, "with cohorts")]
- elif variant == "without-cohorts":
- configs_to_warm = [(FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG, "without cohorts")]
- else:
- # Warm both variants
- configs_to_warm = [
- (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG, "with cohorts"),
- (FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG, "without cohorts"),
- ]
-
- # Warm each variant
- for config, variant_name in configs_to_warm:
- self.stdout.write(f"\n{'=' * 70}")
- self.stdout.write(self.style.SUCCESS(f"Warming flag definitions cache ({variant_name})"))
- self.stdout.write("=" * 70)
-
- # Store the config for get_hypercache_config()
- # Note: Not thread-safe, but management commands run single-threaded
- self._current_config = config
-
- self.run_warm(
- team_ids=team_ids,
- batch_size=batch_size,
- stagger_ttl=stagger_ttl,
- min_ttl_days=min_ttl_days,
- max_ttl_days=max_ttl_days,
- )
+ self.run_warm(
+ team_ids=team_ids,
+ batch_size=batch_size,
+ stagger_ttl=stagger_ttl,
+ min_ttl_days=min_ttl_days,
+ max_ttl_days=max_ttl_days,
+ )
def get_hypercache_config(self):
"""Return the HyperCache management configuration."""
- return getattr(self, "_current_config", FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG)
+ return FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index bf026373f487..f0a5187e827d 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -841,7 +841,6 @@
'tagged_items',
'team_id',
'tombstoned_key',
- 'transform_cohort_filters_for_easy_evaluation',
'usage_dashboard',
'usage_dashboard_has_enriched_insights',
'usage_dashboard_id',
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index bfeef5858219..c2c7d169ece9 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -760,6 +760,10 @@ SPECTACULAR_SETTINGS = {
# redis/miss choice set. Pin to a stable name so the collision doesn't auto-resolve
# to a hash name.
"StaffCacheSourceEnum": ["redis", "miss"],
+ # StaffCacheEntryQuery/Response's singular `cache` field and StaffCacheMutation's
+ # `caches` list item share the same evaluation/definitions choice set. Pin to a
+ # stable name so "cache" and "caches" don't collide into a hash name.
+ "StaffCacheKindEnum": ["evaluation", "definitions"],
},
}
diff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.py
index 1404d8acddba..8bce9d57a59e 100644
--- a/posthog/tasks/hypercache_verification.py
+++ b/posthog/tasks/hypercache_verification.py
@@ -10,7 +10,6 @@ Provides separate tasks for verifying and fixing each HyperCache-backed cache
"""
import time
-from functools import partial
from typing import Literal
from django.conf import settings
@@ -21,13 +20,11 @@ from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded
from posthog.exceptions_capture import capture_exception
-from posthog.storage.hypercache_manager import HyperCacheManagementConfig
from posthog.storage.hypercache_verifier import _run_verification_for_cache
from posthog.tasks.utils import CeleryQueue, PushGatewayTask
from products.feature_flags.backend.local_evaluation import (
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
verify_team_flag_definitions,
)
@@ -42,10 +39,11 @@ LOCK_TIMEOUT_SECONDS = 25 * 60 # 25 minutes
# Flag definitions verification lock timeout matches time_limit (30 min) to ensure
# the lock expires before the next scheduled run if a task crashes without executing
-# its finally block. Each variant runs hourly (without-cohorts at minute 10, with-cohorts
-# at minute 50), so a 30-minute lock expiry guarantees at most 1 run is skipped after a crash.
+# its finally block, guaranteeing at most 1 run is skipped after a crash.
FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS = 30 * 60 # 30 minutes
+FLAG_DEFINITIONS_CACHE_TYPE = "flag_definitions"
+
def _log_soft_time_limit_exceeded(cache_type: str, start_time: float) -> None:
# Not a failure: the run wound down early because it ran out of time.
@@ -57,51 +55,44 @@ def _log_soft_time_limit_exceeded(cache_type: str, start_time: float) -> None:
)
-def _run_flag_definitions_verification(
- config: HyperCacheManagementConfig,
- include_cohorts: bool,
- variant_name: str,
-) -> None:
+def _run_flag_definitions_verification() -> None:
"""
- Run verification for a flag definitions cache variant.
+ Run verification for the flag definitions cache.
- Acquires a distributed lock keyed by variant_name and runs verification for
- the given config. The with-cohorts and without-cohorts variants use separate
- locks, allowing parallel execution when workers are available.
+ Acquires a distributed lock so overlapping scheduled runs skip instead of
+ duplicating work.
Note: Unlike the flags cache (which uses FLAGS_REDIS_URL), the flag definitions
cache uses the default cache backend (REDIS_URL). No special guard needed since
Django's default cache is always available.
"""
- cache_type = f"flag_definitions_{variant_name}"
- lock_key = f"posthog:hypercache_verification:{cache_type}:lock"
+ lock_key = f"posthog:hypercache_verification:{FLAG_DEFINITIONS_CACHE_TYPE}:lock"
if not django_cache.add(lock_key, "locked", timeout=FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS):
- logger.info("Skipping cache verification - already running", cache_type=cache_type)
+ logger.info("Skipping cache verification - already running", cache_type=FLAG_DEFINITIONS_CACHE_TYPE)
return
try:
- logger.info("Starting cache verification", cache_type=cache_type)
+ logger.info("Starting cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE)
start_time = time.time()
- verify_fn = partial(verify_team_flag_definitions, include_cohorts=include_cohorts)
try:
_run_verification_for_cache(
- config=config,
- verify_team_fn=verify_fn,
- cache_type=cache_type,
+ config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
+ verify_team_fn=verify_team_flag_definitions,
+ cache_type=FLAG_DEFINITIONS_CACHE_TYPE,
chunk_size=settings.FLAGS_CACHE_VERIFICATION_CHUNK_SIZE,
)
except SoftTimeLimitExceeded:
- _log_soft_time_limit_exceeded(cache_type, start_time)
+ _log_soft_time_limit_exceeded(FLAG_DEFINITIONS_CACHE_TYPE, start_time)
return
except Exception as e:
- logger.exception("Failed cache verification", cache_type=cache_type, error=str(e))
+ logger.exception("Failed cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE, error=str(e))
capture_exception(e)
raise
duration = time.time() - start_time
- logger.info("Completed cache verification", cache_type=cache_type, duration_seconds=duration)
+ logger.info("Completed cache verification", cache_type=FLAG_DEFINITIONS_CACHE_TYPE, duration_seconds=duration)
finally:
django_cache.delete(lock_key)
@@ -219,43 +210,13 @@ def verify_and_fix_team_metadata_cache_task(self: PushGatewayTask) -> None:
)
def verify_and_fix_flag_definitions_cache_task(self: PushGatewayTask) -> None:
"""
- Periodic task to verify the flag definitions (with-cohorts) HyperCache and fix issues.
-
- Runs hourly at minute 50. Verifies all teams' flag definitions cache entries
- that include cohort data, fixing cache misses, mismatches, or expiry tracking issues.
-
- Uses a per-variant distributed lock to skip execution if a previous run is still in progress.
-
- Metrics: posthog_hypercache_verify_fixes_total{cache_type="flag_definitions_with-cohorts", issue_type="..."}
- """
- _run_flag_definitions_verification(
- config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- include_cohorts=True,
- variant_name="with-cohorts",
- )
-
-
-@shared_task(
- bind=True,
- base=PushGatewayTask,
- ignore_result=True,
- queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
- soft_time_limit=25 * 60, # 25 min soft limit
- time_limit=30 * 60, # 30 min hard limit (matches FLAG_DEFINITIONS_LOCK_TIMEOUT_SECONDS)
-)
-def verify_and_fix_flag_definitions_without_cohorts_cache_task(self: PushGatewayTask) -> None:
- """
- Periodic task to verify the flag definitions (without-cohorts) HyperCache and fix issues.
+ Periodic task to verify the flag definitions HyperCache and fix issues.
- Runs hourly at minute 10. Verifies all teams' flag definitions cache entries
- that exclude cohort data, fixing cache misses, mismatches, or expiry tracking issues.
+ Runs hourly at minute 50. Verifies all teams' flag definitions cache entries,
+ fixing cache misses, mismatches, or expiry tracking issues.
- Uses a per-variant distributed lock to skip execution if a previous run is still in progress.
+ Uses a distributed lock to skip execution if a previous run is still in progress.
- Metrics: posthog_hypercache_verify_fixes_total{cache_type="flag_definitions_without-cohorts", issue_type="..."}
+ Metrics: posthog_hypercache_verify_fixes_total{cache_type="flag_definitions", issue_type="..."}
"""
- _run_flag_definitions_verification(
- config=FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
- include_cohorts=False,
- variant_name="without-cohorts",
- )
+ _run_flag_definitions_verification()
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index b934044d853d..c5df63cca64d 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -20,7 +20,6 @@ from posthog.tasks.email import (
from posthog.tasks.gateway_credential import drain_gateway_credential_last_used_task, refresh_gateway_credentials
from posthog.tasks.hypercache_verification import (
verify_and_fix_flag_definitions_cache_task,
- verify_and_fix_flag_definitions_without_cohorts_cache_task,
verify_and_fix_flags_cache_task,
verify_and_fix_team_metadata_cache_task,
)
@@ -327,22 +326,12 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
expires_seconds=30 * 60,
)
- # Verify flag definitions cache without cohorts - hourly at minute 10
- # Minute 10 reduces the likelihood of overlapping with team_metadata verification at minute 20 and helps spread load.
- add_periodic_task_with_expiry(
- sender,
- crontab(hour="*", minute="10"),
- verify_and_fix_flag_definitions_without_cohorts_cache_task.s(),
- name="verify and fix flag definitions cache (without cohorts)",
- expires_seconds=60 * 60,
- )
-
- # Flag definitions cache verification (with cohorts) - hourly at minute 50
+ # Flag definitions cache verification - hourly at minute 50
add_periodic_task_with_expiry(
sender,
crontab(hour="*", minute="50"),
verify_and_fix_flag_definitions_cache_task.s(),
- name="verify and fix flag definitions cache (with cohorts)",
+ name="verify and fix flag definitions cache",
expires_seconds=60 * 60,
)
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index a0791316bdf0..94403a32bb1f 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -68,7 +68,6 @@
'posthog.tasks.gateway_credential.update_gateway_credential_cache_task',
'posthog.tasks.health_checks.evaluate_health_check_for_team',
'posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_cache_task',
- 'posthog.tasks.hypercache_verification.verify_and_fix_flag_definitions_without_cohorts_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_flags_cache_task',
'posthog.tasks.hypercache_verification.verify_and_fix_team_metadata_cache_task',
'posthog.tasks.integrations.delete_ses_identity_if_unused',
diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.py
index 37cca7d2c1d0..0f1e2225b03e 100644
--- a/posthog/tasks/test/test_hypercache_verification.py
+++ b/posthog/tasks/test/test_hypercache_verification.py
@@ -7,18 +7,14 @@ Tests cover:
- Tasks skip when FLAGS_REDIS_URL not configured
"""
-from collections.abc import Callable
-
from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
from celery.exceptions import SoftTimeLimitExceeded
-from parameterized import parameterized
from posthog.tasks.hypercache_verification import (
verify_and_fix_flag_definitions_cache_task,
- verify_and_fix_flag_definitions_without_cohorts_cache_task,
verify_and_fix_flags_cache_task,
verify_and_fix_team_metadata_cache_task,
)
@@ -152,109 +148,36 @@ class TestVerifyAndFixTeamMetadataCacheTaskDisabled(TestCase):
mock_run_verification.assert_not_called()
-# Parameterized test configuration for the two flag definitions cache variants.
-# Each tuple: (task_fn, include_cohorts, cache_type, other_cache_type, metric_name_fragment)
-FLAG_DEFINITIONS_VARIANTS = [
- (
- "with_cohorts",
- verify_and_fix_flag_definitions_cache_task,
- True,
- "flag_definitions_with-cohorts",
- "flag_definitions_without-cohorts",
- "verify_and_fix_flag_definitions_cache_task",
- ),
- (
- "without_cohorts",
- verify_and_fix_flag_definitions_without_cohorts_cache_task,
- False,
- "flag_definitions_without-cohorts",
- "flag_definitions_with-cohorts",
- "verify_and_fix_flag_definitions_without_cohorts_cache_task",
- ),
-]
-
-
class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCase):
- """Tests for both flag definitions cache verification task variants."""
-
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
- @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_verifies_correct_cache_type(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- cache_type: str,
- _other: str,
- _metric: str,
- mock_run_verification: MagicMock,
- ) -> None:
- mock_run_verification.return_value = MagicMock()
-
- task_fn()
-
- mock_run_verification.assert_called_once()
- call_kwargs = mock_run_verification.call_args[1]
- assert call_kwargs["cache_type"] == cache_type
-
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_verify_fn_passes_correct_include_cohorts(
- self,
- _name: str,
- task_fn: Callable[[], None],
- include_cohorts: bool,
- _cache_type: str,
- _other: str,
- _metric: str,
- mock_run_verification: MagicMock,
- ) -> None:
+ def test_verifies_flag_definitions_cache(self, mock_run_verification: MagicMock) -> None:
from products.feature_flags.backend.local_evaluation import verify_team_flag_definitions
mock_run_verification.return_value = MagicMock()
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
- verify_fn = mock_run_verification.call_args[1]["verify_team_fn"]
- assert verify_fn.func is verify_team_flag_definitions
- assert verify_fn.keywords == {"include_cohorts": include_cohorts}
+ mock_run_verification.assert_called_once()
+ call_kwargs = mock_run_verification.call_args[1]
+ assert call_kwargs["cache_type"] == "flag_definitions"
+ assert call_kwargs["verify_team_fn"] is verify_team_flag_definitions
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification.capture_exception")
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_captures_and_reraises_error(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- _cache_type: str,
- _other: str,
- _metric: str,
- mock_run_verification: MagicMock,
- mock_capture: MagicMock,
- ) -> None:
+ def test_captures_and_reraises_error(self, mock_run_verification: MagicMock, mock_capture: MagicMock) -> None:
error = Exception("flag_definitions verification failed")
mock_run_verification.side_effect = error
with self.assertRaises(Exception) as context:
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
mock_capture.assert_called_once_with(error)
assert context.exception is error
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification.capture_exception")
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
def test_soft_time_limit_exceeded_winds_down_without_capturing(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- _cache_type: str,
- _other: str,
- metric_name: str,
- mock_run_verification: MagicMock,
- mock_capture: MagicMock,
+ self, mock_run_verification: MagicMock, mock_capture: MagicMock
) -> None:
"""A run that hits the soft time limit winds down cleanly: unlike a real
verification failure, it is not captured as an error or re-raised, and the
@@ -262,98 +185,46 @@ class TestVerifyAndFixFlagDefinitionsCacheTask(PushGatewayTaskTestMixin, TestCas
mock_run_verification.side_effect = SoftTimeLimitExceeded()
# Should not raise
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
mock_capture.assert_not_called()
- success = self.registry.get_sample_value(f"posthog_celery_{metric_name}_success")
+ success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
assert success == 1
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_releases_lock_after_error(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- cache_type: str,
- _other: str,
- _metric: str,
- mock_run_verification: MagicMock,
- ) -> None:
+ def test_releases_lock_after_error(self, mock_run_verification: MagicMock) -> None:
from django.core.cache import cache as django_cache
mock_run_verification.side_effect = Exception("boom")
with self.assertRaises(Exception):
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
- lock_key = f"posthog:hypercache_verification:{cache_type}:lock"
+ lock_key = "posthog:hypercache_verification:flag_definitions:lock"
assert django_cache.add(lock_key, "test", timeout=1) is True
django_cache.delete(lock_key)
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_does_not_interfere_with_other_variant_lock(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- _cache_type: str,
- other_cache_type: str,
- _metric: str,
- mock_run_verification: MagicMock,
- ) -> None:
- """Each variant uses its own lock key, so locking one doesn't block the other."""
- from django.core.cache import cache as django_cache
-
- other_lock_key = f"posthog:hypercache_verification:{other_cache_type}:lock"
- django_cache.add(other_lock_key, "locked", timeout=60)
- try:
- mock_run_verification.return_value = MagicMock()
- task_fn()
- mock_run_verification.assert_called_once()
- finally:
- django_cache.delete(other_lock_key)
-
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
- @patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_pushgateway_metrics_recorded_on_success(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- _cache_type: str,
- _other: str,
- metric_name: str,
- mock_run_verification: MagicMock,
- ) -> None:
+ def test_pushgateway_metrics_recorded_on_success(self, mock_run_verification: MagicMock) -> None:
mock_run_verification.return_value = MagicMock()
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
- success = self.registry.get_sample_value(f"posthog_celery_{metric_name}_success")
- duration = self.registry.get_sample_value(f"posthog_celery_{metric_name}_duration_seconds")
+ success = self.registry.get_sample_value("posthog_celery_verify_and_fix_flag_definitions_cache_task_success")
+ duration = self.registry.get_sample_value(
+ "posthog_celery_verify_and_fix_flag_definitions_cache_task_duration_seconds"
+ )
assert success == 1
assert duration is not None and duration >= 0
- @parameterized.expand(FLAG_DEFINITIONS_VARIANTS)
@patch("posthog.tasks.hypercache_verification._run_verification_for_cache")
- def test_skips_when_lock_already_held(
- self,
- _name: str,
- task_fn: Callable[[], None],
- _include_cohorts: bool,
- cache_type: str,
- _other: str,
- _metric: str,
- mock_run_verification: MagicMock,
- ) -> None:
+ def test_skips_when_lock_already_held(self, mock_run_verification: MagicMock) -> None:
from django.core.cache import cache as django_cache
- lock_key = f"posthog:hypercache_verification:{cache_type}:lock"
+ lock_key = "posthog:hypercache_verification:flag_definitions:lock"
django_cache.add(lock_key, "locked", timeout=60)
try:
- task_fn()
+ verify_and_fix_flag_definitions_cache_task()
mock_run_verification.assert_not_called()
finally:
django_cache.delete(lock_key)
diff --git a/products/feature_flags/backend/api/staff_cache.py b/products/feature_flags/backend/api/staff_cache.py
index 507e5a80d718..ec00c550c529 100644
--- a/products/feature_flags/backend/api/staff_cache.py
+++ b/products/feature_flags/backend/api/staff_cache.py
@@ -15,10 +15,7 @@ from posthog.models.team import Team
from posthog.permissions import IsStaffUser
from products.feature_flags.backend.flags_cache import enqueue_evaluation_cache_invalidation, flags_hypercache
-from products.feature_flags.backend.local_evaluation import (
- flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
-)
+from products.feature_flags.backend.local_evaluation import flag_definitions_hypercache
from products.feature_flags.backend.tasks import (
clear_team_definitions_cache,
clear_team_evaluation_cache,
@@ -33,23 +30,17 @@ MAX_TEAMS_PER_MUTATION = 50
EVALUATION = "evaluation"
DEFINITIONS = "definitions"
-DEFINITIONS_NO_COHORTS = "definitions_no_cohorts"
-# What rebuild/clear act on. "definitions" already rebuilds/clears both definitions-cache
-# variants together (see update_flag_caches / clear_flag_definition_caches), so there is no
-# separate mutation target for the no-cohorts variant.
CACHE_CHOICES = [EVALUATION, DEFINITIONS]
# The readable caches, enumerated once here rather than hardcoded in list/entry.
_READABLE_HYPERCACHES = {
EVALUATION: flags_hypercache,
DEFINITIONS: flag_definitions_hypercache,
- DEFINITIONS_NO_COHORTS: flag_definitions_without_cohorts_hypercache,
}
-# What status/entry can read. Unlike mutation, status/entry read each definitions-cache
-# variant independently, so the no-cohorts variant is separately observable here.
-READABLE_CACHE_CHOICES = list(_READABLE_HYPERCACHES)
+# Reading and mutating currently share the same choice set.
+READABLE_CACHE_CHOICES = CACHE_CHOICES
class _RepeatedOrCommaSeparatedListField(serializers.ListField):
@@ -99,15 +90,7 @@ class StaffCacheEntryStatusSerializer(serializers.Serializer):
class StaffCacheTeamStatusSerializer(serializers.Serializer):
team_id = serializers.IntegerField(help_text="Team id.")
evaluation = StaffCacheEntryStatusSerializer(help_text="Status of the /flags evaluation cache.")
- definitions = StaffCacheEntryStatusSerializer(
- help_text="Status of the /flags/definitions local-eval cache (with-cohorts variant)."
- )
- definitions_no_cohorts = StaffCacheEntryStatusSerializer(
- help_text=(
- "Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort "
- "filters transformed to properties for simple SDK clients)."
- )
- )
+ definitions = StaffCacheEntryStatusSerializer(help_text="Status of the /flags/definitions local-eval cache.")
@extend_schema_serializer(many=False)
@@ -144,9 +127,8 @@ class StaffCacheEntryQuerySerializer(serializers.Serializer):
cache = serializers.ChoiceField(
choices=READABLE_CACHE_CHOICES,
help_text=(
- "Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the "
- "/flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' "
- "(the without-cohorts variant served to simple SDK clients)."
+ "Which cache to fetch: 'evaluation' (the /flags cache) or 'definitions' "
+ "(the /flags/definitions local-eval cache)."
),
)
@@ -225,10 +207,8 @@ class FeatureFlagsStaffCacheViewSet(viewsets.ViewSet):
"""
Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
- Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- or clears both definitions-cache variants together). Status/entry can read a third, narrower
- target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- individually readable even though they're only mutated as a pair.
+ Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ (the /flags/definitions local-eval cache), independently readable and mutable.
Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
when a flag changes) rather than re-implementing cache-write logic. Registered on the root
@@ -260,7 +240,6 @@ class FeatureFlagsStaffCacheViewSet(viewsets.ViewSet):
"team_id": team.id,
"evaluation": _entry_status(batches[EVALUATION][team.id]),
"definitions": _entry_status(batches[DEFINITIONS][team.id]),
- "definitions_no_cohorts": _entry_status(batches[DEFINITIONS_NO_COHORTS][team.id]),
}
for team in teams
]
diff --git a/products/feature_flags/backend/canary.py b/products/feature_flags/backend/canary.py
index 272e1bc6f97e..b3f7e19bb09f 100644
--- a/products/feature_flags/backend/canary.py
+++ b/products/feature_flags/backend/canary.py
@@ -65,7 +65,7 @@ def run_local_eval_canary(registry: CollectorRegistry | None) -> None:
return
try:
- payload = _get_flags_response_for_local_evaluation(team, include_cohorts=True)
+ payload = _get_flags_response_for_local_evaluation(team)
except Exception as e:
present_gauge.set(0)
failure_counter.inc()
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 043416b3f715..7b6d1e739727 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -1,14 +1,10 @@
"""
Flag Definitions HyperCache for SDK local evaluation.
-This module provides HyperCaches that store feature flag definitions for SDKs to use
+This module provides a HyperCache that stores feature flag definitions for SDKs to use
in local evaluation. Unlike the flags_cache.py which provides raw flag data for the
-Rust feature-flags service, this provides rich data including cohort definitions and
-group type mappings.
-
-Two cache variants are provided:
-- flag_definitions_hypercache: Includes full cohort definitions for smart clients
-- flag_definitions_without_cohorts_hypercache: Cohort filters transformed to properties for simple clients
+Rust feature-flags service, this provides rich data including full cohort definitions
+and group type mappings.
Cache Key Pattern:
- Uses team_id as the key (ID-based cache)
@@ -63,9 +59,8 @@ from products.surveys.backend.models import Survey
logger = structlog.get_logger(__name__)
-# Sorted set keys for tracking cache expirations
+# Sorted set key for tracking cache expirations
FLAG_DEFINITIONS_CACHE_EXPIRY_SORTED_SET = "flag_definitions_cache_expiry"
-FLAG_DEFINITIONS_NO_COHORTS_CACHE_EXPIRY_SORTED_SET = "flag_definitions_no_cohorts_cache_expiry"
# Metric to track flags dropped during batch processing due to errors
FLAG_PROCESSING_ERROR_COUNTER = Counter(
@@ -385,33 +380,14 @@ DATABASE_FOR_LOCAL_EVALUATION = (
flag_definitions_hypercache = HyperCache(
namespace="feature_flags",
value="flags_with_cohorts.json",
- load_fn=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key), include_cohorts=True),
+ load_fn=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key)),
cache_ttl=settings.FLAGS_CACHE_TTL,
cache_miss_ttl=settings.FLAGS_CACHE_MISS_TTL,
- batch_load_fn=lambda teams: _get_flags_response_for_local_evaluation_batch(teams, include_cohorts=True),
+ batch_load_fn=lambda teams: _get_flags_response_for_local_evaluation_batch(teams),
enable_etag=True,
expiry_sorted_set_key=FLAG_DEFINITIONS_CACHE_EXPIRY_SORTED_SET,
)
-flag_definitions_without_cohorts_hypercache = HyperCache(
- namespace="feature_flags",
- value="flags_without_cohorts.json",
- load_fn=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key), include_cohorts=False),
- cache_ttl=settings.FLAGS_CACHE_TTL,
- cache_miss_ttl=settings.FLAGS_CACHE_MISS_TTL,
- batch_load_fn=lambda teams: _get_flags_response_for_local_evaluation_batch(teams, include_cohorts=False),
- enable_etag=True,
- expiry_sorted_set_key=FLAG_DEFINITIONS_NO_COHORTS_CACHE_EXPIRY_SORTED_SET,
-)
-
-
-def get_flags_response_for_local_evaluation(team: Team, include_cohorts: bool) -> dict | None:
- return (
- flag_definitions_hypercache.get_from_cache(team)
- if include_cohorts
- else flag_definitions_without_cohorts_hypercache.get_from_cache(team)
- )
-
def _resolve_team(team: Team | int) -> Team | None:
"""Resolve a Team object or ID to a Team, returning None if not found."""
@@ -428,26 +404,20 @@ def update_flag_definitions_cache(team: Team | int, ttl: int | None = None) -> b
"""
Update the flag definitions cache for a team.
- Updates both cache variants (with and without cohorts). Delegates to
- HyperCache.update_cache() which handles error logging and sync metrics.
+ Delegates to HyperCache.update_cache() which handles error logging and sync metrics.
Args:
team: Team object or team ID
ttl: Optional custom TTL in seconds (defaults to FLAGS_CACHE_TTL)
Returns:
- True if both cache updates succeeded, False otherwise
+ True if the cache update succeeded, False otherwise
"""
resolved_team = _resolve_team(team)
if resolved_team is None:
return False
- success = True
- for hypercache in [flag_definitions_hypercache, flag_definitions_without_cohorts_hypercache]:
- if not hypercache.update_cache(resolved_team, ttl=ttl):
- success = False
-
- return success
+ return flag_definitions_hypercache.update_cache(resolved_team, ttl=ttl)
# Throttle window for capturing skipped rebuilds, shared across processes via the
@@ -500,32 +470,22 @@ def _skip_write_if_group_mapping_emptied(key: KeyType, payload: dict[str, Any])
def update_flag_caches(team: Team):
- """Update both flag cache variants."""
+ """Update the flag definitions cache."""
logger.info("Syncing feature_flags cache for team", team_id=team.id)
start_time = time.time()
success = False
- size_with_cohorts: int | None = None
- size_without_cohorts: int | None = None
+ size: int | None = None
try:
- with_cohorts = _get_flags_response_for_local_evaluation(team, include_cohorts=True)
+ payload = _get_flags_response_for_local_evaluation(team)
- # Both variants share the same mapping, so one check gates both writes.
- if _skip_write_if_group_mapping_emptied(team, with_cohorts):
+ if _skip_write_if_group_mapping_emptied(team, payload):
return
- # Build both payloads before persisting either, so a failure on the second
- # fetch (e.g. the persons DB drops in this window) skips both writes and the
- # two variants can't drift out of sync.
- without_cohorts = _get_flags_response_for_local_evaluation(team, include_cohorts=False)
-
# Signal-driven rebuilds skip the write when the payload is unchanged: most
# saves that trigger this (notably the nightly cohort recalculation) don't alter
# flag definitions, so the ETag is identical and a rewrite would only add load.
- size_with_cohorts = flag_definitions_hypercache.set_cache_value(team, with_cohorts, skip_if_unchanged=True)
- size_without_cohorts = flag_definitions_without_cohorts_hypercache.set_cache_value(
- team, without_cohorts, skip_if_unchanged=True
- )
+ size = flag_definitions_hypercache.set_cache_value(team, payload, skip_if_unchanged=True)
success = True
except GroupTypesUnavailable as e:
@@ -547,8 +507,7 @@ def update_flag_caches(team: Team):
emit_cache_sync_metrics(
result, "feature_flags", "flags_local_eval.json", duration=duration, increment_counter=False
)
- emit_cache_sync_metrics(result, "feature_flags", "flags_with_cohorts.json", size=size_with_cohorts)
- emit_cache_sync_metrics(result, "feature_flags", "flags_without_cohorts.json", size=size_without_cohorts)
+ emit_cache_sync_metrics(result, "feature_flags", "flags_with_cohorts.json", size=size)
def clear_flag_definition_caches(team: Team | int, kinds: list[str] | None = None):
@@ -559,18 +518,15 @@ def clear_flag_definition_caches(team: Team | int, kinds: list[str] | None = Non
Expiry tracking cleanup is handled by HyperCache.clear_cache() internally.
"""
flag_definitions_hypercache.clear_cache(team, kinds=kinds)
- flag_definitions_without_cohorts_hypercache.clear_cache(team, kinds=kinds)
-def _get_flags_response_for_local_evaluation(team: Team, include_cohorts: bool) -> dict[str, Any]:
+def _get_flags_response_for_local_evaluation(team: Team) -> dict[str, Any]:
"""Build the local-evaluation response for a single team."""
- results = _get_flags_response_for_local_evaluation_batch([team], include_cohorts)
+ results = _get_flags_response_for_local_evaluation_batch([team])
return results.get(team.id, {"flags": [], "group_type_mapping": {}, "cohorts": {}})
-def _get_flags_response_for_local_evaluation_batch(
- teams: list[Team], include_cohorts: bool
-) -> dict[int, dict[str, Any]]:
+def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[int, dict[str, Any]]:
"""
Build local-evaluation responses for multiple teams using bulk data loading.
@@ -692,33 +648,21 @@ def _get_flags_response_for_local_evaluation_batch(
seen_cohorts_cache=seen_cohorts_cache,
)
- if not include_cohorts and len(cohort_ids) == 1:
- feature_flag.filters = {
- **filters,
- "groups": feature_flag.transform_cohort_filters_for_easy_evaluation(
- using_database=DATABASE_FOR_LOCAL_EVALUATION,
- seen_cohorts_cache=seen_cohorts_cache,
- ),
- }
- else:
- feature_flag.filters = filters
-
flags_data.append(EvaluationFeatureFlagSerializer(feature_flag, context={}).data)
- if include_cohorts:
- for cohort_id in cohort_ids:
- str_id = str(cohort_id)
- if str_id not in cohorts:
- cohort = project_cohorts.get(cohort_id)
- if cohort is not None and not cohort.is_static:
- try:
- cohorts[str_id] = cohort.properties.to_dict()
- except Exception:
- logger.error(
- "Error processing cohort properties",
- extra={"cohort_id": cohort_id},
- exc_info=True,
- )
+ for cohort_id in cohort_ids:
+ str_id = str(cohort_id)
+ if str_id not in cohorts:
+ cohort = project_cohorts.get(cohort_id)
+ if cohort is not None and not cohort.is_static:
+ try:
+ cohorts[str_id] = cohort.properties.to_dict()
+ except Exception:
+ logger.error(
+ "Error processing cohort properties",
+ extra={"cohort_id": cohort_id},
+ exc_info=True,
+ )
flag_id_to_key[str(feature_flag.id)] = feature_flag.key
@@ -730,7 +674,7 @@ def _get_flags_response_for_local_evaluation_batch(
response_data: dict[str, Any] = {
"flags": flags_data,
"group_type_mapping": gtm_by_project.get(team.project_id, {}),
- "cohorts": cohorts if include_cohorts else {},
+ "cohorts": cohorts,
}
results[tid] = _apply_flag_dependency_transformation(response_data, flag_id_to_key)
@@ -747,11 +691,7 @@ def _get_flags_response_for_local_evaluation_batch(
return results
-# Per-variant update functions for management configs. Each updates only its own
-# cache variant so that warm_caches doesn't do double work when iterating configs.
-
-
-def _update_flag_definitions_with_cohorts(team: Team | int, ttl: int | None = None) -> bool:
+def _update_flag_definitions(team: Team | int, ttl: int | None = None) -> bool:
resolved_team = _resolve_team(team)
if resolved_team is None:
return False
@@ -760,25 +700,12 @@ def _update_flag_definitions_with_cohorts(team: Team | int, ttl: int | None = No
)
-def _update_flag_definitions_without_cohorts(team: Team | int, ttl: int | None = None) -> bool:
- resolved_team = _resolve_team(team)
- if resolved_team is None:
- return False
- return flag_definitions_without_cohorts_hypercache.update_cache(
- resolved_team, ttl=ttl, should_skip_write=_skip_write_if_group_mapping_emptied
- )
-
-
-# HyperCache management configs for warming/verification.
-# Two separate configs, one for each cache variant.
-# Both share the same team-scoping queryset from flags_cache, giving flag
-# definitions the same ~89% team reduction that the flags cache already has.
-# Each config uses a per-variant update_fn so that callers iterating both
-# configs (e.g., warm_caches, refresh) don't double-write a variant.
-# Verification runs both configs independently to keep each variant correct.
+# HyperCache management config for warming/verification. Uses the same team-scoping
+# queryset as flags_cache, giving flag definitions the same ~89% team reduction that
+# the flags cache already has.
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
hypercache=flag_definitions_hypercache,
- update_fn=_update_flag_definitions_with_cohorts,
+ update_fn=_update_flag_definitions,
cache_name="flag_definitions",
get_teams_queryset_fn=get_teams_with_flags_queryset,
get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,
@@ -790,22 +717,11 @@ FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
should_skip_write=_skip_write_if_group_mapping_emptied,
)
-FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(
- hypercache=flag_definitions_without_cohorts_hypercache,
- update_fn=_update_flag_definitions_without_cohorts,
- cache_name="flag_definitions_no_cohorts",
- get_teams_queryset_fn=get_teams_with_flags_queryset,
- get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,
- repair_miss_during_grace_period=True,
- should_skip_write=_skip_write_if_group_mapping_emptied,
-)
-
def verify_team_flag_definitions(
team: Team,
db_batch_data: dict | None = None,
cache_batch_data: dict | None = None,
- include_cohorts: bool = True,
verbose: bool = False,
) -> dict:
"""
@@ -815,26 +731,23 @@ def verify_team_flag_definitions(
team: Team to verify
db_batch_data: Pre-loaded DB data from batch_load_fn (keyed by team.id)
cache_batch_data: Pre-loaded cache data from batch_get_from_cache (keyed by team.id)
- include_cohorts: Which cache variant to verify (True for with-cohorts, False for without)
verbose: If True, include detailed diffs
Returns:
Dict with 'status' ("match", "miss", "mismatch") and 'issue' type.
"""
- hypercache = flag_definitions_hypercache if include_cohorts else flag_definitions_without_cohorts_hypercache
-
# Get cached data - use pre-loaded batch data if available.
# The third tuple element (etag) is unused for flag-definitions verification.
if cache_batch_data and team.id in cache_batch_data:
cached_data, source, _ = cache_batch_data[team.id]
else:
- cached_data, source = hypercache.get_from_cache_with_source(team)
+ cached_data, source = flag_definitions_hypercache.get_from_cache_with_source(team)
# Get flag definitions from database
if db_batch_data and team.id in db_batch_data:
db_data = db_batch_data[team.id]
else:
- db_data = _get_flags_response_for_local_evaluation(team, include_cohorts)
+ db_data = _get_flags_response_for_local_evaluation(team)
db_flags = db_data.get("flags", []) if isinstance(db_data, dict) else []
diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.py
index 1ffe295dbeba..53fe65d4492a 100644
--- a/products/feature_flags/backend/models/feature_flag.py
+++ b/products/feature_flags/backend/models/feature_flag.py
@@ -1,7 +1,7 @@
import copy
import json
from functools import lru_cache
-from typing import TYPE_CHECKING, Any, Optional, cast
+from typing import TYPE_CHECKING, Any, Optional
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.postgres.aggregates import ArrayAgg
@@ -17,14 +17,13 @@ import structlog
from django_deprecate_fields import deprecate_field
from posthog.caching.flags_redis_cache import write_flags_to_cache
-from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER, PropertyOperatorType
+from posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER
from posthog.exceptions_capture import capture_exception
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.file_system.constants import DEFAULT_SURFACE
from posthog.models.file_system.file_system_mixin import FileSystemSyncMixin
from posthog.models.file_system.file_system_representation import FileSystemRepresentation
from posthog.models.property import GroupTypeIndex
-from posthog.models.property.property import Property, PropertyGroup
from posthog.models.signals import mutable_receiver
from posthog.models.utils import RootTeamManager, RootTeamMixin
@@ -355,146 +354,6 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
def get_filters(self) -> dict:
return self.filters
- def transform_cohort_filters_for_easy_evaluation(
- self,
- using_database: str = "default",
- seen_cohorts_cache: Optional[dict[int, CohortOrEmpty]] = None,
- ):
- """
- Expands cohort filters into person property filters when possible.
- This allows for easy local flag evaluation.
- """
- # Expansion depends on number of conditions on the flag.
- # If flag has only the cohort condition, we get more freedom to maneuver in the cohort expansion.
- # If flag has multiple conditions, we can only expand the cohort condition if it's a single property group.
- # Also support only a single cohort expansion. i.e. a flag with multiple cohort conditions will not be expanded.
- # Few more edge cases are possible here, where expansion is possible, but it doesn't seem
- # worth it trying to catch all of these.
-
- if seen_cohorts_cache is None:
- seen_cohorts_cache = {}
-
- if len(self.get_cohort_ids(using_database=using_database, seen_cohorts_cache=seen_cohorts_cache)) != 1:
- return self.conditions
-
- cohort_group_rollout = None
- cohort: CohortOrEmpty = None
-
- parsed_conditions = []
- for condition in self.conditions:
- if condition.get("variant"):
- # variant overrides are not supported for cohort expansion.
- return self.conditions
-
- cohort_condition = False
- props = condition.get("properties", [])
- cohort_group_rollout = condition.get("rollout_percentage")
- for prop in props:
- if prop.get("type") == "cohort":
- cohort_condition = True
- cohort_id = int(prop.get("value"))
- if cohort_id:
- if len(props) > 1:
- # We cannot expand this cohort condition if it's not the only property in its group.
- return self.conditions
- try:
- if cohort_id in seen_cohorts_cache:
- cohort = seen_cohorts_cache[cohort_id]
- if not cohort:
- return self.conditions
- else:
- cohort = Cohort.objects.db_manager(using_database).get(
- pk=cohort_id,
- team__project_id=self.team.project_id,
- deleted=False,
- )
- seen_cohorts_cache[cohort_id] = cohort
- except Cohort.DoesNotExist:
- seen_cohorts_cache[cohort_id] = ""
- return self.conditions
- if not cohort_condition:
- # flag group without a cohort filter, let it be as is.
- parsed_conditions.append(condition)
-
- if not cohort or len(cohort.properties.flat) == 0:
- return self.conditions
-
- if not all(property.type == "person" for property in cohort.properties.flat):
- # Cohorts containing non-person property types (e.g. behavioral, person_metadata)
- # are deliberately not inlined into flag groups. They flow to SDKs as cohort
- # references; modern SDKs raise InconclusiveMatchError on unknown property types
- # and fall back to /flags/, where the Rust matcher handles them.
- #
- # Note: do NOT route person_metadata through the legacy posthog/queries/base.py
- # paths (`property_to_Q` / `match_property`). Those don't recognize the type;
- # `match_property` in particular dispatches purely on `key` and would silently
- # produce a wrong-but-not-erroring result.
- return self.conditions
-
- if any(property.negation for property in cohort.properties.flat):
- # Local evaluation doesn't support negation.
- return self.conditions
-
- # all person properties, so now if we can express the cohort as feature flag groups, we'll be golden.
-
- # If there's only one effective property group, we can always express this as feature flag groups.
- # A single ff group, if cohort properties are AND'ed together.
- # Multiple ff groups, if cohort properties are OR'ed together.
- from posthog.models.property.util import clear_excess_levels
-
- target_properties = clear_excess_levels(cohort.properties)
-
- if isinstance(target_properties, Property):
- # cohort was effectively a single property.
- parsed_conditions.append(
- {
- "properties": [target_properties.to_dict()],
- "rollout_percentage": cohort_group_rollout,
- }
- )
-
- elif isinstance(target_properties.values[0], Property):
- # Property Group of properties
- if target_properties.type == PropertyOperatorType.AND:
- parsed_conditions.append(
- {
- "properties": [prop.to_dict() for prop in target_properties.values],
- "rollout_percentage": cohort_group_rollout,
- }
- )
- else:
- # cohort OR requires multiple ff group
- for prop in target_properties.values:
- parsed_conditions.append(
- {
- "properties": [prop.to_dict()],
- "rollout_percentage": cohort_group_rollout,
- }
- )
- else:
- # If there's nested property groups, we need to express that as OR of ANDs.
- # Being a bit dumb here, and not trying to apply De Morgan's law to coerce AND of ORs into OR of ANDs.
- if target_properties.type == PropertyOperatorType.AND:
- return self.conditions
-
- for prop_group in cast(list[PropertyGroup], target_properties.values):
- if (
- len(prop_group.values) == 0
- or not isinstance(prop_group.values[0], Property)
- or (prop_group.type == PropertyOperatorType.OR and len(prop_group.values) > 1)
- ):
- # too nested or invalid, bail out
- return self.conditions
-
- parsed_conditions.append(
- {
- "properties": [prop.to_dict() for prop in prop_group.values],
- "rollout_percentage": cohort_group_rollout,
- }
- )
-
- return parsed_conditions
-
def get_cohort_ids(
self,
using_database: str = "default",
diff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.py
index 3e909f8b2bd4..c76bc4027d5e 100644
--- a/products/feature_flags/backend/rebuild_queue.py
+++ b/products/feature_flags/backend/rebuild_queue.py
@@ -13,9 +13,8 @@ Throttling keeps a permanently-failing team from being rebuilt on a loop:
- a consecutive-failure circuit breaker stops attempts entirely for
``CIRCUIT_OPEN_SECONDS`` once a team fails ``CIRCUIT_OPEN_THRESHOLD`` times.
-Both cache variants (with and without cohorts) are rebuilt, so a with-cohorts miss
-heals the without-cohorts entry too. The drain exists for the mass-eviction backlog,
-so it loads the whole batch in one DB round (like the verifier) rather than per team.
+The drain exists for the mass-eviction backlog, so it loads the whole batch in one
+DB round (like the verifier) rather than per team.
"""
import time
@@ -31,7 +30,6 @@ from posthog.redis import get_client
from products.feature_flags.backend.local_evaluation import (
_skip_write_if_group_mapping_emptied,
flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
)
logger = structlog.get_logger(__name__)
@@ -168,8 +166,8 @@ def _emit_queue_gauges(redis: redis_lib.Redis, now: float) -> None:
def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, bool]:
"""Rebuild every eligible team from a single batched DB load, then record each
- outcome. Mirrors the verifier: one batch_load_fn per variant, then set_cache_value
- per team (no per-team load_fn), which is the point of draining in one pass.
+ outcome. Mirrors the verifier: one batch_load_fn, then set_cache_value per team
+ (no per-team load_fn), which is the point of draining in one pass.
A SoftTimeLimitExceeded propagates so the task winds down cleanly (the interrupted
teams stay missing and are re-enqueued by their next miss). Any other load error
@@ -179,18 +177,16 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
if not team_ids:
return {}
- # Both flag_definitions caches are always constructed with a batch_load_fn; bind it
+ # flag_definitions_hypercache is always constructed with a batch_load_fn; bind it
# to narrow the Optional type and fail loudly if that invariant ever breaks.
- with_cohorts_load = flag_definitions_hypercache.batch_load_fn
- without_cohorts_load = flag_definitions_without_cohorts_hypercache.batch_load_fn
- if with_cohorts_load is None or without_cohorts_load is None:
- raise RuntimeError("flag_definitions hypercaches must be configured with a batch_load_fn")
+ batch_load = flag_definitions_hypercache.batch_load_fn
+ if batch_load is None:
+ raise RuntimeError("flag_definitions_hypercache must be configured with a batch_load_fn")
try:
teams = list(Team.objects.filter(id__in=team_ids))
teams_by_id = {team.id: team for team in teams}
- with_cohorts = with_cohorts_load(teams)
- without_cohorts = without_cohorts_load(teams)
+ payloads = batch_load(teams)
except SoftTimeLimitExceeded:
raise
except Exception:
@@ -203,9 +199,9 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
if team is None:
results[team_id] = _record_result(redis, team_id, ok=False)
continue
- payload = with_cohorts[team_id]
+ payload = payloads[team_id]
if _skip_write_if_group_mapping_emptied(team, payload):
- # personhog lag would cache an emptied group_type_mapping; skip both writes
+ # personhog lag would cache an emptied group_type_mapping; skip the write
# without counting a failure (that would wrongly advance the circuit breaker).
# Release the cooldown so the team retries on the next drain once the mapping
# is available, rather than staying missing for the full cooldown window.
@@ -213,7 +209,6 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
continue
try:
flag_definitions_hypercache.set_cache_value(team, payload)
- flag_definitions_without_cohorts_hypercache.set_cache_value(team, without_cohorts[team_id])
ok = True
except SoftTimeLimitExceeded:
raise
diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.py
index 8a294c87464e..0a5d93024c0d 100644
--- a/products/feature_flags/backend/tasks.py
+++ b/products/feature_flags/backend/tasks.py
@@ -24,7 +24,6 @@ from products.feature_flags.backend.flags_cache import (
)
from products.feature_flags.backend.local_evaluation import (
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
clear_flag_definition_caches,
update_flag_caches,
)
@@ -328,9 +327,8 @@ def compute_feature_flag_metrics(self: PushGatewayTask) -> None:
@shared_task(bind=True, base=PushGatewayTask, ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)
def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> None:
"""
- Periodic task to refresh flag definitions caches before they expire.
+ Periodic task to refresh the flag definitions cache before entries expire.
- Refreshes both with-cohorts and without-cohorts cache variants.
Runs hourly and refreshes caches with TTL < 24 hours to prevent cache misses.
Note: Most cache updates happen via Django signals when flags change.
@@ -357,44 +355,20 @@ def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> No
limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
)
- total_successful = 0
- total_failed = 0
-
- # Refresh both cache variants
- for config, variant_name in [
- (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG, "with-cohorts"),
- (FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG, "without-cohorts"),
- ]:
- try:
- successful, failed = refresh_expiring_caches(
- config=config,
- ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,
- limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
- )
- total_successful += successful
- total_failed += failed
- logger.info(
- "Completed flag definitions cache refresh for variant",
- variant=variant_name,
- successful_refreshes=successful,
- failed_refreshes=failed,
- )
- except Exception as e:
- logger.exception(
- "Failed to refresh flag definitions cache variant",
- variant=variant_name,
- error=str(e),
- )
- total_failed += 1
-
- successful_gauge.set(total_successful)
- failed_gauge.set(total_failed)
+ successful, failed = refresh_expiring_caches(
+ config=FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
+ ttl_threshold_hours=settings.FLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS,
+ limit=settings.FLAGS_CACHE_REFRESH_LIMIT,
+ )
+
+ successful_gauge.set(successful)
+ failed_gauge.set(failed)
duration = time.time() - start_time
logger.info(
"Completed flag definitions cache refresh",
- total_successful_refreshes=total_successful,
- total_failed_refreshes=total_failed,
+ successful_refreshes=successful,
+ failed_refreshes=failed,
duration_seconds=duration,
)
@@ -402,11 +376,10 @@ def refresh_expiring_flag_definitions_cache_entries(self: PushGatewayTask) -> No
@shared_task(bind=True, base=PushGatewayTask, ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)
def cleanup_stale_flag_definitions_expiry_tracking_task(self: PushGatewayTask) -> None:
"""
- Periodic task to clean up stale entries in the flag definitions cache expiry tracking sorted sets.
+ Periodic task to clean up stale entries in the flag definitions cache expiry tracking sorted set.
Removes entries for teams that no longer exist in the database.
Runs daily to prevent sorted set bloat from deleted teams.
- Cleans up both with-cohorts and without-cohorts sorted sets.
"""
from posthog.storage.cache_expiry_manager import cleanup_stale_expiry_tracking
@@ -417,30 +390,10 @@ def cleanup_stale_flag_definitions_expiry_tracking_task(self: PushGatewayTask) -
registry=self.metrics_registry,
)
- total_removed = 0
- configs = [
- (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG, "with-cohorts"),
- (FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG, "without-cohorts"),
- ]
-
- for config, variant_name in configs:
- try:
- removed_count = cleanup_stale_expiry_tracking(config)
- total_removed += removed_count
- logger.info(
- "Completed flag definitions expiry tracking cleanup for variant",
- variant=variant_name,
- removed_count=removed_count,
- )
- except Exception as e:
- logger.exception(
- "Failed to cleanup flag definitions expiry tracking for variant",
- variant=variant_name,
- error=str(e),
- )
-
- entries_cleaned_gauge.set(total_removed)
- logger.info("Completed flag definitions expiry tracking cleanup", total_removed_count=total_removed)
+ removed_count = cleanup_stale_expiry_tracking(FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG)
+
+ entries_cleaned_gauge.set(removed_count)
+ logger.info("Completed flag definitions expiry tracking cleanup", removed_count=removed_count)
@shared_task(
diff --git a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
index 0d7c4c78ea24..7df803fade2b 100644
--- a/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
+++ b/products/feature_flags/backend/test/test_flag_definitions_cache_tasks.py
@@ -12,35 +12,33 @@ from products.feature_flags.backend.tasks import (
class TestRefreshExpiringFlagDefinitionsCacheEntries(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")
- def test_refreshes_both_cache_variants(self, mock_refresh: MagicMock) -> None:
+ def test_refreshes_cache(self, mock_refresh: MagicMock) -> None:
mock_refresh.return_value = (5, 0)
refresh_expiring_flag_definitions_cache_entries()
- assert mock_refresh.call_count == 2
+ mock_refresh.assert_called_once()
@patch("posthog.storage.cache_expiry_manager.refresh_expiring_caches")
- def test_continues_to_next_variant_on_error(self, mock_refresh: MagicMock) -> None:
- mock_refresh.side_effect = [Exception("variant 1 failed"), (3, 0)]
+ def test_propagates_error(self, mock_refresh: MagicMock) -> None:
+ mock_refresh.side_effect = Exception("refresh failed")
- refresh_expiring_flag_definitions_cache_entries()
-
- assert mock_refresh.call_count == 2
+ with self.assertRaises(Exception):
+ refresh_expiring_flag_definitions_cache_entries()
class TestCleanupStaleFlagDefinitionsExpiryTrackingTask(PushGatewayTaskTestMixin, TestCase):
@patch("posthog.storage.cache_expiry_manager.cleanup_stale_expiry_tracking")
- def test_cleans_up_both_cache_variants(self, mock_cleanup: MagicMock) -> None:
+ def test_cleans_up_cache(self, mock_cleanup: MagicMock) -> None:
mock_cleanup.return_value = 3
cleanup_stale_flag_definitions_expiry_tracking_task()
- assert mock_cleanup.call_count == 2
+ mock_cleanup.assert_called_once()
@patch("posthog.storage.cache_expiry_manager.cleanup_stale_expiry_tracking")
- def test_continues_to_next_variant_on_error(self, mock_cleanup: MagicMock) -> None:
- mock_cleanup.side_effect = [Exception("variant 1 failed"), 2]
-
- cleanup_stale_flag_definitions_expiry_tracking_task()
+ def test_propagates_error(self, mock_cleanup: MagicMock) -> None:
+ mock_cleanup.side_effect = Exception("cleanup failed")
- assert mock_cleanup.call_count == 2
+ with self.assertRaises(Exception):
+ cleanup_stale_flag_definitions_expiry_tracking_task()
diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.py
index 13331aad75c7..467730a88dde 100644
--- a/products/feature_flags/backend/test/test_local_evaluation.py
+++ b/products/feature_flags/backend/test/test_local_evaluation.py
@@ -21,16 +21,12 @@ from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flags
from products.feature_flags.backend.local_evaluation import (
FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,
- FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG,
_extract_cohort_ids_from_filters,
_get_flags_response_for_local_evaluation,
_get_flags_response_for_local_evaluation_batch,
- _update_flag_definitions_with_cohorts,
- _update_flag_definitions_without_cohorts,
+ _update_flag_definitions,
clear_flag_definition_caches,
flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
- get_flags_response_for_local_evaluation,
update_flag_caches,
update_flag_definitions_cache,
verify_team_flag_definitions,
@@ -179,20 +175,13 @@ class TestLocalEvaluationCache(BaseTest):
assert response.get("group_type_mapping", {}) == {"0": "organization"}
assert len(response.get("cohorts", {})) == 2
- def test_generates_correct_local_evaluation_response_with_cohorts(self):
- response = get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ def test_generates_correct_local_evaluation_response(self):
+ response = flag_definitions_hypercache.get_from_cache(self.team)
assert response
assert len(response.get("flags", [])) == 2
assert response.get("group_type_mapping", {}) == {"0": "organization"}
assert len(response.get("cohorts", {})) == 2
- def test_generates_correct_local_evaluation_response_without_cohorts(self):
- response = get_flags_response_for_local_evaluation(self.team, include_cohorts=False)
- assert response
- assert len(response.get("flags", [])) == 2
- assert response.get("group_type_mapping", {}) == {"0": "organization"}
- assert len(response.get("cohorts", {})) == 0
-
def test_get_flags_cache_hot(self):
update_flag_caches(self.team)
response, source = flag_definitions_hypercache.get_from_cache_with_source(self.team)
@@ -250,19 +239,17 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):
return (response or {}).get("group_type_mapping", {})
@patch("posthog.storage.hypercache.HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER")
- def test_unchanged_rebuild_skips_both_variant_writes(self, mock_skip_counter):
+ def test_unchanged_rebuild_skips_write(self, mock_skip_counter):
# The signal path opts into skip_if_unchanged=True. A second rebuild with no flag
- # changes must skip the rewrite for both variants; dropping the kwarg silently
- # reverts the optimization and only this assertion would catch it.
+ # changes must skip the rewrite; dropping the kwarg silently reverts the
+ # optimization and only this assertion would catch it.
update_flag_caches(self.team)
mock_skip_counter.labels.assert_not_called()
update_flag_caches(self.team)
- assert mock_skip_counter.labels.call_count == 2
- mock_skip_counter.labels.assert_any_call(namespace="feature_flags", value="flags_with_cohorts.json")
- mock_skip_counter.labels.assert_any_call(namespace="feature_flags", value="flags_without_cohorts.json")
- assert mock_skip_counter.labels.return_value.inc.call_count == 2
+ mock_skip_counter.labels.assert_called_once_with(namespace="feature_flags", value="flags_with_cohorts.json")
+ assert mock_skip_counter.labels.return_value.inc.call_count == 1
@patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_REBUILD_SKIPPED_COUNTER")
def test_skips_write_on_group_types_unavailable(self, mock_skipped_counter):
@@ -313,7 +300,7 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):
return_value={self.team.project_id: []},
):
with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:
- assert _update_flag_definitions_with_cohorts(self.team) is False
+ assert _update_flag_definitions(self.team) is False
mock_set.assert_not_called()
mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")
@@ -596,7 +583,7 @@ class TestSurveyFlagExclusion(BaseTest):
**{flag_field: survey_flag},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert regular_flag.key in flag_keys
@@ -617,7 +604,7 @@ class TestSurveyFlagExclusion(BaseTest):
linked_flag=user_linked_flag,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert user_linked_flag.key in flag_keys
@@ -637,12 +624,12 @@ class TestSurveyFlagExclusion(BaseTest):
targeting_flag=survey_flag,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
assert survey_flag.key not in [f["key"] for f in response["flags"]]
survey.delete()
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
assert survey_flag.key in [f["key"] for f in response["flags"]]
def test_survey_flags_excluded_from_api_response(self):
@@ -666,7 +653,7 @@ class TestSurveyFlagExclusion(BaseTest):
internal_targeting_flag=survey_flag,
)
- response = get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
assert response is not None
flag_keys = [f["key"] for f in response["flags"]]
@@ -739,7 +726,7 @@ class TestSurveyFlagExclusion(BaseTest):
targeting_flag=survey_flag,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
assert survey_flag.key not in [f["key"] for f in response["flags"]]
# Archive the survey (not delete)
@@ -747,7 +734,7 @@ class TestSurveyFlagExclusion(BaseTest):
survey.save()
# Flag should still be excluded since the survey still exists
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
assert survey_flag.key not in [f["key"] for f in response["flags"]]
def test_survey_flag_reassignment_updates_exclusions(self):
@@ -770,7 +757,7 @@ class TestSurveyFlagExclusion(BaseTest):
targeting_flag=flag_a,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert flag_a.key not in flag_keys
assert flag_b.key in flag_keys
@@ -778,7 +765,7 @@ class TestSurveyFlagExclusion(BaseTest):
survey.targeting_flag = flag_b
survey.save()
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert flag_a.key in flag_keys
assert flag_b.key not in flag_keys
@@ -799,7 +786,7 @@ class TestSurveyFlagExclusion(BaseTest):
targeting_flag=shared_flag,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert shared_flag.key not in flag_keys
@@ -831,7 +818,7 @@ class TestSurveyFlagExclusion(BaseTest):
internal_response_sampling_flag=flag_b,
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flag_keys = [f["key"] for f in response["flags"]]
assert flag_a.key not in flag_keys
@@ -895,7 +882,7 @@ class TestLocalEvaluationBatch(BaseTest):
return team
def test_batch_empty_team_list(self):
- result = _get_flags_response_for_local_evaluation_batch([], True)
+ result = _get_flags_response_for_local_evaluation_batch([])
assert result == {}
@parameterized.expand(
@@ -931,7 +918,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
flag_keys = {f["key"] for f in results[team.id]["flags"]}
if should_include:
@@ -954,7 +941,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"rollout_percentage": 50}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team_a, team_b], True)
+ results = _get_flags_response_for_local_evaluation_batch([team_a, team_b])
assert team_a.id in results
assert team_b.id in results
@@ -975,7 +962,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"rollout_percentage": 100}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team_with_flags, team_without_flags], True)
+ results = _get_flags_response_for_local_evaluation_batch([team_with_flags, team_without_flags])
assert len(results[team_with_flags.id]["flags"]) == 1
assert results[team_without_flags.id]["flags"] == []
@@ -989,7 +976,7 @@ class TestLocalEvaluationBatch(BaseTest):
team=team, project_id=team.project_id, group_type="company", group_type_index=0
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
assert results[team.id]["flags"] == []
assert results[team.id]["group_type_mapping"] == {"0": "company"}
@@ -1030,7 +1017,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort_b.pk}]}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team_a, team_b], True)
+ results = _get_flags_response_for_local_evaluation_batch([team_a, team_b])
cohort_ids_a = set(results[team_a.id]["cohorts"].keys())
cohort_ids_b = set(results[team_b.id]["cohorts"].keys())
@@ -1072,7 +1059,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": referenced_cohort.pk}]}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
assert str(referenced_cohort.pk) in results[team.id]["cohorts"]
assert str(unreferenced_cohort.pk) not in results[team.id]["cohorts"]
@@ -1112,7 +1099,7 @@ class TestLocalEvaluationBatch(BaseTest):
},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
assert str(dynamic_cohort.pk) in results[team.id]["cohorts"]
assert str(static_cohort.pk) not in results[team.id]["cohorts"]
@@ -1150,7 +1137,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": parent_cohort.pk}]}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
assert str(parent_cohort.pk) in results[team.id]["cohorts"]
assert str(leaf_cohort.pk) in results[team.id]["cohorts"]
@@ -1196,7 +1183,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": grandparent.pk}]}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
cohort_ids = set(results[team.id]["cohorts"].keys())
assert str(grandparent.pk) in cohort_ids
@@ -1243,7 +1230,7 @@ class TestLocalEvaluationBatch(BaseTest):
filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort_a.pk}]}]},
)
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
cohort_ids = set(results[team.id]["cohorts"].keys())
assert str(cohort_a.pk) in cohort_ids
@@ -1274,7 +1261,7 @@ class TestLocalEvaluationBatch(BaseTest):
# Expected queries: survey flag IDs and flags (with evaluation
# tags via ArrayAgg). Group type mappings are read from
# personhog, not SQL. No cohort query should be issued.
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
assert results[team.id]["cohorts"] == {}
assert len(results[team.id]["flags"]) == 1
@@ -1304,7 +1291,7 @@ class TestLocalEvaluationBatch(BaseTest):
cohort.deleted = True
cohort.save()
- results = _get_flags_response_for_local_evaluation_batch([team], True)
+ results = _get_flags_response_for_local_evaluation_batch([team])
flag_keys = [f["key"] for f in results[team.id]["flags"]]
assert "flag-ref-deleted-cohort" in flag_keys
@@ -1324,32 +1311,9 @@ class TestFlagDefinitionsCache(BaseTest):
Changing the key format would orphan existing cached data,
causing a cold cache on deploy.
"""
- with_cohorts_key = flag_definitions_hypercache.get_cache_key(self.team)
- without_cohorts_key = flag_definitions_without_cohorts_hypercache.get_cache_key(self.team)
+ key = flag_definitions_hypercache.get_cache_key(self.team)
- assert with_cohorts_key == f"cache/teams/{self.team.id}/feature_flags/flags_with_cohorts.json"
- assert without_cohorts_key == f"cache/teams/{self.team.id}/feature_flags/flags_without_cohorts.json"
-
- def test_update_flag_definitions_cache_updates_both_variants(self):
- FeatureFlag.objects.create(
- team=self.team,
- key="test-flag",
- created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- result = update_flag_definitions_cache(self.team)
- assert result is True
-
- with_cohorts, source1 = flag_definitions_hypercache.get_from_cache_with_source(self.team)
- without_cohorts, source2 = flag_definitions_without_cohorts_hypercache.get_from_cache_with_source(self.team)
-
- assert source1 == "redis"
- assert source2 == "redis"
- assert with_cohorts is not None
- assert without_cohorts is not None
- assert len(with_cohorts["flags"]) == 1
- assert len(without_cohorts["flags"]) == 1
+ assert key == f"cache/teams/{self.team.id}/feature_flags/flags_with_cohorts.json"
def test_update_flag_definitions_cache_accepts_team_id(self):
FeatureFlag.objects.create(
@@ -1371,7 +1335,7 @@ class TestFlagDefinitionsCache(BaseTest):
result = update_flag_definitions_cache(999999)
assert result is False
- def test_clear_flag_definition_caches_clears_both_variants(self):
+ def test_clear_flag_definition_caches(self):
FeatureFlag.objects.create(
team=self.team,
key="test-flag",
@@ -1381,34 +1345,24 @@ class TestFlagDefinitionsCache(BaseTest):
update_flag_definitions_cache(self.team)
- _, source1 = flag_definitions_hypercache.get_from_cache_with_source(self.team)
- _, source2 = flag_definitions_without_cohorts_hypercache.get_from_cache_with_source(self.team)
- assert source1 == "redis"
- assert source2 == "redis"
+ _, source = flag_definitions_hypercache.get_from_cache_with_source(self.team)
+ assert source == "redis"
clear_flag_definition_caches(self.team, kinds=["redis", "s3"])
- _, source1 = flag_definitions_hypercache.get_from_cache_with_source(self.team)
- _, source2 = flag_definitions_without_cohorts_hypercache.get_from_cache_with_source(self.team)
- assert source1 == "db"
- assert source2 == "db"
+ _, source = flag_definitions_hypercache.get_from_cache_with_source(self.team)
+ assert source == "db"
- def test_hypercache_configs_are_properly_configured(self):
- config1 = FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG
- assert config1.cache_name == "flag_definitions"
- assert config1.hypercache == flag_definitions_hypercache
- assert config1.update_fn == _update_flag_definitions_with_cohorts
+ def test_hypercache_config_is_properly_configured(self):
+ config = FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG
+ assert config.cache_name == "flag_definitions"
+ assert config.hypercache == flag_definitions_hypercache
+ assert config.update_fn == _update_flag_definitions
# Grace-period skip prevents the verifier from flagging caches whose
# underlying flags were just updated and whose async rebuild is still in flight.
- assert config1.get_team_ids_to_skip_fix_fn == get_team_ids_with_recently_updated_flags
-
- config2 = FLAG_DEFINITIONS_NO_COHORTS_HYPERCACHE_MANAGEMENT_CONFIG
- assert config2.cache_name == "flag_definitions_no_cohorts"
- assert config2.hypercache == flag_definitions_without_cohorts_hypercache
- assert config2.update_fn == _update_flag_definitions_without_cohorts
- assert config2.get_team_ids_to_skip_fix_fn == get_team_ids_with_recently_updated_flags
+ assert config.get_team_ids_to_skip_fix_fn == get_team_ids_with_recently_updated_flags
- def test_update_flag_definitions_cache_returns_false_on_partial_failure(self):
+ def test_update_flag_definitions_cache_returns_false_on_failure(self):
FeatureFlag.objects.create(
team=self.team,
key="test-flag",
@@ -1421,10 +1375,6 @@ class TestFlagDefinitionsCache(BaseTest):
assert result is False
- # The second variant should still have been updated
- _, source = flag_definitions_without_cohorts_hypercache.get_from_cache_with_source(self.team)
- assert source == "redis"
-
def test_update_flag_definitions_cache_passes_custom_ttl(self):
FeatureFlag.objects.create(
team=self.team,
@@ -1433,16 +1383,10 @@ class TestFlagDefinitionsCache(BaseTest):
filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- with (
- patch.object(flag_definitions_hypercache, "update_cache", return_value=True) as mock_with,
- patch.object(
- flag_definitions_without_cohorts_hypercache, "update_cache", return_value=True
- ) as mock_without,
- ):
+ with patch.object(flag_definitions_hypercache, "update_cache", return_value=True) as mock_update:
update_flag_definitions_cache(self.team, ttl=3600)
- mock_with.assert_called_once_with(self.team, ttl=3600)
- mock_without.assert_called_once_with(self.team, ttl=3600)
+ mock_update.assert_called_once_with(self.team, ttl=3600)
@override_settings(FLAGS_REDIS_URL="redis://test")
@@ -1461,7 +1405,7 @@ class TestVerifyFlagDefinitions(BaseTest):
filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
)
- result = verify_team_flag_definitions(self.team, include_cohorts=True)
+ result = verify_team_flag_definitions(self.team)
assert result["status"] == "miss"
assert result["issue"] == "CACHE_MISS"
@@ -1476,7 +1420,7 @@ class TestVerifyFlagDefinitions(BaseTest):
update_flag_definitions_cache(self.team)
- result = verify_team_flag_definitions(self.team, include_cohorts=True)
+ result = verify_team_flag_definitions(self.team)
assert result["status"] == "match"
assert result["issue"] == ""
@@ -1494,7 +1438,7 @@ class TestVerifyFlagDefinitions(BaseTest):
flag.key = "modified-flag"
flag.save()
- result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)
+ result = verify_team_flag_definitions(self.team, verbose=True)
assert result["status"] == "mismatch"
assert result["issue"] == "DATA_MISMATCH"
@@ -1519,7 +1463,7 @@ class TestVerifyFlagDefinitions(BaseTest):
flag.filters = {"groups": [{"properties": [], "rollout_percentage": 50}]}
flag.save()
- result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)
+ result = verify_team_flag_definitions(self.team, verbose=True)
assert result["status"] == "mismatch"
assert result["issue"] == "DATA_MISMATCH"
@@ -1565,7 +1509,7 @@ class TestVerifyFlagDefinitions(BaseTest):
mutate_cached_flag(cached_data["flags"][0])
flag_definitions_hypercache.set_cache_value(self.team, cached_data)
- result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)
+ result = verify_team_flag_definitions(self.team, verbose=True)
assert result["status"] == expected_status
if expected_diff_field is not None:
@@ -1574,22 +1518,6 @@ class TestVerifyFlagDefinitions(BaseTest):
assert field_mismatch_diffs[0]["flag_key"] == "test-flag"
assert expected_diff_field in field_mismatch_diffs[0]["diff_fields"]
- def test_verify_both_variants_independently(self):
- FeatureFlag.objects.create(
- team=self.team,
- key="test-flag",
- created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- update_flag_definitions_cache(self.team)
-
- result_with = verify_team_flag_definitions(self.team, include_cohorts=True)
- result_without = verify_team_flag_definitions(self.team, include_cohorts=False)
-
- assert result_with["status"] == "match"
- assert result_without["status"] == "match"
-
def test_verify_returns_mismatch_when_cohort_changed(self):
cohort = Cohort.objects.create(
team=self.team,
@@ -1616,7 +1544,7 @@ class TestVerifyFlagDefinitions(BaseTest):
cohort.groups = [{"properties": [{"key": "email", "value": "[email protected]", "type": "person"}]}]
cohort.save()
- result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)
+ result = verify_team_flag_definitions(self.team, verbose=True)
assert result["status"] == "mismatch"
assert result["issue"] == "DATA_MISMATCH"
@@ -1648,7 +1576,7 @@ class TestVerifyFlagDefinitions(BaseTest):
mapping.group_type = "organization"
_seed_group_type_mapping_into_fake(mapping)
- result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)
+ result = verify_team_flag_definitions(self.team, verbose=True)
assert result["status"] == "mismatch"
assert result["issue"] == "DATA_MISMATCH"
@@ -1675,7 +1603,7 @@ class TestFlagDefinitionsManagementCommands(BaseTest):
super().setUp()
clear_flag_definition_caches(self.team, kinds=["redis", "s3"])
- def test_verify_command_checks_both_variants(self):
+ def test_verify_command_reports_results(self):
from io import StringIO
from django.core.management import call_command
@@ -1691,11 +1619,9 @@ class TestFlagDefinitionsManagementCommands(BaseTest):
call_command("verify_flag_definitions_cache", f"--team-ids={self.team.id}", stdout=out)
output = out.getvalue()
- assert "with cohorts" in output
- assert "without cohorts" in output
- assert output.count("Verification Results") == 2
+ assert output.count("Verification Results") == 1
- def test_warm_command_processes_both_variants_by_default(self):
+ def test_warm_command_processes_teams(self):
from io import StringIO
from django.core.management import call_command
@@ -1711,34 +1637,8 @@ class TestFlagDefinitionsManagementCommands(BaseTest):
call_command("warm_flag_definitions_cache", f"--team-ids={self.team.id}", stdout=out)
output = out.getvalue()
- assert "with cohorts" in output
- assert "without cohorts" in output
assert "Successful: 1" in output
- def test_warm_command_with_variant_flag(self):
- from io import StringIO
-
- from django.core.management import call_command
-
- FeatureFlag.objects.create(
- team=self.team,
- key="test-flag",
- created_by=self.user,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- )
-
- out = StringIO()
- call_command(
- "warm_flag_definitions_cache",
- f"--team-ids={self.team.id}",
- "--variant=with-cohorts",
- stdout=out,
- )
-
- output = out.getvalue()
- assert "with cohorts" in output
- assert "without cohorts" not in output
-
@override_settings(FLAGS_REDIS_URL=None)
class TestFlagDefinitionsCacheWithoutRedis(BaseTest):
@@ -1817,7 +1717,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
flag_c_data = self._find_flag(flags, "flag-c")
@@ -1877,7 +1777,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
}
flag_a.save()
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
self.assertEqual(len(flags), 2)
@@ -1942,7 +1842,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
flag_c_data = self._find_flag(flags, "flag-c")
@@ -1983,7 +1883,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
self_flag_data = self._find_flag(flags, "self-flag")
@@ -2026,7 +1926,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
flag_b_data = self._find_flag(flags, "flag-b")
@@ -2068,7 +1968,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
},
)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
flag_a_data = self._find_flag(flags, "flag-a")
@@ -2110,7 +2010,7 @@ class TestFlagDependencyChainTransformation(BaseTest):
)
dependent_flags.append(flag)
- response = _get_flags_response_for_local_evaluation(self.team, include_cohorts=True)
+ response = _get_flags_response_for_local_evaluation(self.team)
flags = response["flags"]
for i, _flag in enumerate(dependent_flags):
diff --git a/products/feature_flags/backend/test/test_rebuild_queue.py b/products/feature_flags/backend/test/test_rebuild_queue.py
index 6c538723d279..88084f1763f7 100644
--- a/products/feature_flags/backend/test/test_rebuild_queue.py
+++ b/products/feature_flags/backend/test/test_rebuild_queue.py
@@ -43,9 +43,7 @@ def _rebuilds(error=None, skip_write=False, load_error=None):
patch.object(rebuild_queue, "Team") as team,
patch.object(rebuild_queue, "_skip_write_if_group_mapping_emptied", return_value=skip_write),
patch.object(rebuild_queue.flag_definitions_hypercache, "batch_load_fn", new=_load),
- patch.object(rebuild_queue.flag_definitions_without_cohorts_hypercache, "batch_load_fn", new=_load),
patch.object(rebuild_queue.flag_definitions_hypercache, "set_cache_value", side_effect=error) as set_cache,
- patch.object(rebuild_queue.flag_definitions_without_cohorts_hypercache, "set_cache_value", side_effect=error),
):
team.objects.filter.side_effect = lambda id__in: [SimpleNamespace(id=int(t)) for t in id__in]
yield set_cache
diff --git a/products/feature_flags/backend/test/test_staff_cache_api.py b/products/feature_flags/backend/test/test_staff_cache_api.py
index c1c0cb6668b5..39f99b48ed42 100644
--- a/products/feature_flags/backend/test/test_staff_cache_api.py
+++ b/products/feature_flags/backend/test/test_staff_cache_api.py
@@ -13,10 +13,7 @@ from products.feature_flags.backend.api.staff_cache import (
StaffCacheStatusQuerySerializer,
)
from products.feature_flags.backend.flags_cache import flags_hypercache
-from products.feature_flags.backend.local_evaluation import (
- flag_definitions_hypercache,
- flag_definitions_without_cohorts_hypercache,
-)
+from products.feature_flags.backend.local_evaluation import flag_definitions_hypercache
from products.feature_flags.backend.models.feature_flag import FeatureFlag
REBUILD_URL = "/api/feature_flags_staff_cache/rebuild/"
@@ -141,24 +138,10 @@ class TestFeatureFlagsStaffCacheAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.json()["results"]), 1)
- def test_status_reports_the_two_definitions_variants_independently(self):
- self.addCleanup(flag_definitions_hypercache.clear_cache, self.team)
- self.addCleanup(flag_definitions_without_cohorts_hypercache.clear_cache, self.team)
-
- # Only warm the without-cohorts variant; the with-cohorts variant stays cold.
- flag_definitions_without_cohorts_hypercache.update_cache(self.team)
-
- response = self.client.get(f"/api/feature_flags_staff_cache/?team_ids={self.team.id}")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- results = response.json()["results"][0]
- self.assertEqual(results["definitions_no_cohorts"]["source"], "redis")
- self.assertEqual(results["definitions"]["source"], "miss")
-
@parameterized.expand(
[
("evaluation", flags_hypercache),
("definitions", flag_definitions_hypercache),
- ("definitions_no_cohorts", flag_definitions_without_cohorts_hypercache),
]
)
def test_entry_reads_the_hypercache_matching_the_cache_param(self, cache_kind, hypercache):
@@ -167,7 +150,6 @@ class TestFeatureFlagsStaffCacheAPI(APIBaseTest):
# regardless of how the test ends.
self.addCleanup(flags_hypercache.clear_cache, self.team)
self.addCleanup(flag_definitions_hypercache.clear_cache, self.team)
- self.addCleanup(flag_definitions_without_cohorts_hypercache.clear_cache, self.team)
FeatureFlag.objects.create(
team=self.team,
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index c3355d324de8..82a469d5cc7b 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -36,10 +36,8 @@ export interface StaffCacheTeamStatusApi {
team_id: number
/** Status of the /flags evaluation cache. */
evaluation: StaffCacheEntryStatusApi
- /** Status of the /flags/definitions local-eval cache (with-cohorts variant). */
+ /** Status of the /flags/definitions local-eval cache. */
definitions: StaffCacheEntryStatusApi
- /** Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort filters transformed to properties for simple SDK clients). */
- definitions_no_cohorts: StaffCacheEntryStatusApi
}
export interface StaffCacheStatusResponseApi {
@@ -51,9 +49,9 @@ export interface StaffCacheStatusResponseApi {
* * `evaluation` - evaluation
* * `definitions` - definitions
*/
-export type CachesEnumApi = (typeof CachesEnumApi)[keyof typeof CachesEnumApi]
+export type StaffCacheKindEnumApi = (typeof StaffCacheKindEnumApi)[keyof typeof StaffCacheKindEnumApi]
-export const CachesEnumApi = {
+export const StaffCacheKindEnumApi = {
Evaluation: 'evaluation',
Definitions: 'definitions',
} as const
@@ -65,7 +63,7 @@ export interface StaffCacheMutationApi {
*/
team_ids: number[]
/** Which logical caches to act on: 'evaluation' (the /flags cache) and/or 'definitions' (the /flags/definitions local-eval cache). Defaults to both. */
- caches?: CachesEnumApi[]
+ caches?: StaffCacheKindEnumApi[]
}
export interface StaffCacheMutationResponseApi {
@@ -81,28 +79,14 @@ export interface StaffCacheMutationResponseApi {
*/
export type StaffCacheEntryResponseApiData = { [key: string]: unknown } | null
-/**
- * * `evaluation` - evaluation
- * * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts
- */
-export type CacheEnumApi = (typeof CacheEnumApi)[keyof typeof CacheEnumApi]
-
-export const CacheEnumApi = {
- Evaluation: 'evaluation',
- Definitions: 'definitions',
- DefinitionsNoCohorts: 'definitions_no_cohorts',
-} as const
-
export interface StaffCacheEntryResponseApi {
/** Team id. */
team_id: number
/** Which cache this entry is for.
*
* * `evaluation` - evaluation
- * * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts */
- cache: CacheEnumApi
+ * * `definitions` - definitions */
+ cache: StaffCacheKindEnumApi
/** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
*
* * `redis` - redis
@@ -1591,11 +1575,10 @@ export type FeatureFlagsStaffCacheListParams = {
export type FeatureFlagsStaffCacheEntryRetrieveParams = {
/**
- * Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the /flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' (the without-cohorts variant served to simple SDK clients).
+ * Which cache to fetch: 'evaluation' (the /flags cache) or 'definitions' (the /flags/definitions local-eval cache).
*
* * `evaluation` - evaluation
* * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts
* @minLength 1
*/
cache: FeatureFlagsStaffCacheEntryRetrieveCache
@@ -1611,7 +1594,6 @@ export type FeatureFlagsStaffCacheEntryRetrieveCache =
export const FeatureFlagsStaffCacheEntryRetrieveCache = {
Evaluation: 'evaluation',
Definitions: 'definitions',
- DefinitionsNoCohorts: 'definitions_no_cohorts',
} as const
export type FeatureFlagsStaffTeamConfigListParams = {
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 4bc89eb9b70b..e66977b7f58d 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -97,10 +97,8 @@ export const getFeatureFlagsStaffCacheListUrl = (params: FeatureFlagsStaffCacheL
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
@@ -123,10 +121,8 @@ export const getFeatureFlagsStaffCacheClearCreateUrl = () => {
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
@@ -163,10 +159,8 @@ export const getFeatureFlagsStaffCacheEntryRetrieveUrl = (params: FeatureFlagsSt
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
@@ -189,10 +183,8 @@ export const getFeatureFlagsStaffCacheRebuildCreateUrl = () => {
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index 26457d2756c6..1b5c5efd81be 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -12,10 +12,8 @@ import * as zod from 'zod'
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
@@ -43,10 +41,8 @@ export const FeatureFlagsStaffCacheClearCreateBody = /* @__PURE__ */ zod.object(
/**
* Staff-only, unscoped status/entry/rebuild/clear for the HyperCache-backed flag caches.
*
- * Rebuild/clear act on two logical targets ('evaluation' and 'definitions'; the latter rebuilds
- * or clears both definitions-cache variants together). Status/entry can read a third, narrower
- * target ('definitions_no_cohorts') independently, since the two definitions-cache variants are
- * individually readable even though they're only mutated as a pair.
+ * Rebuild/clear act on two logical targets: 'evaluation' (the /flags cache) and 'definitions'
+ * (the /flags/definitions local-eval cache), independently readable and mutable.
*
* Reuses the existing cache functions and Celery tasks (the same mechanism signal handlers use
* when a flag changes) rather than re-implementing cache-write logic. Registered on the root
diff --git a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
index b68ec837cb20..8721215f14b0 100644
--- a/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
+++ b/products/feature_flags/frontend/staff/StaffCacheToolsTab.tsx
@@ -21,7 +21,7 @@ const NO_SELECTION_REASON = 'Select at least one team'
const ALL_CACHES: StaffCacheKind[] = ['evaluation', 'definitions']
-const READABLE_CACHE_KINDS: StaffReadableCacheKind[] = ['evaluation', 'definitions', 'definitions_no_cohorts']
+const READABLE_CACHE_KINDS: StaffReadableCacheKind[] = ['evaluation', 'definitions']
function CacheStatusCell({ status, onView }: { status?: StaffCacheEntryStatus; onView: () => void }): JSX.Element {
const tag = !status ? (
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
index f0280bafcc58..048ac8ea9e7d 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.test.ts
@@ -61,7 +61,6 @@ describe('featureFlagsStaffToolsLogic', () => {
team_id: 5,
evaluation: { source: 'redis', flag_count: 3 },
definitions: { source: 'redis', flag_count: 3 },
- definitions_no_cohorts: { source: 'miss', flag_count: null },
},
],
},
@@ -76,7 +75,6 @@ describe('featureFlagsStaffToolsLogic', () => {
team_id: 5,
evaluation: { source: 'redis', flag_count: 3 },
definitions: { source: 'redis', flag_count: 3 },
- definitions_no_cohorts: { source: 'miss', flag_count: null },
},
},
})
diff --git a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
index 84288bc42d0b..183550811fbd 100644
--- a/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
+++ b/products/feature_flags/frontend/staff/featureFlagsStaffToolsLogic.ts
@@ -14,9 +14,9 @@ import {
featureFlagsStaffTeamsList,
} from '../generated/api'
import type {
- CachesEnumApi,
FeatureFlagsStaffCacheEntryRetrieveCache,
StaffCacheEntryResponseApi,
+ StaffCacheKindEnumApi,
StaffCacheMutationResponseApi,
StaffCacheTeamStatusApi,
StaffTeamConfigApi,
@@ -25,17 +25,14 @@ import type {
import type { featureFlagsStaffToolsLogicType } from './featureFlagsStaffToolsLogicType'
// What rebuild/clear can act on. Mirrors the backend's CACHE_CHOICES.
-export type StaffCacheKind = CachesEnumApi
+export type StaffCacheKind = StaffCacheKindEnumApi
-// What status/entry can read. Mirrors the backend's READABLE_CACHE_CHOICES: unlike mutation,
-// the two definitions-cache variants are individually observable even though they're only
-// mutated as a pair (see the backend's staff_cache.py module docstring).
+// What status/entry can read. Mirrors the backend's READABLE_CACHE_CHOICES.
export type StaffReadableCacheKind = FeatureFlagsStaffCacheEntryRetrieveCache
export const CACHE_LABELS: Record<StaffReadableCacheKind, string> = {
evaluation: 'Flags cache',
- definitions: 'Definitions cache (cohorts)',
- definitions_no_cohorts: 'Definitions cache (no cohorts)',
+ definitions: 'Definitions cache',
}
const MIN_SEARCH_LENGTH = 2
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f084ea402e62..c0d35e1e1864 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12486,32 +12486,6 @@ export namespace Schemas {
failing_workflows?: string[];
}
- /**
- * * `evaluation` - evaluation
- * * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts
- */
- export type CacheEnum = typeof CacheEnum[keyof typeof CacheEnum];
-
-
- export const CacheEnum = {
- Evaluation: 'evaluation',
- Definitions: 'definitions',
- DefinitionsNoCohorts: 'definitions_no_cohorts',
- } as const;
-
- /**
- * * `evaluation` - evaluation
- * * `definitions` - definitions
- */
- export type CachesEnum = typeof CachesEnum[keyof typeof CachesEnum];
-
-
- export const CachesEnum = {
- Evaluation: 'evaluation',
- Definitions: 'definitions',
- } as const;
-
export interface EventsHeatMapColumnAggregationResult {
column: number;
value: number;
@@ -55924,6 +55898,18 @@ export namespace Schemas {
*/
export type StaffCacheEntryResponseData = { [key: string]: unknown } | null;
+ /**
+ * * `evaluation` - evaluation
+ * * `definitions` - definitions
+ */
+ export type StaffCacheKindEnum = typeof StaffCacheKindEnum[keyof typeof StaffCacheKindEnum];
+
+
+ export const StaffCacheKindEnum = {
+ Evaluation: 'evaluation',
+ Definitions: 'definitions',
+ } as const;
+
/**
* * `redis` - redis
* * `miss` - miss
@@ -55942,9 +55928,8 @@ export namespace Schemas {
/** Which cache this entry is for.
*
* * `evaluation` - evaluation
- * * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts */
- cache: CacheEnum;
+ * * `definitions` - definitions */
+ cache: StaffCacheKindEnum;
/** 'redis' when a warm entry is cached, or 'miss' when nothing is cached in Redis.
*
* * `redis` - redis
@@ -55977,7 +55962,7 @@ export namespace Schemas {
*/
team_ids: number[];
/** Which logical caches to act on: 'evaluation' (the /flags cache) and/or 'definitions' (the /flags/definitions local-eval cache). Defaults to both. */
- caches?: CachesEnum[];
+ caches?: StaffCacheKindEnum[];
}
export interface StaffCacheMutationResponse {
@@ -55992,10 +55977,8 @@ export namespace Schemas {
team_id: number;
/** Status of the /flags evaluation cache. */
evaluation: StaffCacheEntryStatus;
- /** Status of the /flags/definitions local-eval cache (with-cohorts variant). */
+ /** Status of the /flags/definitions local-eval cache. */
definitions: StaffCacheEntryStatus;
- /** Status of the /flags/definitions local-eval cache (without-cohorts variant, cohort filters transformed to properties for simple SDK clients). */
- definitions_no_cohorts: StaffCacheEntryStatus;
}
export interface StaffCacheStatusResponse {
@@ -65804,11 +65787,10 @@ export namespace Schemas {
export type FeatureFlagsStaffCacheEntryRetrieveParams = {
/**
- * Which cache to fetch: 'evaluation' (the /flags cache), 'definitions' (the /flags/definitions local-eval cache, with-cohorts variant), or 'definitions_no_cohorts' (the without-cohorts variant served to simple SDK clients).
+ * Which cache to fetch: 'evaluation' (the /flags cache) or 'definitions' (the /flags/definitions local-eval cache).
*
* * `evaluation` - evaluation
* * `definitions` - definitions
- * * `definitions_no_cohorts` - definitions_no_cohorts
* @minLength 1
*/
cache: FeatureFlagsStaffCacheEntryRetrieveCache;
@@ -65824,7 +65806,6 @@ export namespace Schemas {
export const FeatureFlagsStaffCacheEntryRetrieveCache = {
Evaluation: 'evaluation',
Definitions: 'definitions',
- DefinitionsNoCohorts: 'definitions_no_cohorts',
} as const;
export type FeatureFlagsStaffTeamConfigListParams = {