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): skip malformed cohorts in resave_cohorts dependency map (#112904)

posthog[bot]1ad9a748f82a
diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.py
index e990206e6650..2a56f2dba814 100644
--- a/posthog/management/commands/resave_cohorts.py
+++ b/posthog/management/commands/resave_cohorts.py
@@ -374,14 +374,17 @@ class Command(BaseCommand):
"""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}
- cohort_dependencies = self._build_dependency_map(all_cohorts, seen_cohorts_cache)
+ cohort_dependencies, unreadable_ids = self._build_dependency_map(team, all_cohorts, seen_cohorts_cache)
- # Sort cohorts topologically - dependencies first, then dependents
- sorted_cohort_ids = sort_cohorts_topologically({c.id for c in all_cohorts}, seen_cohorts_cache)
+ # Sort cohorts topologically - dependencies first, then dependents. The sort parses the
+ # filters of every cohort it reaches, so the unreadable ones stay out of it.
+ sorted_cohort_ids = sort_cohorts_topologically(
+ {c.id for c in all_cohorts if c.id not in unreadable_ids}, seen_cohorts_cache
+ )
- total = 0
+ total = len(unreadable_ids)
changed = 0
- errors = 0
+ errors = len(unreadable_ids)
validation_errors = 0
prospective_realtime = 0
@@ -448,17 +451,34 @@ class Command(BaseCommand):
last_id = batch[-1].id
def _build_dependency_map(
- self, all_cohorts: list[Cohort], seen_cohorts_cache: dict[int, CohortOrEmpty]
- ) -> dict[int, set[int]]:
+ self, team: Team, all_cohorts: list[Cohort], seen_cohorts_cache: dict[int, CohortOrEmpty]
+ ) -> tuple[dict[int, set[int]], set[int]]:
"""Map each cohort id to every cohort id it depends on, recursively: A->B->C makes A depend on
- both B and C."""
+ both B and C.
+
+ Also return the ids of the cohorts whose dependencies cannot be read. Malformed filters make
+ the lookup raise for that cohort and for every cohort that references it. The run skips
+ these cohorts and counts them as errors, so one bad cohort does not stop the run.
+ """
cohort_dependencies: dict[int, set[int]] = {}
+ unreadable_ids: set[int] = set()
for cohort in all_cohorts:
if not cohort.filters:
continue
- dependencies = get_all_cohort_dependencies(cohort, seen_cohorts_cache=seen_cohorts_cache)
+ try:
+ dependencies = get_all_cohort_dependencies(cohort, seen_cohorts_cache=seen_cohorts_cache)
+ except Exception as err:
+ unreadable_ids.add(cohort.id)
+ logger.error(
+ "cohort_resave_error",
+ cohort_id=cohort.id,
+ team_id=team.id,
+ error=str(err),
+ exc_info=True,
+ )
+ continue
cohort_dependencies[cohort.id] = {dep.id for dep in dependencies}
- return cohort_dependencies
+ return cohort_dependencies, unreadable_ids
def _recompute_cohort(
self,
diff --git a/posthog/management/commands/test/test_resave_cohorts.py b/posthog/management/commands/test/test_resave_cohorts.py
index 434c6e5fd455..8cd78820854a 100644
--- a/posthog/management/commands/test/test_resave_cohorts.py
+++ b/posthog/management/commands/test/test_resave_cohorts.py
@@ -275,6 +275,44 @@ class TestResaveCohortsCommandWithDependencies(BaseTest):
# 3. Realtime cohort should be realtime (no problematic dependencies)
assert realtime_cohort.cohort_type == "realtime"
+ def test_cohort_with_unparseable_filters_is_counted_as_an_error_without_stopping_the_run(self):
+ malformed = Cohort.objects.create(team=self.team, name="malformed", filters=_make_person_only_filters())
+ Cohort.objects.filter(id=malformed.id).update(
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "OR",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"type": "person", "key": "email", "value": "[email protected]"}],
+ },
+ {"type": "person", "key": "email", "value": "[email protected]"},
+ ],
+ }
+ ],
+ }
+ }
+ )
+ referencing = Cohort.objects.create(
+ team=self.team,
+ name="referencing",
+ filters={"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": malformed.id}]}},
+ )
+ healthy = Cohort.objects.create(team=self.team, name="healthy", filters=_make_person_only_filters())
+ out = StringIO()
+
+ call_command("resave_cohorts", team_id=[self.team.id], stdout=out)
+
+ healthy.refresh_from_db()
+ referencing.refresh_from_db()
+ assert healthy.cohort_type == "realtime"
+ assert referencing.cohort_type is None
+ assert "3 cohorts" in out.getvalue()
+ assert "2 errors" in out.getvalue()
+
def test_cohort_with_multiple_leaf_dependencies_can_be_realtime(self):
"""Test that a cohort referencing multiple leaf cohorts (no dependencies) can be realtime."""
team: Team = self.team