Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): verify realtime cohort classification in resave_cohorts (#84886)

Gustavo H. Strassburgerb43707133d62
diff --git a/posthog/admin/admins/resave_cohorts_admin.py b/posthog/admin/admins/resave_cohorts_admin.py
index 300823b02cff..03e7ade9105b 100644
--- a/posthog/admin/admins/resave_cohorts_admin.py
+++ b/posthog/admin/admins/resave_cohorts_admin.py
@@ -4,6 +4,8 @@ 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
+
class ResaveCohortsForm(forms.Form):
team_id = forms.IntegerField(required=False, help_text="Only process cohorts for this team id (optional)")
@@ -26,17 +28,25 @@ def resave_cohorts_view(request):
"batch_size": form.cleaned_data["batch_size"],
"dry_run": form.cleaned_data["dry_run"],
}
- if form.cleaned_data.get("team_id"):
- command_kwargs["team_id"] = form.cleaned_data["team_id"]
+ team_id = form.cleaned_data.get("team_id")
+ if team_id is not None:
+ # Presence, not truthiness: team 0 has to reach the command, which rejects it. Reading
+ # it as "no team given" would silently widen the run to every team.
+ # `call_command` skips argparse coercion for keyword options, so the list the
+ # `--team-id` flag builds has to be passed already built.
+ command_kwargs["team_id"] = [team_id]
try:
call_command("resave_cohorts", **command_kwargs)
- scope = f"team {form.cleaned_data['team_id']}" if form.cleaned_data.get("team_id") else "all teams"
+ scope = f"team {team_id}" if team_id is not None else "all teams"
mode = "dry-run" if form.cleaned_data["dry_run"] else "apply"
messages.success(
request,
f"Cohort re-save started ({mode}) for {scope} with batch_size={form.cleaned_data['batch_size']}.",
)
+ except UnclassifiedCohortsError 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)}")
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 654a002e63c0..5e8685356c26 100644
--- a/posthog/management/commands/resave_cohorts.py
+++ b/posthog/management/commands/resave_cohorts.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Any
-from django.core.management.base import BaseCommand, CommandParser
+from django.core.management.base import BaseCommand, CommandError, CommandParser
import structlog
@@ -10,11 +10,27 @@ from posthog.api.cohort import validate_filters_and_compute_realtime_support
from posthog.dataclasses import frozen
from posthog.models.team.team import Team
-from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.cohort import Cohort, 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
logger = structlog.get_logger(__name__)
+# How many unclassified cohort ids to name in the failure output before summarizing the rest.
+UNCLASSIFIED_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)
+
+
+class UnclassifiedCohortsError(CommandError):
+ """The run finished and persisted its saves, but left cohorts the realtime gate misreads.
+
+ 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.
+ """
+
@frozen
class CohortResaveStats:
@@ -25,6 +41,15 @@ class CohortResaveStats:
prospective_realtime: int
+@frozen
+class TeamSelection:
+ team_ids: tuple[int, ...] | None
+ label: str
+ # Whether the operator named a scope. Only then is an unclassified cohort worth failing on: a
+ # bare run covers every team, including the ones the realtime gate never reads.
+ explicit: bool
+
+
class Command(BaseCommand):
help = "Regenerate inline bytecode (in filters), cohort_type, and condition_type for cohorts."
@@ -32,7 +57,13 @@ class Command(BaseCommand):
parser.add_argument(
"--team-id",
type=int,
- help="Team ID to process; if omitted, processes all teams.",
+ nargs="+",
+ help="Team IDs to process; if omitted, processes all teams.",
+ )
+ parser.add_argument(
+ "--realtime-allowlist",
+ action="store_true",
+ help="Process the teams matched by REALTIME_COHORT_TEAM_ALLOWLIST.",
)
parser.add_argument(
"--batch-size",
@@ -48,26 +79,25 @@ class Command(BaseCommand):
def handle(self, *args: Any, **options: Any) -> None:
# Parse CLI arguments
- team_id = options.get("team_id")
+ selection = self._resolve_teams(options)
dry_run: bool = bool(options.get("dry_run"))
batch_size: int = int(options.get("batch_size") or 500)
# Log start of operation
logger.info(
"cohort_resave_started",
- team_id=team_id,
+ team_ids=selection.team_ids,
dry_run=dry_run,
batch_size=batch_size,
- scope="single_team" if team_id else "all_teams",
+ scope=selection.label,
)
- scope = f"team {team_id}" if team_id else "all teams"
dry_run_label = " (dry run)" if dry_run else ""
- self.stdout.write(f"Starting cohort resave for {scope}, batch_size={batch_size}{dry_run_label}")
+ self.stdout.write(f"Starting cohort resave for {selection.label}, batch_size={batch_size}{dry_run_label}")
# Get teams to process
teams_qs = Team.objects.all().order_by("id")
- if team_id:
- teams_qs = teams_qs.filter(id=team_id)
+ if selection.team_ids is not None:
+ teams_qs = teams_qs.filter(id__in=selection.team_ids)
# Track global stats
global_total = 0
@@ -117,6 +147,10 @@ class Command(BaseCommand):
style = self.style.WARNING if (stats.errors > 0 or stats.validation_errors > 0) else self.style.SUCCESS
self.stdout.write(style(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.
+ unclassified = None if dry_run else self._unclassified_cohort_ids(selection)
+
# Log final summary
change_pct = round((global_changed / global_total * 100), 2) if global_total > 0 else 0
realtime_pct = round((global_prospective_realtime / global_total * 100), 2) if global_total > 0 else 0
@@ -131,19 +165,105 @@ class Command(BaseCommand):
validation_error_count=global_validation_errors,
change_percentage=change_pct,
realtime_percentage=realtime_pct,
+ unclassified_count=None if unclassified is None else len(unclassified),
)
self.stdout.write("")
- final_style = self.style.WARNING if (global_errors > 0 or global_validation_errors > 0) else self.style.SUCCESS
+ healthy = global_errors == 0 and global_validation_errors == 0 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(
final_style(
f"Done{dry_run_label}. "
f"{teams_processed} teams, {global_total} cohorts, "
f"{global_changed} changed ({change_pct}%), "
f"{global_prospective_realtime} realtime ({realtime_pct}%), "
- f"{global_errors} errors, {global_validation_errors} validation errors"
+ f"{global_errors} errors, {global_validation_errors} validation errors, "
+ f"{unclassified_label}"
)
)
+ if unclassified and selection.explicit:
+ self._fail_on_unclassified(unclassified)
+
+ 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.
+
+ Reading persisted state covers every way a cohort ends up unclassified: a save that raised, a
+ filter set the validator rejected, and a well-formed filter group with no leaf conditions,
+ which the resave classifies as realtime and leaves with a null `condition_type`. It only
+ means anything after a run that persisted, so the caller skips it on a dry run.
+ """
+ qs = Cohort.objects.filter(cohort_type__in=REALTIME_GATED_COHORT_TYPES, condition_type__isnull=True)
+ if selection.team_ids is not None:
+ qs = qs.filter(team_id__in=selection.team_ids)
+ return list(qs.order_by("id").values_list("id", flat=True))
+
+ def _fail_on_unclassified(self, cohort_ids: list[int]) -> None:
+ """Refuse to report success while a gated cohort still has a null `condition_type`.
+
+ 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}. "
+ "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 _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))
+ missing = sorted({team_id for team_id in requested if team_id not in found})
+ if missing:
+ raise CommandError(f"No team with id {', '.join(str(team_id) for team_id in missing)}")
+ return tuple(sorted(found))
+
+ def _resolve_teams(self, options: dict[str, Any]) -> TeamSelection:
+ """Resolve the team selector into explicit ids, or None for every team."""
+ team_ids: list[int] | None = options.get("team_id")
+ realtime_allowlist: bool = bool(options.get("realtime_allowlist"))
+
+ if team_ids is not None and realtime_allowlist:
+ raise CommandError("Pass only one of --team-id, --realtime-allowlist")
+
+ if team_ids is not None:
+ if any(team_id <= 0 for team_id in team_ids):
+ raise CommandError("--team-id must be a positive integer")
+ resolved = self._existing_team_ids(team_ids)
+ label = f"team {resolved[0]}" if len(resolved) == 1 else f"{len(resolved)} teams"
+ return TeamSelection(team_ids=resolved, label=label, explicit=True)
+
+ if realtime_allowlist:
+ if realtime_allowlist_matches_every_team():
+ # Scanning every team to rediscover that the allowlist matches all of them would
+ # build an `IN` clause holding every team id, parsed once per queryset.
+ return TeamSelection(
+ team_ids=None,
+ label="all teams (realtime allowlist matches every team)",
+ explicit=True,
+ )
+ allowed = tuple(
+ candidate
+ for candidate in Team.objects.order_by("id").values_list("id", flat=True)
+ if is_realtime_cohort_team(candidate)
+ )
+ # An allowlist that matches nothing would resave nothing and still report success, which
+ # during a rollout reads the same as "every cohort is classified".
+ if not allowed:
+ raise CommandError("REALTIME_COHORT_TEAM_ALLOWLIST matches no teams")
+ return TeamSelection(
+ team_ids=allowed,
+ label=f"{len(allowed)} realtime-allowlisted teams",
+ explicit=True,
+ )
+
+ return TeamSelection(team_ids=None, label="all teams", explicit=False)
+
def _process_team_cohorts(self, team: Team, batch_size: int, dry_run: bool) -> CohortResaveStats:
"""Process all cohorts for a single team."""
# Initialize stats for this team
diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.py
index 9a0d720e7e7c..22d902fab8db 100644
--- a/posthog/management/commands/test/test_resave_cohorts.py
+++ b/posthog/management/commands/test/test_resave_cohorts.py
@@ -1,10 +1,17 @@
from __future__ import annotations
+from io import StringIO
from typing import Any
+import pytest
from posthog.test.base import BaseTest
+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 parameterized import parameterized
from posthog.models.team.team import Team
@@ -111,7 +118,7 @@ class TestResaveCohortsCommandSingleTeam(BaseTest):
assert not _has_condition_hash(c.filters)
# Run command for this team
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload and assert
updated = {c.id: Cohort.objects.get(id=c.id) for c in cohorts}
@@ -177,7 +184,7 @@ class TestResaveCohortsCommandSingleTeam(BaseTest):
cohort = Cohort.objects.create(team=team, name="rt", filters=_make_realtime_filters())
Cohort.objects.filter(id=cohort.id).update(condition_type=None)
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
cohort.refresh_from_db()
assert cohort.condition_type == {
@@ -220,7 +227,7 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
realtime_cohort = Cohort.objects.create(team=team, name="fully_realtime", filters=_make_person_only_filters())
# Run command
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload cohorts
unsupported_cohort.refresh_from_db()
@@ -266,7 +273,7 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
)
# Run command
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload cohorts
leaf_cohort1.refresh_from_db()
@@ -308,7 +315,7 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
)
# Run command
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload cohorts
realtime_dependency.refresh_from_db()
@@ -353,7 +360,7 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
)
# Run command
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload cohorts
non_realtime_dep.refresh_from_db()
@@ -410,7 +417,7 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
)
# Run command
- call_command("resave_cohorts", team_id=team.id)
+ call_command("resave_cohorts", team_id=[team.id])
# Reload cohorts
cohort_a.refresh_from_db()
@@ -477,7 +484,7 @@ class TestResaveCohortsCommandTwoTeams(BaseTest):
cohorts_b = make_five(team_b, ref_b)
# Run for team A only
- call_command("resave_cohorts", team_id=team_a.id)
+ call_command("resave_cohorts", team_id=[team_a.id])
for c in cohorts_a:
c.refresh_from_db()
@@ -508,3 +515,151 @@ class TestResaveCohortsCommandTwoTeams(BaseTest):
assert cohorts_b[2].cohort_type == "realtime"
assert cohorts_b[3].cohort_type is None # Cannot be realtime because it references a static cohort
assert cohorts_b[4].cohort_type == "realtime"
+
+
+class TestResaveCohortsCommandTeamSelection(BaseTest):
+ def test_team_id_processes_only_the_listed_teams(self):
+ team_a: Team = self.team
+ team_b: Team = Team.objects.create(organization=self.organization)
+ team_c: Team = Team.objects.create(organization=self.organization)
+
+ cohort_b = Cohort.objects.create(team=team_b, name="rt_b", filters=_make_realtime_filters())
+ cohort_c = Cohort.objects.create(team=team_c, name="rt_c", filters=_make_realtime_filters())
+ Cohort.objects.filter(id__in=[cohort_b.id, cohort_c.id]).update(condition_type=None)
+
+ call_command("resave_cohorts", team_id=[team_a.id, team_b.id])
+
+ cohort_b.refresh_from_db()
+ cohort_c.refresh_from_db()
+ assert cohort_b.condition_type is not None
+ assert cohort_c.condition_type is None
+
+ def test_realtime_allowlist_processes_only_allowlisted_teams(self):
+ team_b: Team = Team.objects.create(organization=self.organization)
+ cohort_a = Cohort.objects.create(team=self.team, name="rt_a", filters=_make_realtime_filters())
+ cohort_b = Cohort.objects.create(team=team_b, name="rt_b", filters=_make_realtime_filters())
+ Cohort.objects.filter(id__in=[cohort_a.id, cohort_b.id]).update(condition_type=None)
+
+ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST=str(team_b.id)):
+ call_command("resave_cohorts", realtime_allowlist=True)
+
+ cohort_a.refresh_from_db()
+ cohort_b.refresh_from_db()
+ assert cohort_b.condition_type is not None
+ assert cohort_a.condition_type is None
+
+ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")
+ def test_realtime_allowlist_matching_every_team_processes_every_team(self):
+ team_b: Team = Team.objects.create(organization=self.organization)
+ cohort = Cohort.objects.create(team=team_b, name="rt", filters=_make_realtime_filters())
+ Cohort.objects.filter(id=cohort.id).update(condition_type=None)
+
+ call_command("resave_cohorts", realtime_allowlist=True)
+
+ cohort.refresh_from_db()
+ assert cohort.condition_type is not None
+
+ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none")
+ def test_realtime_allowlist_matching_no_teams_fails(self):
+ with pytest.raises(CommandError, match="matches no teams"):
+ call_command("resave_cohorts", realtime_allowlist=True)
+
+ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")
+ def test_conflicting_team_selectors_fail(self):
+ with pytest.raises(CommandError, match="only one of"):
+ call_command("resave_cohorts", team_id=[self.team.id], realtime_allowlist=True)
+
+ @parameterized.expand(
+ [
+ ("unknown_team_id", {"team_id": [9999999]}, "No team with id 9999999"),
+ ("zero_team_id", {"team_id": [0]}, "must be a positive integer"),
+ ]
+ )
+ def test_selector_matching_no_team_fails(self, _name: str, kwargs: dict[str, Any], message: str):
+ cohort = Cohort.objects.create(team=self.team, name="rt", filters=_make_realtime_filters())
+ Cohort.objects.filter(id=cohort.id).update(condition_type=None)
+
+ with pytest.raises(CommandError, match=message):
+ call_command("resave_cohorts", **kwargs)
+
+ cohort.refresh_from_db()
+ assert cohort.condition_type is None
+
+
+class TestResaveCohortsCommandConditionTypeVerification(BaseTest):
+ @parameterized.expand([("realtime",), ("behavioral",)])
+ def test_gated_cohort_the_validator_rejects_fails_the_command(self, cohort_type: str):
+ cohort = Cohort.objects.create(team=self.team, name="rt", filters=_make_realtime_filters())
+ # Filters the validator rejects, so the resave cannot recompute a condition_type for it
+ Cohort.objects.filter(id=cohort.id).update(
+ cohort_type=cohort_type, condition_type=None, filters={"properties": {}}
+ )
+
+ with pytest.raises(CommandError, match=f"cohorts still have a null condition_type: {cohort.id}"):
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ def test_leafless_cohort_the_resave_classifies_fails_the_command(self):
+ # A well-formed group with no leaves passes validation and saves as realtime, but has nothing
+ # to derive a condition_type from, so the success path writes the state the gate misreads.
+ cohort = Cohort.objects.create(
+ team=self.team, name="leafless", filters={"properties": {"type": "AND", "values": []}}
+ )
+
+ with pytest.raises(CommandError, match=f"cohorts still have a null condition_type: {cohort.id}"):
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ cohort.refresh_from_db()
+ assert cohort.cohort_type == "realtime"
+ assert cohort.condition_type is None
+
+ def test_gated_cohort_left_unclassified_by_a_failed_save_fails_the_command(self):
+ cohort = Cohort.objects.create(team=self.team, name="rt", filters=_make_realtime_filters())
+ Cohort.objects.filter(id=cohort.id).update(cohort_type="realtime", condition_type=None)
+
+ with patch.object(Cohort, "save", side_effect=Exception("save blew up")):
+ with pytest.raises(CommandError, match=f"cohorts still have a null condition_type: {cohort.id}"):
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ def test_unclassified_cohort_does_not_fail_a_run_over_every_team(self):
+ # A bare run covers teams the realtime gate never reads, so it reports rather than fails.
+ cohort = Cohort.objects.create(team=self.team, name="rt", filters=_make_realtime_filters())
+ Cohort.objects.filter(id=cohort.id).update(
+ cohort_type="realtime", condition_type=None, filters={"properties": {}}
+ )
+
+ call_command("resave_cohorts")
+
+ cohort.refresh_from_db()
+ assert cohort.condition_type is None
+
+ def test_dry_run_reports_the_verification_as_unchecked_rather_than_clean(self):
+ # Nothing is persisted, so the post-run query would read the state the run started from.
+ # Saying so beats printing a zero that reads as "every cohort is classified".
+ Cohort.objects.create(team=self.team, name="rt", filters=_make_realtime_filters())
+ out = StringIO()
+
+ call_command("resave_cohorts", team_id=[self.team.id], dry_run=True, stdout=out)
+
+ assert "unclassified not checked" in out.getvalue()
+
+ def test_dry_run_neither_persists_nor_fails_on_an_unclassified_gated_cohort(self):
+ cohort = Cohort.objects.create(team=self.team, name="leafless", filters={"properties": {"type": "AND"}})
+ Cohort.objects.filter(id=cohort.id).update(cohort_type="realtime", condition_type=None)
+ out = StringIO()
+
+ call_command("resave_cohorts", team_id=[self.team.id], dry_run=True, stdout=out)
+
+ assert "unclassified not checked" in out.getvalue()
+ cohort.refresh_from_db()
+ assert cohort.filters == {"properties": {"type": "AND"}}
+ assert cohort.condition_type is None
+
+ def test_unclassifiable_non_gated_cohort_does_not_fail_the_command(self):
+ cohort = Cohort.objects.create(team=self.team, name="batch", filters=_make_realtime_filters())
+ Cohort.objects.filter(id=cohort.id).update(cohort_type=None, condition_type=None, filters={"properties": {}})
+
+ call_command("resave_cohorts", team_id=[self.team.id])
+
+ cohort.refresh_from_db()
+ assert cohort.cohort_type is None
+ assert cohort.condition_type is None
diff --git a/posthog/test/test_resave_cohorts_admin.py b/posthog/test/test_resave_cohorts_admin.py
new file mode 100644
index 000000000000..5b926764174a
--- /dev/null
+++ b/posthog/test/test_resave_cohorts_admin.py
@@ -0,0 +1,57 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.test import Client, override_settings
+
+from parameterized import parameterized
+
+from posthog.management.commands.resave_cohorts import UnclassifiedCohortsError
+
+
+@override_settings(ADMIN_PORTAL_ENABLED=True)
+class TestResaveCohortsAdminView(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.client = Client()
+ self.user.is_staff = True
+ self.user.save()
+ self.client.force_login(self.user)
+
+ def _post(self, team_id: str, follow: bool = False):
+ return self.client.post("/admin/resave-cohorts/", {"batch_size": 500, "team_id": team_id}, follow=follow)
+
+ @parameterized.expand(
+ [
+ ("explicit_team", "7", [7]),
+ # Team 0 has to reach the command, which rejects it. Reading it as "no team given" would
+ # silently resave every team.
+ ("team_zero", "0", [0]),
+ ("blank_team", "", None),
+ ]
+ )
+ @patch("posthog.admin.admins.resave_cohorts_admin.call_command")
+ def test_form_team_id_reaches_the_command(
+ self, _name: str, submitted: str, expected: list[int] | None, mock_call_command: MagicMock
+ ) -> None:
+ self._post(submitted)
+
+ assert mock_call_command.call_args.kwargs.get("team_id") == expected
+
+ @patch("posthog.admin.admins.resave_cohorts_admin.call_command")
+ def test_unclassified_cohorts_report_as_a_warning(self, mock_call_command: MagicMock) -> None:
+ mock_call_command.side_effect = UnclassifiedCohortsError("2 cohorts still have a null condition_type: 1, 2")
+
+ response = self._post("7", follow=True)
+
+ message = next(iter(response.context["messages"]))
+ assert message.level_tag == "warning"
+ assert "finished" in str(message)
+
+ @patch("posthog.admin.admins.resave_cohorts_admin.call_command")
+ def test_a_run_that_never_started_reports_as_an_error(self, mock_call_command: MagicMock) -> None:
+ mock_call_command.side_effect = Exception("boom")
+
+ response = self._post("7", follow=True)
+
+ message = next(iter(response.context["messages"]))
+ assert message.level_tag == "error"
diff --git a/products/cohorts/backend/realtime_teams.py b/products/cohorts/backend/realtime_teams.py
index 248a04e3abde..5adbc615e02f 100644
--- a/products/cohorts/backend/realtime_teams.py
+++ b/products/cohorts/backend/realtime_teams.py
@@ -4,6 +4,11 @@ from django.conf import settings
_MAX_RANGE_SPAN = 100_000
+def _matches_every_team(raw_allowlist: str) -> bool:
+ raw_allowlist = raw_allowlist.strip()
+ return raw_allowlist == "" or raw_allowlist.lower() == "all" or raw_allowlist == "*"
+
+
def _team_in_allowlist(raw_allowlist: str, team_id: int) -> bool:
"""Whether ``team_id`` matches a team-allowlist setting.
@@ -16,7 +21,7 @@ def _team_in_allowlist(raw_allowlist: str, team_id: int) -> bool:
Malformed tokens are ignored — the Rust side rejects the whole value at startup.
"""
raw_allowlist = raw_allowlist.strip()
- if raw_allowlist == "" or raw_allowlist.lower() == "all" or raw_allowlist == "*":
+ if _matches_every_team(raw_allowlist):
return True
if raw_allowlist.lower() == "none":
return False
@@ -37,6 +42,14 @@ def _team_in_allowlist(raw_allowlist: str, team_id: int) -> bool:
return False
+def realtime_allowlist_matches_every_team() -> bool:
+ """Whether the realtime allowlist is one of the match-everything values.
+
+ Lets a caller skip enumerating every team to rediscover that the allowlist covers all of them.
+ """
+ return _matches_every_team(settings.REALTIME_COHORT_TEAM_ALLOWLIST)
+
+
def is_realtime_cohort_team(team_id: int) -> bool:
"""Whether the realtime-cohort pipeline is scoped to ``team_id``."""
return _team_in_allowlist(settings.REALTIME_COHORT_TEAM_ALLOWLIST, team_id)