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.

fix(cohorts): avoid enqueuing flags cache rebuilds per cohort (#90904)

Matheus Batista32e0679b7101
diff --git a/posthog/admin/admins/resave_cohorts_admin.py b/posthog/admin/admins/resave_cohorts_admin.py
index 03e7ade9105b..6eb80686873b 100644
--- a/posthog/admin/admins/resave_cohorts_admin.py
+++ b/posthog/admin/admins/resave_cohorts_admin.py
@@ -4,7 +4,7 @@ from django.core.exceptions import PermissionDenied
from django.core.management import call_command
from django.shortcuts import redirect, render
-from posthog.management.commands.resave_cohorts import UnclassifiedCohortsError
+from posthog.management.commands.resave_cohorts import IncompleteResaveError
class ResaveCohortsForm(forms.Form):
@@ -44,9 +44,9 @@ def resave_cohorts_view(request):
request,
f"Cohort re-save started ({mode}) for {scope} with batch_size={form.cleaned_data['batch_size']}.",
)
- except UnclassifiedCohortsError as e:
+ except IncompleteResaveError as e:
# The run finished and persisted its saves, so this is not a failure to start.
- messages.warning(request, f"Cohort re-save finished, but found unclassified cohorts: {str(e)}")
+ messages.warning(request, f"Cohort re-save finished with problems: {str(e)}")
except Exception as e:
messages.error(request, f"Failed to start cohort re-save: {str(e)}")
diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.py
index b59ddea84a57..e990206e6650 100644
--- a/posthog/management/commands/resave_cohorts.py
+++ b/posthog/management/commands/resave_cohorts.py
@@ -1,5 +1,10 @@
from __future__ import annotations
+import signal
+import threading
+from collections.abc import Iterator
+from contextlib import AbstractContextManager, contextmanager, nullcontext
+from types import FrameType
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
@@ -13,25 +18,91 @@ from posthog.models.team.team import Team
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, CohortType
from products.cohorts.backend.models.util import get_all_cohort_dependencies, sort_cohorts_topologically
from products.cohorts.backend.realtime_teams import is_realtime_cohort_team, realtime_allowlist_matches_every_team
+from products.feature_flags.backend.flags_cache import coalesced_cohort_flags_cache_rebuilds
logger = structlog.get_logger(__name__)
-# How many unclassified cohort ids to name in the failure output before summarizing the rest.
-UNCLASSIFIED_REPORT_LIMIT = 20
+# How many ids to name in a failure message before summarizing the rest.
+ID_REPORT_LIMIT = 20
# The cohort types the realtime membership gate routes, so a null condition_type changes how they
# evaluate. See `uses_realtime_membership` in rust/feature-flags/src/cohorts/cohort_models.rs.
REALTIME_GATED_COHORT_TYPES = (CohortType.REALTIME, CohortType.BEHAVIORAL)
+# The catchable signals that end a run without unwinding it. SIGTERM reaches the command when it
+# is the container's main process or is killed by hand. A run in a toolbox `kubectl exec` shell
+# never gets SIGTERM, because a pod stop signals only the main process, but a hangup of that
+# shell's terminal ends it with SIGHUP.
+UNWIND_SIGNALS = (signal.SIGTERM, signal.SIGHUP)
-class UnclassifiedCohortsError(CommandError):
- """The run finished and persisted its saves, but left cohorts the realtime gate misreads.
+
+@contextmanager
+def termination_unwinds() -> Iterator[bool]:
+ """Raise on SIGTERM and SIGHUP instead of dying in place, when they are this command's to take.
+
+ Either signal otherwise kills the process between a team's cohort saves committing and its
+ coalesced cache rebuild being enqueued, and nothing sweeps that back: the service-cache
+ verifier does not compare cohorts, and a rerun finds nothing left to change. Unwinding lets
+ the coalescing block dispatch the teams it has already recorded. `KeyboardInterrupt` because
+ the per-cohort `except Exception` must not swallow it. SIGKILL cannot be caught, so an
+ expired toolbox claim or an OOM kill still loses the rebuild of the team in progress.
+
+ Yields whether the unwind is in place. The admin view runs the command inside a web worker,
+ which owns its own shutdown, so the caller must not coalesce rebuilds it cannot flush there.
+ """
+ if threading.current_thread() is not threading.main_thread():
+ # Only the main thread may install a handler, and a server that hands sync views to a
+ # threadpool runs the admin view off it.
+ yield False
+ return
+
+ dispositions = {signum: signal.getsignal(signum) for signum in UNWIND_SIGNALS}
+ if any(disposition not in (signal.SIG_DFL, signal.SIG_IGN) for disposition in dispositions.values()):
+ # Something else owns one of them, a web worker serving the admin view for one. Taking it
+ # over would replace that shutdown path, and a handler installed outside Python reads
+ # back as `None`, which cannot be restored afterwards.
+ yield False
+ return
+
+ def raise_interrupt(signum: int, frame: FrameType | None) -> None:
+ raise KeyboardInterrupt(f"received {signal.Signals(signum).name}")
+
+ # An ignored signal cannot end the run, so it stays ignored. `nohup` ignores SIGHUP, and a
+ # run started under it must survive the hangup it asked to survive.
+ taken = [signum for signum, disposition in dispositions.items() if disposition is signal.SIG_DFL]
+ for signum in taken:
+ signal.signal(signum, raise_interrupt)
+ try:
+ yield True
+ finally:
+ for signum in taken:
+ signal.signal(signum, signal.SIG_DFL)
+
+
+def _summarize_ids(ids: list[int]) -> str:
+ shown = ", ".join(str(value) for value in ids[:ID_REPORT_LIMIT])
+ remainder = len(ids) - ID_REPORT_LIMIT
+ if remainder > 0:
+ shown += f", and {remainder} more"
+ return shown
+
+
+class IncompleteResaveError(CommandError):
+ """The run finished and persisted its saves, but left state a rerun does not repair.
Distinct from the other `CommandError`s the command raises, which all reject the invocation
before any work happens, so a caller can tell a run that never started from one that did.
"""
+class UnclassifiedCohortsError(IncompleteResaveError):
+ """The run left cohorts the realtime gate misreads."""
+
+
+class StaleFlagsCacheError(IncompleteResaveError):
+ """The run left teams whose flags cache rebuild never reached the broker."""
+
+
@frozen
class CohortResaveStats:
total: int
@@ -39,6 +110,9 @@ class CohortResaveStats:
errors: int
validation_errors: int
prospective_realtime: int
+ # The team's cohorts were resaved but its cache rebuild never reached the broker, so the
+ # team keeps a stale flags cache.
+ rebuild_dispatch_failed: bool
@frozen
@@ -115,47 +189,54 @@ class Command(BaseCommand):
global_errors = 0
global_validation_errors = 0
global_prospective_realtime = 0
+ stale_cache_team_ids: list[int] = []
teams_processed = 0
total_teams = teams_qs.count()
# Process each team separately
- for team in teams_qs:
- teams_processed += 1
- logger.info(
- "cohort_resave_team_started",
- team_id=team.id,
- team_progress=f"{teams_processed}/{total_teams}",
- )
- self.stdout.write(f"Processing team {team.id} ({teams_processed}/{total_teams})")
-
- stats = self._process_team_cohorts(team, batch_size, dry_run)
-
- # Accumulate stats
- global_total += stats.total
- global_changed += stats.changed
- global_errors += stats.errors
- global_validation_errors += stats.validation_errors
- global_prospective_realtime += stats.prospective_realtime
-
- # Log team completion
- if stats.total > 0:
+ with termination_unwinds() as coalesce_rebuilds:
+ for team in teams_qs:
+ teams_processed += 1
logger.info(
- "cohort_resave_team_completed",
+ "cohort_resave_team_started",
team_id=team.id,
- total_cohorts=stats.total,
- changed_cohorts=stats.changed,
- realtime_cohorts=stats.prospective_realtime,
- error_count=stats.errors,
- validation_error_count=stats.validation_errors,
- dry_run=dry_run,
+ team_progress=f"{teams_processed}/{total_teams}",
)
- msg = f" Team {team.id}: {stats.total} cohorts, {stats.changed} changed, {stats.prospective_realtime} realtime"
- if stats.errors > 0:
- msg += f", {stats.errors} errors"
- if stats.validation_errors > 0:
- msg += f", {stats.validation_errors} validation errors"
- style = self.style.WARNING if (stats.errors > 0 or stats.validation_errors > 0) else self.style.SUCCESS
- self.stdout.write(style(msg))
+ self.stdout.write(f"Processing team {team.id} ({teams_processed}/{total_teams})")
+
+ stats = self._process_team_cohorts(team, batch_size, dry_run, coalesce_rebuilds)
+
+ # Accumulate stats
+ global_total += stats.total
+ global_changed += stats.changed
+ global_errors += stats.errors
+ global_validation_errors += stats.validation_errors
+ global_prospective_realtime += stats.prospective_realtime
+ if stats.rebuild_dispatch_failed:
+ stale_cache_team_ids.append(team.id)
+
+ # Log team completion
+ if stats.total > 0:
+ logger.info(
+ "cohort_resave_team_completed",
+ team_id=team.id,
+ total_cohorts=stats.total,
+ changed_cohorts=stats.changed,
+ realtime_cohorts=stats.prospective_realtime,
+ error_count=stats.errors,
+ validation_error_count=stats.validation_errors,
+ rebuild_dispatch_failed=stats.rebuild_dispatch_failed,
+ dry_run=dry_run,
+ )
+ msg = f" Team {team.id}: {stats.total} cohorts, {stats.changed} changed, {stats.prospective_realtime} realtime"
+ if stats.errors > 0:
+ msg += f", {stats.errors} errors"
+ if stats.validation_errors > 0:
+ msg += f", {stats.validation_errors} validation errors"
+ if stats.rebuild_dispatch_failed:
+ msg += ", flags cache rebuild not enqueued"
+ unhealthy = stats.errors > 0 or stats.validation_errors > 0 or stats.rebuild_dispatch_failed
+ self.stdout.write((self.style.WARNING if unhealthy else self.style.SUCCESS)(msg))
# A dry run persists nothing, so there is no post-run state to verify. `None` keeps that
# apart from an empty list, which would claim the check ran and found nothing.
@@ -173,12 +254,13 @@ class Command(BaseCommand):
realtime_cohorts=global_prospective_realtime,
error_count=global_errors,
validation_error_count=global_validation_errors,
+ stale_cache_team_count=len(stale_cache_team_ids),
change_percentage=change_pct,
realtime_percentage=realtime_pct,
unclassified_count=None if unclassified is None else len(unclassified),
)
self.stdout.write("")
- healthy = global_errors == 0 and global_validation_errors == 0 and not unclassified
+ healthy = global_errors == 0 and global_validation_errors == 0 and not stale_cache_team_ids and not unclassified
final_style = self.style.SUCCESS if healthy else self.style.WARNING
unclassified_label = "unclassified not checked" if unclassified is None else f"{len(unclassified)} unclassified"
self.stdout.write(
@@ -188,6 +270,7 @@ class Command(BaseCommand):
f"{global_changed} changed ({change_pct}%), "
f"{global_prospective_realtime} realtime ({realtime_pct}%), "
f"{global_errors} errors, {global_validation_errors} validation errors, "
+ f"{len(stale_cache_team_ids)} teams with a stale flags cache, "
f"{unclassified_label}"
)
)
@@ -195,6 +278,9 @@ class Command(BaseCommand):
if unclassified and selection.explicit:
self._fail_on_unclassified(unclassified)
+ if stale_cache_team_ids:
+ self._fail_on_stale_cache(stale_cache_team_ids)
+
def _unclassified_cohort_ids(self, selection: TeamSelection) -> list[int]:
"""Cohorts the realtime gate routes that still have a null `condition_type`, read back from
the database.
@@ -215,16 +301,24 @@ class Command(BaseCommand):
The realtime membership gate reads a null `condition_type` as "no behavioral condition", so
an unclassified cohort silently evaluates as if it had none.
"""
- shown = ", ".join(str(cohort_id) for cohort_id in cohort_ids[:UNCLASSIFIED_REPORT_LIMIT])
- remainder = len(cohort_ids) - UNCLASSIFIED_REPORT_LIMIT
- if remainder > 0:
- shown += f", and {remainder} more"
raise UnclassifiedCohortsError(
- f"{len(cohort_ids)} cohorts still have a null condition_type: {shown}. "
+ f"{len(cohort_ids)} cohorts still have a null condition_type: {_summarize_ids(cohort_ids)}. "
"Fix their filters and rerun before treating the team as classified. "
"Deleted cohorts count too, because restoring one returns it to the realtime gate unclassified."
)
+ def _fail_on_stale_cache(self, team_ids: list[int]) -> None:
+ """Refuse to report success while a team still serves the cohort rules the run replaced.
+
+ The rebuild never reached the broker, and nothing sweeps that back: the service-cache
+ verifier does not compare cohorts, and a rerun finds nothing left to change.
+ """
+ raise StaleFlagsCacheError(
+ f"{len(team_ids)} teams kept a stale flags cache: {_summarize_ids(team_ids)}. "
+ "A rerun changes nothing, so enqueue update_team_flags_cache and "
+ "update_team_service_flags_cache for them."
+ )
+
def _existing_team_ids(self, requested: list[int]) -> tuple[int, ...]:
"""Refuse team ids that do not exist, so a typo cannot pass as a clean run over no cohorts."""
found = set(Team.objects.filter(id__in=requested).values_list("id", flat=True))
@@ -274,7 +368,9 @@ class Command(BaseCommand):
return TeamSelection(team_ids=None, label="all teams", explicit=False)
- def _process_team_cohorts(self, team: Team, batch_size: int, dry_run: bool) -> CohortResaveStats:
+ def _process_team_cohorts(
+ self, team: Team, batch_size: int, dry_run: bool, coalesce_rebuilds: bool
+ ) -> CohortResaveStats:
"""Process all cohorts for a single team."""
all_cohorts = self._load_team_cohorts(team, batch_size)
seen_cohorts_cache: dict[int, CohortOrEmpty] = {c.id: c for c in all_cohorts}
@@ -289,32 +385,41 @@ class Command(BaseCommand):
validation_errors = 0
prospective_realtime = 0
- for cohort_id in sorted_cohort_ids:
- cohort = seen_cohorts_cache.get(cohort_id)
- if not cohort:
- continue
-
- total += 1
- try:
- outcome = self._recompute_cohort(cohort, team, seen_cohorts_cache, cohort_dependencies)
- if outcome.validation_failed:
- validation_errors += 1
- # Counted before the save, so a realtime cohort whose save raises still reports as one.
- if outcome.prospective_realtime:
- prospective_realtime += 1
- if outcome.changed:
- if not dry_run:
- cohort.save(update_fields=["filters", "cohort_type", "condition_type"])
- changed += 1
- except Exception as err:
- errors += 1
- logger.error(
- "cohort_resave_error",
- cohort_id=cohort.id,
- team_id=team.id,
- error=str(err),
- exc_info=True,
- )
+ # Each save fires two whole-team flags-cache rebuilds, so the block coalesces them into one
+ # dispatch per team. Scoping it to one team means that team reads a stale cache only while
+ # its own cohorts are being resaved, rather than until the whole run finishes. Without the
+ # signal unwind nothing flushes the block on shutdown, so an unprotected run keeps the
+ # per-save enqueues instead.
+ rebuilds: AbstractContextManager[set[int]] = (
+ coalesced_cohort_flags_cache_rebuilds() if coalesce_rebuilds else nullcontext(set())
+ )
+ with rebuilds as stale_cache_teams:
+ for cohort_id in sorted_cohort_ids:
+ cohort = seen_cohorts_cache.get(cohort_id)
+ if not cohort:
+ continue
+
+ total += 1
+ try:
+ outcome = self._recompute_cohort(cohort, team, seen_cohorts_cache, cohort_dependencies)
+ if outcome.validation_failed:
+ validation_errors += 1
+ # Counted before the save, so a realtime cohort whose save raises still reports as one.
+ if outcome.prospective_realtime:
+ prospective_realtime += 1
+ if outcome.changed:
+ if not dry_run:
+ cohort.save(update_fields=["filters", "cohort_type", "condition_type"])
+ changed += 1
+ except Exception as err:
+ errors += 1
+ logger.error(
+ "cohort_resave_error",
+ cohort_id=cohort.id,
+ team_id=team.id,
+ error=str(err),
+ exc_info=True,
+ )
return CohortResaveStats(
total=total,
@@ -322,6 +427,7 @@ class Command(BaseCommand):
errors=errors,
validation_errors=validation_errors,
prospective_realtime=prospective_realtime,
+ rebuild_dispatch_failed=bool(stale_cache_teams),
)
def _load_team_cohorts(self, team: Team, batch_size: int) -> list[Cohort]:
diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.py
index ddc85f99d380..434c6e5fd455 100644
--- a/posthog/management/commands/test/test_resave_cohorts.py
+++ b/posthog/management/commands/test/test_resave_cohorts.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import signal
+import threading
from io import StringIO
from typing import Any
@@ -9,10 +11,11 @@ from unittest.mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from posthog.management.commands.resave_cohorts import UNWIND_SIGNALS, StaleFlagsCacheError, termination_unwinds
from posthog.models.team.team import Team
from posthog.test.db_context_capturing import capture_db_queries
@@ -21,6 +24,12 @@ from products.cohorts.backend.models.cohort import Cohort
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
+def _default_unwind_signals(test: SimpleTestCase) -> None:
+ for signum in UNWIND_SIGNALS:
+ previous = signal.signal(signum, signal.SIG_DFL)
+ test.addCleanup(signal.signal, signum, previous if previous is not None else signal.SIG_DFL)
+
+
def _has_condition_hash(obj: Any) -> bool:
if isinstance(obj, dict):
if "conditionHash" in obj:
@@ -539,6 +548,117 @@ class TestResaveCohortsCommandTwoTeams(BaseTest):
assert cohorts_b[4].cohort_type == "realtime"
+@override_settings(FLAGS_REDIS_URL="redis://test")
+@patch("django.db.transaction.on_commit", lambda fn: fn())
+@patch("products.feature_flags.backend.tasks.update_team_flags_cache")
+@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")
+class TestResaveCohortsCommandFlagsCacheRebuilds(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The command coalesces only when no other handler owns SIGTERM or SIGHUP, which is the CLI
+ # case. Pin the dispositions so the test runner's own do not decide which path runs.
+ _default_unwind_signals(self)
+
+ def _seed_two_teams(self) -> tuple[Team, Team]:
+ team_a: Team = self.team
+ team_b: Team = Team.objects.create(organization=self.organization)
+ for team in (team_a, team_b):
+ for index in range(3):
+ Cohort.objects.create(team=team, name=f"rt_{team.id}_{index}", filters=_make_realtime_filters())
+ return team_a, team_b
+
+ def test_rebuilds_each_changed_team_once(self, mock_service, mock_definitions) -> None:
+ team_a, team_b = self._seed_two_teams()
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ call_command("resave_cohorts", team_id=[team_a.id, team_b.id])
+
+ for mock_task in (mock_service, mock_definitions):
+ dispatched = [call.args[0] for call in mock_task.delay.call_args_list]
+ assert dispatched.count(team_a.id) == 1
+ assert dispatched.count(team_b.id) == 1
+
+ def test_a_run_that_cannot_unwind_keeps_the_per_save_rebuilds(self, mock_service, mock_definitions) -> None:
+ team_a, _ = self._seed_two_teams()
+ # Stands in for the admin path, where a web worker owns SIGTERM and nothing would flush
+ # the coalescing block on shutdown.
+ signal.signal(signal.SIGTERM, lambda signum, frame: None)
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ call_command("resave_cohorts", team_id=[team_a.id])
+
+ for mock_task in (mock_service, mock_definitions):
+ dispatched = [call.args[0] for call in mock_task.delay.call_args_list]
+ assert dispatched.count(team_a.id) > 1
+
+ def test_the_teams_left_with_a_stale_cache_fail_the_run(self, mock_service, mock_definitions) -> None:
+ team_a, team_b = self._seed_two_teams()
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+ mock_service.delay.side_effect = RuntimeError("broker unreachable")
+
+ out = StringIO()
+ with pytest.raises(StaleFlagsCacheError) as error:
+ call_command("resave_cohorts", team_id=[team_a.id, team_b.id], stdout=out)
+
+ assert "2 teams with a stale flags cache" in out.getvalue()
+ assert str(team_a.id) in str(error.value)
+
+
+def _other_handler(signum: int, frame: object) -> None: ...
+
+
+class TestTerminationUnwinds(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ _default_unwind_signals(self)
+
+ @parameterized.expand([("sigterm", signal.SIGTERM), ("sighup", signal.SIGHUP)])
+ def test_the_signal_raises_inside_the_block_and_is_restored_after(self, _name: str, signum: int) -> None:
+ with termination_unwinds() as unwinds:
+ assert unwinds
+ handler = signal.getsignal(signum)
+ assert callable(handler)
+ with pytest.raises(KeyboardInterrupt):
+ handler(signum, None)
+
+ assert signal.getsignal(signum) is signal.SIG_DFL
+
+ def test_off_the_main_thread_it_reports_no_unwind(self) -> None:
+ unwinds: list[bool] = []
+
+ def run() -> None:
+ with termination_unwinds() as unwind:
+ unwinds.append(unwind)
+
+ thread = threading.Thread(target=run)
+ thread.start()
+ thread.join()
+
+ assert unwinds == [False]
+ assert all(signal.getsignal(signum) is signal.SIG_DFL for signum in UNWIND_SIGNALS)
+
+ @parameterized.expand(
+ [
+ ("sigterm_claimed", signal.SIGTERM, _other_handler, False),
+ ("sighup_claimed", signal.SIGHUP, _other_handler, False),
+ ("sighup_ignored_by_nohup", signal.SIGHUP, signal.SIG_IGN, True),
+ ]
+ )
+ def test_a_disposition_someone_else_set_is_left_in_place(
+ self, _name: str, signum: int, disposition: Any, expected_unwinds: bool
+ ) -> None:
+ signal.signal(signum, disposition)
+
+ with termination_unwinds() as unwinds:
+ assert unwinds is expected_unwinds
+ assert signal.getsignal(signum) is disposition
+
+ assert signal.getsignal(signum) is disposition
+
+
class TestResaveCohortsCommandTeamSelection(BaseTest):
def test_team_id_processes_only_the_listed_teams(self):
team_a: Team = self.team
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 63aa6516245b..7bc3c405f69c 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -28,8 +28,11 @@ Manual operations:
import sys
from collections import defaultdict, deque
-from collections.abc import Mapping
+from collections.abc import Iterator, Mapping
+from contextlib import contextmanager
+from contextvars import ContextVar
from datetime import UTC, datetime, timedelta
+from functools import partial
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
@@ -1533,6 +1536,77 @@ def enqueue_evaluation_cache_invalidation(team_id: int) -> None:
_enqueue_invalidation(team_id)
+# The two caches a cohort save rebuilds: the local-evaluation definitions cache and the
+# flags-service cache.
+FlagsCacheName = Literal["definitions", "service"]
+
+_deferred_rebuild_teams: ContextVar[dict[int, set[FlagsCacheName]] | None] = ContextVar(
+ "deferred_flags_cache_rebuild_teams", default=None
+)
+
+
+def defer_flags_cache_rebuild(team_id: int, cache: FlagsCacheName) -> bool:
+ """Record the team's rebuild of `cache` if a coalescing block is active.
+
+ Returns True when the rebuild was recorded, which means the caller must not enqueue its
+ own.
+ """
+ teams = _deferred_rebuild_teams.get()
+ if teams is None:
+ return False
+ teams.setdefault(team_id, set()).add(cache)
+ return True
+
+
+def _dispatch_flags_cache_rebuilds(team_id: int, caches: set[FlagsCacheName], failed_teams: set[int]) -> None:
+ """Enqueue the recorded rebuilds for one team, recording the team when a publish fails."""
+ from products.feature_flags.backend.tasks import update_team_flags_cache, update_team_service_flags_cache
+
+ tasks = {"definitions": update_team_flags_cache, "service": update_team_service_flags_cache}
+
+ failed = False
+ for cache in sorted(caches):
+ # One try per task, so a broker failure on one does not drop the other.
+ try:
+ tasks[cache].delay(team_id)
+ except Exception:
+ # The saves already committed, so raising would abort the rest of a fleet-wide run.
+ # The caller reports the team instead.
+ failed = True
+ logger.error("coalesced_flags_cache_dispatch_failed", team_id=team_id, cache=cache, exc_info=True)
+
+ if failed:
+ failed_teams.add(team_id)
+ else:
+ logger.info("coalesced_flags_cache_dispatch", team_id=team_id)
+
+
+@contextmanager
+def coalesced_cohort_flags_cache_rebuilds() -> Iterator[set[int]]:
+ """Coalesce the cohort-save flags-cache rebuilds inside the block to one dispatch per team.
+
+ A bulk cohort resave otherwise enqueues two whole-team rebuilds per cohort, where two per
+ team are sufficient. Only the two cohort receivers coalesce; flag and experiment saves
+ inside the block still enqueue their own rebuild. Each receiver records the cache it was
+ about to rebuild, so the dispatch enqueues exactly what the receivers wanted.
+
+ Yields the set of team ids whose dispatch failed, so the caller can report them. In
+ autocommit it is filled by the time the block exits; under an open transaction the dispatch
+ waits for the commit and the set fills later.
+ """
+ failed_teams: set[int] = set()
+ token = _deferred_rebuild_teams.set({})
+ try:
+ yield failed_teams
+ finally:
+ teams = _deferred_rebuild_teams.get() or {}
+ # Reset before dispatching: eager Celery runs the rebuild inline, and a cohort save
+ # inside it would otherwise record into a dict nobody reads again.
+ _deferred_rebuild_teams.reset(token)
+ for team_id, caches in sorted(teams.items()):
+ transaction.on_commit(partial(_dispatch_flags_cache_rebuilds, team_id, caches, failed_teams))
+
+
@receiver(post_save, sender=FeatureFlag)
@receiver(post_delete, sender=FeatureFlag)
def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):
@@ -1636,6 +1710,9 @@ def cohort_changed_flags_cache(sender, instance: "Cohort", **kwargs):
if update_fields is not None and frozenset(update_fields) <= _COHORT_RECALCULATION_FIELDS:
return
+ if defer_flags_cache_rebuild(instance.team_id, "service"):
+ return
+
from products.feature_flags.backend.tasks import update_team_service_flags_cache
# Intentionally bypasses _enqueue_invalidation: cohort changes do not
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 35efad8c1cb8..da6fb761fd48 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -59,6 +59,7 @@ from products.feature_flags.backend.facade.config import ConfigFormatError
from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_ids
from products.feature_flags.backend.flags_cache import (
_compare_flag_fields,
+ defer_flags_cache_rebuild,
get_team_ids_with_recently_updated_flags,
get_teams_with_flags_queryset,
)
@@ -1006,6 +1007,9 @@ def cohort_changed(sender, instance: "Cohort", **kwargs):
if is_cohort_recalculation_only_save(kwargs):
return
+ if defer_flags_cache_rebuild(instance.team_id, "definitions"):
+ return
+
from products.feature_flags.backend.tasks import update_team_flags_cache
transaction.on_commit(lambda: update_team_flags_cache.delay(instance.team_id))
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index 5623bd19b87e..17ecf0d7138a 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -52,6 +52,7 @@ from products.feature_flags.backend.flags_cache import (
_serialize_cohort,
_strip_null_values,
clear_flags_cache,
+ coalesced_cohort_flags_cache_rebuilds,
flags_hypercache,
get_flags_from_cache,
get_team_ids_with_recently_updated_flags,
@@ -4634,6 +4635,149 @@ class TestCohortChangedFlagsCacheSignal(BaseTest):
mock_task.delay.assert_not_called()
+@override_settings(FLAGS_REDIS_URL="redis://test")
+@patch("django.db.transaction.on_commit", lambda fn: fn())
+@patch("products.feature_flags.backend.tasks.update_team_flags_cache")
+@patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")
+class TestCoalescedFlagsCacheRebuilds(BaseTest):
+ def _save_definition(self, cohort: Cohort) -> None:
+ cohort.filters = {"properties": {"type": "AND", "values": []}}
+ cohort.save(update_fields=["filters"])
+
+ def test_saves_inside_the_block_dispatch_once_on_exit(self, mock_service, mock_definitions):
+ cohort_one = Cohort.objects.create(team=self.team, name="one")
+ cohort_two = Cohort.objects.create(team=self.team, name="two")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ with coalesced_cohort_flags_cache_rebuilds() as stale_cache_teams:
+ self._save_definition(cohort_one)
+ self._save_definition(cohort_two)
+ mock_service.delay.assert_not_called()
+ mock_definitions.delay.assert_not_called()
+
+ mock_service.delay.assert_called_once_with(self.team.id)
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+ assert stale_cache_teams == set()
+
+ def test_dispatches_once_per_team(self, mock_service, mock_definitions):
+ other_team = Team.objects.create(organization=self.organization)
+ cohort_here = Cohort.objects.create(team=self.team, name="here")
+ cohort_there = Cohort.objects.create(team=other_team, name="there")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ with coalesced_cohort_flags_cache_rebuilds():
+ self._save_definition(cohort_here)
+ self._save_definition(cohort_there)
+ self._save_definition(cohort_here)
+
+ assert sorted(call.args[0] for call in mock_service.delay.call_args_list) == sorted(
+ [self.team.id, other_team.id]
+ )
+ assert sorted(call.args[0] for call in mock_definitions.delay.call_args_list) == sorted(
+ [self.team.id, other_team.id]
+ )
+
+ def test_dispatches_recorded_teams_when_the_block_raises(self, mock_service, mock_definitions):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ with pytest.raises(RuntimeError):
+ with coalesced_cohort_flags_cache_rebuilds():
+ self._save_definition(cohort)
+ raise RuntimeError("interrupted")
+
+ mock_service.delay.assert_called_once_with(self.team.id)
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+
+ @override_settings(FLAGS_REDIS_URL=None)
+ def test_skips_the_service_cache_when_no_flags_redis_url(self, mock_service, mock_definitions):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ with coalesced_cohort_flags_cache_rebuilds():
+ self._save_definition(cohort)
+ mock_definitions.delay.assert_not_called()
+
+ mock_service.delay.assert_not_called()
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+
+ def test_receivers_enqueue_again_after_the_block_exits(self, mock_service, mock_definitions):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+
+ with coalesced_cohort_flags_cache_rebuilds():
+ self._save_definition(cohort)
+
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+ self._save_definition(cohort)
+
+ mock_service.delay.assert_called_once_with(self.team.id)
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+
+ def test_a_cohort_saved_while_dispatching_still_enqueues(self, mock_service, mock_definitions):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+ saved_during_dispatch = Cohort.objects.create(team=self.team, name="two")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ def save_another_cohort(_team_id):
+ # Clear the side effect first: the nested save dispatches inline, which would
+ # otherwise call back into here forever.
+ mock_definitions.delay.side_effect = None
+ self._save_definition(saved_during_dispatch)
+
+ # Stands in for eager Celery, which runs the rebuild inline.
+ mock_definitions.delay.side_effect = save_another_cohort
+
+ with coalesced_cohort_flags_cache_rebuilds():
+ self._save_definition(cohort)
+
+ assert mock_definitions.delay.call_count == 2
+
+ @parameterized.expand([("definitions",), ("service",)])
+ def test_a_failed_publish_is_reported_and_does_not_drop_the_other_rebuild(
+ self, mock_service, mock_definitions, failing
+ ):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+ failing_mock, surviving_mock = (
+ (mock_definitions, mock_service) if failing == "definitions" else (mock_service, mock_definitions)
+ )
+ failing_mock.delay.side_effect = RuntimeError("broker unreachable")
+
+ with coalesced_cohort_flags_cache_rebuilds() as stale_cache_teams:
+ self._save_definition(cohort)
+
+ assert stale_cache_teams == {self.team.id}
+ surviving_mock.delay.assert_called_once_with(self.team.id)
+
+
+@override_settings(FLAGS_REDIS_URL="redis://test")
+class TestCoalescedRebuildsWaitForTheCommit(BaseTest):
+ @patch("products.feature_flags.backend.tasks.update_team_flags_cache")
+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")
+ def test_dispatch_is_deferred_to_the_commit(self, mock_service, mock_definitions):
+ cohort = Cohort.objects.create(team=self.team, name="one")
+ mock_service.reset_mock()
+ mock_definitions.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ with coalesced_cohort_flags_cache_rebuilds():
+ cohort.filters = {"properties": {"type": "AND", "values": []}}
+ cohort.save(update_fields=["filters"])
+ # A worker started here would read the cohort rows before they commit.
+ mock_service.delay.assert_not_called()
+ mock_definitions.delay.assert_not_called()
+
+ mock_service.delay.assert_called_once_with(self.team.id)
+ mock_definitions.delay.assert_called_once_with(self.team.id)
+
+
class TestStripNullValues(unittest.TestCase):
"""Pure-function tests for ``_strip_null_values``.