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): trigger a repair run when only cohort composition changes (#101209)

Matheus Batista1e5f8d73fe49
diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.py
index 8e6d3f384aaf..ae94d0eec95b 100644
--- a/products/cohorts/backend/backfill/readiness.py
+++ b/products/cohorts/backend/backfill/readiness.py
@@ -21,6 +21,7 @@ from products.cohorts.backend.models.backfill import (
)
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.leaf_shape import (
+ FilterShapeHashes,
extract_behavioral_leaf_shape_hash,
extract_leaf_shape_hash,
extract_person_leaf_shape_hash,
@@ -102,9 +103,11 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
"""CAS-stamp event readiness for one pinned cohort.
Keys on the behavioral shape hash, not the full one: edit-time invalidation only nulls
- ``last_backfill_events_at`` when the behavioral leaves change (see ``_maintain_filter_shape_hashes``).
- A person-property or cohort-reference edit mid-backfill shifts the full hash without touching
- events readiness, so keying on the full hash would wrongly supersede a still-valid events backfill.
+ ``last_backfill_events_at`` when the behavioral leaves change, or when the definition changes in
+ a way no other run repairs (see ``_maintain_filter_shape_hashes``).
+ A person-property edit mid-backfill shifts the full hash without touching events readiness, so
+ keying on the full hash would wrongly supersede a still-valid events backfill.
+ A separate, locked definition check refuses a run that predates a required composition repair.
"""
return _stamp_readiness(run, cohort_id, _EVENTS)
@@ -136,13 +139,33 @@ def _stamp_readiness(run: CohortBackfillRun, cohort_id: int, spec: _ReadinessSpe
)
return False
+ # Serialize the definition check with edits; supersession runs only after the edit commits.
+ cohort = (
+ Cohort.objects.select_for_update(of=("self",)).only("filters").filter(id=cohort_id, team_id=run.team_id).first()
+ )
+ composition_stale = False
+ if cohort is not None:
+ try:
+ current_shape = FilterShapeHashes.from_filters(cohort.filters)
+ pinned_shape = FilterShapeHashes.from_filters(participation.pinned_filters)
+ composition_stale = current_shape.composition_repair_kind(pinned_shape, cohort.filters) == run.backfill_kind
+ except Exception:
+ # An unreadable definition cannot prove readiness and must not trap the finalizer in retries.
+ composition_stale = True
+ logger.exception(
+ "cohort_backfill_readiness_definition_invalid",
+ run_id=str(run.id),
+ cohort_id=cohort_id,
+ readiness=spec.readiness,
+ )
+
pinned = getattr(participation, spec.hash_field)
# Reused by the rollback below, so both writes fence on the same pinned fingerprint.
cohort_fence = {"id": cohort_id, "team_id": run.team_id, spec.hash_field: pinned}
- updated = Cohort.objects.filter(**cohort_fence, **{f"{spec.stamp_field}__isnull": True}).update(
- **{spec.stamp_field: Now()}
- )
+ updated = not composition_stale and Cohort.objects.filter(
+ **cohort_fence, **{f"{spec.stamp_field}__isnull": True}
+ ).update(**{spec.stamp_field: Now()})
if updated:
# ``superseded_at__isnull`` guards a supersession racing in after the up-front check; a
# 0-row stamp then means the participation lost the race, so refuse (finalizer treats it
@@ -157,7 +180,12 @@ def _stamp_readiness(run: CohortBackfillRun, cohort_id: int, spec: _ReadinessSpe
current_readiness = (
Cohort.objects.filter(id=cohort_id, team_id=run.team_id).values_list(spec.hash_field, spec.stamp_field).first()
)
- if current_readiness is not None and current_readiness[0] == pinned and current_readiness[1] is not None:
+ if (
+ not composition_stale
+ and current_readiness is not None
+ and current_readiness[0] == pinned
+ and current_readiness[1] is not None
+ ):
return _ratify(run, participation.id)
error = "Cohort definition changed before readiness was stamped"
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index 74e1612fa551..b94daacbf960 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from posthog.test.base import BaseTest
from django.db import connection
@@ -13,7 +15,7 @@ from products.cohorts.backend.backfill.readiness import (
stamp_person_properties_readiness,
)
from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohort, create_person_backfill_run_for_cohort
-from products.cohorts.backend.models.backfill import CohortBackfillRunCohort, CohortBackfillRunStatus
+from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBackfillRunCohort, CohortBackfillRunStatus
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.leaf_shape import extract_leaf_shape_hash, extract_person_leaf_shape_hash
@@ -145,6 +147,71 @@ class TestBackfillReadiness(BaseTest):
self.assertIsNone(participation.superseded_at)
self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)
+ @parameterized.expand(KINDS)
+ def test_composition_edit_before_supersession_cannot_stamp(
+ self, name: str, make_run, stamp, hash_column: str, stamp_column: str, *_edits
+ ) -> None:
+ filters = self._filters(7, person_hash="person-a")
+ if name == "person_properties":
+ filters["properties"]["values"] = filters["properties"]["values"][1:]
+ cohort = Cohort.objects.create(team=self.team, cohort_type=CohortType.REALTIME, filters=filters)
+ run = make_run(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
+ pinned_hash = getattr(cohort, hash_column)
+
+ cohort.filters["properties"]["values"][-1]["negation"] = True
+ cohort.save(update_fields=["filters"])
+
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
+ self.assertIsNone(participation.superseded_at)
+ self.assertEqual(getattr(cohort, hash_column), pinned_hash)
+ self.assertFalse(stamp(run, cohort.id))
+
+ cohort.refresh_from_db()
+ run.refresh_from_db()
+ participation.refresh_from_db()
+ self.assertIsNone(getattr(cohort, stamp_column))
+ self.assertIsNotNone(participation.superseded_at)
+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
+
+ @parameterized.expand(
+ [
+ (f"{name}_{source}", make_run, stamp, stamp_column, source)
+ for name, make_run, stamp, _hash, stamp_column, _same, _other in KINDS
+ for source in ("current", "pinned")
+ ]
+ )
+ def test_malformed_definition_supersedes_without_stamping(
+ self,
+ _name: str,
+ make_run: Callable[[int, int, str], CohortBackfillRun | None],
+ stamp: Callable[[CohortBackfillRun, int], bool],
+ stamp_column: str,
+ source: str,
+ ) -> None:
+ cohort, run = self._cohort_and_run(make_run)
+ run.status = CohortBackfillRunStatus.RECONCILING
+ run.save(update_fields=["status"])
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
+ malformed_filters = {"properties": {"type": "AND", "values": 3}}
+ if source == "current":
+ Cohort.objects.filter(id=cohort.id, team_id=self.team.id).update(filters=malformed_filters)
+ else:
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(id=participation.id).update(
+ pinned_filters=malformed_filters
+ )
+
+ self.assertFalse(stamp(run, cohort.id))
+
+ cohort.refresh_from_db()
+ run.refresh_from_db()
+ participation.refresh_from_db()
+ self.assertIsNone(getattr(cohort, stamp_column))
+ self.assertIsNone(participation.stamped_at)
+ self.assertIsNotNone(participation.superseded_at)
+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
+ self.assertIsNotNone(run.finished_at)
+
@parameterized.expand(KINDS)
def test_already_stamped_readiness_is_not_overwritten(
self, _name: str, make_run, stamp, _hash: str, stamp_column: str, *_edits
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 3a87bcc188f8..2f23a1635914 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -36,6 +36,7 @@ from posthog.schema_enums import ProductKey
from posthog.settings.base_variables import TEST
from products.cohorts.backend.models.leaf_shape import (
+ FilterShapeHashes,
extract_behavioral_leaf_shape_hash,
extract_leaf_shape_hash,
extract_person_leaf_shape_hash,
@@ -382,37 +383,54 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
stored_person_shape_hash = self.__dict__.get("person_filters_shape_hash")
previous_behavioral_shape_hash = stored_behavioral_shape_hash
previous_person_shape_hash = stored_person_shape_hash
-
- if not self._state.adding and (
- stored_shape_hash is None or stored_behavioral_shape_hash is None or stored_person_shape_hash is None
- ):
- persisted = (
- Cohort.objects.filter(id=self.pk, team_id=self.team_id)
- .values(
- "filters",
- "filters_shape_hash",
- "behavioral_filters_shape_hash",
- "person_filters_shape_hash",
- )
- .first()
- )
+ previous_shape_hash = None
+
+ if not self._state.adding:
+ persisted_query = Cohort.objects.filter(id=self.pk, team_id=self.team_id)
+ if (
+ stored_shape_hash is not None
+ and stored_behavioral_shape_hash is not None
+ and stored_person_shape_hash is not None
+ ):
+ # Check equality in Postgres: a stale instance can overwrite a concurrent edit.
+ # Matching rows need no JSONB transfer or rehash; legacy hashes still fall through.
+ persisted_query = persisted_query.exclude(filters_shape_hash=new_shape_hash)
+ persisted = persisted_query.values(
+ "filters",
+ "filters_shape_hash",
+ "behavioral_filters_shape_hash",
+ "person_filters_shape_hash",
+ ).first()
if persisted is not None:
+ # Kind hashes retain edits made while the cohort was outside realtime tracking.
+ # Recomputing those baselines from filters would lose that invalidation signal.
+ try:
+ previous_shape_hash = extract_leaf_shape_hash(persisted["filters"])
+ except Exception:
+ # A malformed baseline must not disable invalidation for a valid replacement.
+ previous_shape_hash = None
if stored_shape_hash is None:
stored_shape_hash = persisted["filters_shape_hash"]
if stored_behavioral_shape_hash is None:
stored_behavioral_shape_hash = persisted["behavioral_filters_shape_hash"]
- previous_behavioral_shape_hash = (
- stored_behavioral_shape_hash
- if stored_behavioral_shape_hash is not None
- else extract_behavioral_leaf_shape_hash(persisted["filters"])
- )
+ try:
+ previous_behavioral_shape_hash = (
+ stored_behavioral_shape_hash
+ if stored_behavioral_shape_hash is not None
+ else extract_behavioral_leaf_shape_hash(persisted["filters"])
+ )
+ except Exception:
+ previous_behavioral_shape_hash = None
if stored_person_shape_hash is None:
stored_person_shape_hash = persisted["person_filters_shape_hash"]
- previous_person_shape_hash = (
- stored_person_shape_hash
- if stored_person_shape_hash is not None
- else extract_person_leaf_shape_hash(persisted["filters"])
- )
+ try:
+ previous_person_shape_hash = (
+ stored_person_shape_hash
+ if stored_person_shape_hash is not None
+ else extract_person_leaf_shape_hash(persisted["filters"])
+ )
+ except Exception:
+ previous_person_shape_hash = None
shape_hash_needs_update = stored_shape_hash != new_shape_hash
behavioral_shape_hash_needs_update = stored_behavioral_shape_hash != new_behavioral_shape_hash
@@ -422,6 +440,18 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
)
person_shape_changed = not self._state.adding and previous_person_shape_hash != new_person_shape_hash
+ current_shape = FilterShapeHashes(
+ definition=new_shape_hash, behavioral=new_behavioral_shape_hash, person=new_person_shape_hash
+ )
+ previous_shape = FilterShapeHashes(
+ definition=previous_shape_hash,
+ behavioral=previous_behavioral_shape_hash,
+ person=previous_person_shape_hash,
+ )
+ repair_kind = current_shape.composition_repair_kind(previous_shape, self.filters)
+ behavioral_shape_changed |= repair_kind == "behavioral"
+ person_shape_changed |= repair_kind == "person_property"
+
self.filters_shape_hash = new_shape_hash
self.behavioral_filters_shape_hash = new_behavioral_shape_hash
self.person_filters_shape_hash = new_person_shape_hash
diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.py
index 32bb3ca72e1c..1dc2d3c3124c 100644
--- a/products/cohorts/backend/models/leaf_shape.py
+++ b/products/cohorts/backend/models/leaf_shape.py
@@ -2,7 +2,9 @@ import json
import hashlib
from collections.abc import Iterator
from enum import StrEnum
-from typing import NamedTuple
+from typing import Literal, NamedTuple
+
+from posthog.dataclasses import frozen
_I32_MIN = -(2**31)
_I32_MAX = 2**31 - 1
@@ -83,7 +85,6 @@ def _hash_keys(keys: list[list[object]]) -> str:
class _LeafShapeMode(StrEnum):
- FULL = "full"
BEHAVIORAL_ONLY = "behavioral_only"
PERSON_ONLY = "person_only"
@@ -95,10 +96,10 @@ def _extract_leaf_shape_keys(filters: dict | None, *, mode: _LeafShapeMode) -> l
keys: list[list[object]] = []
for leaf in walk_filter_leaves(properties):
leaf_type = leaf.get("type")
- if leaf_type == "person" and mode != _LeafShapeMode.BEHAVIORAL_ONLY:
+ if leaf_type == "person" and mode == _LeafShapeMode.PERSON_ONLY:
if (condition_hash := leaf.get("conditionHash")) is not None:
keys.append(["person", condition_hash])
- elif leaf_type == "behavioral" and mode != _LeafShapeMode.PERSON_ONLY:
+ elif leaf_type == "behavioral" and mode == _LeafShapeMode.BEHAVIORAL_ONLY:
if (condition_hash := leaf.get("conditionHash")) is not None:
keys.append(
[
@@ -115,19 +116,87 @@ def _extract_leaf_shape_keys(filters: dict | None, *, mode: _LeafShapeMode) -> l
),
]
)
- elif leaf_type == "cohort" and mode == _LeafShapeMode.FULL:
- keys.append(["cohort", leaf.get("value"), bool(leaf.get("negation", False))])
return keys
-def extract_leaf_shape_hash(filters: dict | None) -> str:
- """Fingerprint the leaf fields that feed the Stage 1 `LeafStateKey`.
+def _canonical(node: object) -> str:
+ return json.dumps(node, sort_keys=True, separators=(",", ":"))
+
+
+def _render_definition(node: object) -> list[object] | None:
+ """Render one filter node into an order-insensitive, JSON-serializable form, or `None` if it
+ contributes nothing to the definition.
+
+ Group children are deduped and sorted because AND and OR are commutative and idempotent, so a
+ reordered or repeated criterion is the same definition. A group of one operand renders as that
+ operand: the cohort editor shows its AND/OR toggle even on a single criterion, and a toggle with
+ one operand under it means nothing.
- This is not the Rust key itself. It is a stable SHA-256 over the full leaf set, while
- `LeafStateKey::for_behavioral` uses a 16-byte digest of one leaf. Keep these fields in lockstep:
- behavioral leaves via `BehavioralLeafKey`; person conditionHash; cohort value and negation.
+ Cohort references are negated by `negation` or by `operator: "not_in"`, which mirrors
+ `cohort_ref_negation` in `rust/cohort-core/src/filters/leaf_classifier.rs`. Person and
+ behavioral leaves are negated by `negation` alone, because a bare `not_in` on those is a
+ value-list predicate already compiled into the bytecode the conditionHash digests.
+
+ `is True` rather than `bool(...)` for the same reason `_effective_i32` rejects a non-int: Rust
+ reads the field with `as_bool().unwrap_or(false)`, so a non-boolean is absent there, and
+ `bool(1)` here would disagree.
"""
- return _hash_keys(_extract_leaf_shape_keys(filters, mode=_LeafShapeMode.FULL))
+ if not isinstance(node, dict):
+ return None
+
+ node_type = node.get("type")
+ if node_type in ("AND", "OR"):
+ unique: dict[str, list[object]] = {}
+ for child in node.get("values") or []:
+ if (rendered := _render_definition(child)) is not None:
+ unique.setdefault(_canonical(rendered), rendered)
+ # Rust retains empty groups and excludes their cohort from realtime evaluation.
+ children = [unique[key] for key in sorted(unique)]
+ if len(children) == 1:
+ return children[0]
+ return [node_type, children]
+
+ negation = node.get("negation") is True
+ if node_type == "behavioral":
+ return [
+ "behavioral",
+ *behavioral_leaf_key(
+ condition_hash=node.get("conditionHash"),
+ value=node.get("value"),
+ time_value=node.get("time_value"),
+ time_interval=node.get("time_interval"),
+ explicit_datetime=node.get("explicit_datetime"),
+ explicit_datetime_to=node.get("explicit_datetime_to"),
+ operator=node.get("operator"),
+ operator_value=node.get("operator_value"),
+ ),
+ negation,
+ ]
+ if node_type == "person":
+ return ["person", node.get("conditionHash"), negation]
+ if node_type == "cohort":
+ return ["cohort", node.get("value"), negation or node.get("operator") == "not_in"]
+ return [node_type]
+
+
+def extract_leaf_shape_hash(filters: dict | None) -> str:
+ """Fingerprint the whole cohort definition: every leaf, its negation, and the AND/OR tree it
+ sits in, order-insensitive.
+
+ This is the only fingerprint that sees composition. The two kind hashes below key on leaf
+ identity alone, so an edit that only moves AND/OR, negation, or a nested-cohort reference moves
+ this hash and neither of theirs. Saves and readiness stamps use `FilterShapeHashes` to agree
+ on which kind must repair a definition change that no leaf hash would trigger.
+ Keep the leaf fields in lockstep with Rust: behavioral leaves via `BehavioralLeafKey`; person
+ conditionHash; cohort value; the negation rules in `_render_definition`.
+ """
+ if not filters or not (properties := filters.get("properties")):
+ return ""
+
+ rendered = _render_definition(properties)
+ if rendered is None:
+ return ""
+ return hashlib.sha256(_canonical(rendered).encode()).hexdigest()
def extract_behavioral_leaf_shape_hash(filters: dict | None) -> str:
@@ -138,3 +207,39 @@ def extract_behavioral_leaf_shape_hash(filters: dict | None) -> str:
def extract_person_leaf_shape_hash(filters: dict | None) -> str:
"""Fingerprint only person-property condition hashes."""
return _hash_keys(_extract_leaf_shape_keys(filters, mode=_LeafShapeMode.PERSON_ONLY))
+
+
+@frozen
+class FilterShapeHashes:
+ definition: str | None
+ behavioral: str | None
+ person: str | None
+
+ @classmethod
+ def from_filters(cls, filters: dict | None) -> "FilterShapeHashes":
+ return cls(
+ definition=extract_leaf_shape_hash(filters),
+ behavioral=extract_behavioral_leaf_shape_hash(filters),
+ person=extract_person_leaf_shape_hash(filters),
+ )
+
+ def composition_repair_kind(
+ self, previous: "FilterShapeHashes", filters: dict | None
+ ) -> Literal["behavioral", "person_property"] | None:
+ if previous.definition is None or previous.definition == self.definition:
+ return None
+
+ leaf_types = {leaf.get("type") for leaf in walk_filter_leaves((filters or {}).get("properties"))}
+ person_backfillable = bool(self.person) and "person_metadata" not in leaf_types
+ # Match the run creators: an unhashed behavioral leaf can trigger a run, but person metadata cannot.
+ if previous.behavioral != self.behavioral and "behavioral" in leaf_types:
+ return None
+ if previous.person != self.person and person_backfillable:
+ return None
+
+ # Either kind reconciles the whole tree. Prefer the events stamp used by strict flag routing.
+ if self.behavioral:
+ return "behavioral"
+ if person_backfillable:
+ return "person_property"
+ return None
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index 98f3def4faaf..e2930042334e 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -27,33 +27,46 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.on_commit = on_commit_patch.start()
self.addCleanup(on_commit_patch.stop)
- def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:
- values = [
- {
+ def _filters(
+ self,
+ window_days: int | None,
+ *,
+ person_hash: str | None = None,
+ extra_person_hash: str | None = None,
+ behavioral_hash: str | None = "stable-condition-hash",
+ group_type: str = "AND",
+ ) -> dict:
+ values = []
+ if window_days is not None:
+ behavioral = {
"type": "behavioral",
"key": "$pageview",
"event_type": "events",
"value": "performed_event_multiple",
- "conditionHash": "stable-condition-hash",
"time_value": window_days,
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
}
- ]
- if person_hash is not None:
- values.append(
- {
- "type": "person",
- "key": "email",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": person_hash,
- }
- )
- return {"properties": {"type": "AND", "values": values}}
-
- def _cohort(self, window_days: int = 7, *, person_hash: str | None = None) -> Cohort:
+ # Absent rather than null, which is how the API stores a leaf whose bytecode generation
+ # failed: the cohort keeps `cohort_type` realtime and the leaf keeps no condition hash.
+ if behavioral_hash is not None:
+ behavioral["conditionHash"] = behavioral_hash
+ values.append(behavioral)
+ for leaf_hash in (person_hash, extra_person_hash):
+ if leaf_hash is not None:
+ values.append(
+ {
+ "type": "person",
+ "key": "email",
+ "value": ["[email protected]"],
+ "operator": "exact",
+ "conditionHash": leaf_hash,
+ }
+ )
+ return {"properties": {"type": group_type, "values": values}}
+
+ def _cohort(self, window_days: int | None = 7, *, person_hash: str | None = None) -> Cohort:
return Cohort.objects.create(
team=self.team,
cohort_type=CohortType.REALTIME,
@@ -312,6 +325,211 @@ class TestBehavioralBackfillDependencies(BaseTest):
self._assert_one_debounced_task_per_kind(enqueue, redis, cohort, "cohort_edited")
+ def _assert_one_debounced_task(self, enqueue, redis, cohort: Cohort, kind: CohortBackfillKind) -> None:
+ enqueue.assert_called_once_with(
+ args=[self.team.id, cohort.id, "cohort_edited", kind],
+ countdown=300,
+ )
+ redis.set.assert_called_once_with(f"cohort_backfill_{kind.value}_pending:{cohort.id}", 1, nx=True, ex=300)
+
+ @parameterized.expand(
+ [
+ (
+ "group_operator_on_mixed",
+ {"window_days": 7, "person_hash": "person-a"},
+ {"window_days": 7, "person_hash": "person-a", "group_type": "OR"},
+ CohortBackfillKind.BEHAVIORAL,
+ ),
+ (
+ "group_operator_on_person_only",
+ {"window_days": None, "person_hash": "person-a", "extra_person_hash": "person-b"},
+ {
+ "window_days": None,
+ "person_hash": "person-a",
+ "extra_person_hash": "person-b",
+ "group_type": "OR",
+ },
+ CohortBackfillKind.PERSON_PROPERTY,
+ ),
+ (
+ "last_person_leaf_removed",
+ {"window_days": 7, "person_hash": "person-a"},
+ {"window_days": 7},
+ CohortBackfillKind.BEHAVIORAL,
+ ),
+ (
+ "last_behavioral_leaf_removed",
+ {"window_days": 7, "person_hash": "person-a"},
+ {"window_days": None, "person_hash": "person-a"},
+ CohortBackfillKind.PERSON_PROPERTY,
+ ),
+ ]
+ )
+ def test_edit_no_leaf_set_run_repairs_enqueues_one_runnable_kind(
+ self, _name: str, before: dict, after: dict, kind: CohortBackfillKind
+ ) -> None:
+ # Reconcile evaluates the whole tree whichever kind it runs for, so one run repairs the
+ # cohort. Removing the last person leaf is in this set because the person run its hash change
+ # would ask for is refused: the cohort has no person leaf left to pin.
+ cohort = Cohort.objects.create(team=self.team, cohort_type=CohortType.REALTIME, filters=self._filters(**before))
+ redis = self._redis()
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
+ ):
+ cohort.filters = self._filters(**after)
+ cohort.save()
+
+ self._assert_one_debounced_task(enqueue, redis, cohort, kind)
+
+ @parameterized.expand([("group_operator", None), ("empty_and", "AND"), ("empty_or", "OR")])
+ def test_composition_edit_nulls_the_events_stamp_and_moves_no_kind_hash(
+ self, _name: str, empty_group: str | None
+ ) -> None:
+ cohort = self._cohort(7, person_hash="person-a")
+ old_behavioral_hash = cohort.behavioral_filters_shape_hash
+ old_person_hash = cohort.person_filters_shape_hash
+ ready_at = timezone.now()
+ Cohort.objects.filter(id=cohort.id).update(
+ last_backfill_events_at=ready_at,
+ last_backfill_person_properties_at=ready_at,
+ last_realtime_cohort_calculation_at=ready_at,
+ )
+ cohort.refresh_from_db()
+ before = self._orphan_count()
+
+ # A partial save, because `resave_cohorts` re-drives the fleet with a frozen field set. The
+ # stamp this edit nulls has to be added to that set, or the null is decided and never written.
+ if empty_group is None:
+ cohort.filters = self._filters(7, person_hash="person-a", group_type="OR")
+ else:
+ assert cohort.filters is not None
+ cohort.filters["properties"]["values"].append({"type": empty_group, "values": []})
+ cohort.save(update_fields=["filters"])
+
+ cohort.refresh_from_db()
+ # Runs in flight pin these columns and the processor, the seeder and the finalizer compare
+ # them, so the replacement run must pin what the superseded one did.
+ self.assertEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)
+ self.assertEqual(cohort.person_filters_shape_hash, old_person_hash)
+ self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertEqual(cohort.last_backfill_person_properties_at, ready_at)
+ self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
+ self.assertEqual(self._orphan_count(), before + 1)
+
+ def test_adding_the_first_person_leaf_enqueues_only_the_person_run(self) -> None:
+ # The person run already reconciles the whole cohort, so the composition rule must not add a
+ # behavioral history replay to an edit that triggers a run on its own.
+ cohort = self._cohort(7)
+ ready_at = timezone.now()
+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)
+ cohort.refresh_from_db()
+ redis = self._redis()
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
+ ):
+ cohort.filters = self._filters(7, person_hash="person-a")
+ cohort.save()
+
+ self._assert_one_debounced_task(enqueue, redis, cohort, CohortBackfillKind.PERSON_PROPERTY)
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.last_backfill_events_at, ready_at)
+
+ def test_behavioral_leaf_losing_its_hash_enqueues_only_the_behavioral_run(self) -> None:
+ # The behavioral receiver creates a run for any behavioral leaf, hashed or not, so this edit
+ # already triggers one and the composition rule must not add a person run beside it. The API
+ # reaches this state by storing the raw filters when filter validation raises, which leaves
+ # the cohort realtime with a leaf that never got a condition hash.
+ cohort = self._cohort(7, person_hash="person-a")
+ redis = self._redis()
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
+ ):
+ cohort.filters = self._filters(7, person_hash="person-a", behavioral_hash=None)
+ cohort.save()
+
+ self._assert_one_debounced_task(enqueue, redis, cohort, CohortBackfillKind.BEHAVIORAL)
+
+ @parameterized.expand([("stored_hashes", False), ("null_hashes", True)])
+ def test_malformed_persisted_filters_still_invalidate_on_a_leaf_edit(self, _name: str, null_hashes: bool) -> None:
+ # The composition signal reads the persisted filters, which the leaf-shape comparison never
+ # had to parse. A row the renderer cannot walk must cost only that signal: the method
+ # swallows its own exceptions, so letting one escape here would silently turn off every
+ # invalidation for this cohort, including the leaf edits that worked before the rule existed.
+ cohort = self._cohort(7, person_hash="person-a")
+ Cohort.objects.filter(id=cohort.id).update(
+ filters={"properties": {"type": "AND", "values": 3}},
+ behavioral_filters_shape_hash=None if null_hashes else cohort.behavioral_filters_shape_hash,
+ person_filters_shape_hash=None if null_hashes else cohort.person_filters_shape_hash,
+ last_backfill_events_at=timezone.now(),
+ last_backfill_person_properties_at=timezone.now(),
+ )
+ cohort.refresh_from_db()
+
+ cohort.filters = self._filters(30, person_hash="person-b")
+ cohort.save()
+
+ cohort.refresh_from_db()
+ self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(cohort.last_backfill_person_properties_at)
+ self.assertTrue(cohort.behavioral_filters_shape_hash)
+ self.assertTrue(cohort.person_filters_shape_hash)
+
+ @parameterized.expand([("legacy_hash", True), ("current_hash", False)])
+ def test_save_with_unchanged_filters_enqueues_nothing(self, _name: str, legacy_hash: bool) -> None:
+ # Every stored full hash was computed from the leaf set alone before the fingerprint existed.
+ # Reading the previous definition from that column rather than from the persisted filters
+ # would turn each cohort's first save after the deploy into an edit, and the fleet would
+ # replay its history for nothing.
+ cohort = self._cohort(7, person_hash="person-a")
+ old_behavioral_hash = cohort.behavioral_filters_shape_hash
+ old_person_hash = cohort.person_filters_shape_hash
+ ready_at = timezone.now()
+ Cohort.objects.filter(id=cohort.id).update(
+ filters_shape_hash="a-hash-written-under-the-old-rule" if legacy_hash else cohort.filters_shape_hash,
+ last_backfill_events_at=ready_at,
+ last_backfill_person_properties_at=ready_at,
+ last_realtime_cohort_calculation_at=ready_at,
+ )
+ cohort.refresh_from_db()
+ redis = self._redis()
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
+ ):
+ cohort.name = "renamed"
+ cohort.save()
+
+ enqueue.assert_not_called()
+ redis.set.assert_not_called()
+ cohort.refresh_from_db()
+ self.assertEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)
+ self.assertEqual(cohort.person_filters_shape_hash, old_person_hash)
+ self.assertEqual(cohort.last_backfill_events_at, ready_at)
+ self.assertEqual(cohort.last_backfill_person_properties_at, ready_at)
+ self.assertEqual(cohort.last_realtime_cohort_calculation_at, ready_at)
+
+ def test_stale_instance_restoring_definition_invalidates_readiness(self) -> None:
+ cohort = self._cohort(7, person_hash="person-a")
+ stale = Cohort.objects.get(id=cohort.id)
+ cohort.filters = self._filters(7, person_hash="person-a", group_type="OR")
+ cohort.save(update_fields=["filters"])
+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())
+
+ stale.name = "renamed"
+ stale.save()
+
+ stale.refresh_from_db()
+ assert stale.filters is not None
+ self.assertEqual(stale.filters["properties"]["type"], "AND")
+ self.assertIsNone(stale.last_backfill_events_at)
+
@parameterized.expand(TRIGGER_KINDS)
def test_two_edits_share_one_debounce_key(self, _name: str, kind: CohortBackfillKind, edits) -> None:
cohort = self._cohort(7, person_hash="person-a")
diff --git a/products/cohorts/backend/models/test/test_leaf_shape.py b/products/cohorts/backend/models/test/test_leaf_shape.py
index 4ebe6e4ece9a..511bbcf88794 100644
--- a/products/cohorts/backend/models/test/test_leaf_shape.py
+++ b/products/cohorts/backend/models/test/test_leaf_shape.py
@@ -10,23 +10,37 @@ from products.cohorts.backend.models.leaf_shape import (
)
+def _behavioral_leaf(**overrides: object) -> dict:
+ leaf = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "value": "performed_event_multiple",
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": "cd0863735b457170",
+ "operator": "gte",
+ "operator_value": 3,
+ }
+ leaf.update(overrides)
+ return leaf
+
+
+def _group(group_type: str, *values: dict) -> dict:
+ return {"type": group_type, "values": list(values)}
+
+
+_BEHAVIORAL = _behavioral_leaf()
+_OTHER_BEHAVIORAL = _behavioral_leaf(conditionHash="ffffffffffffffff")
+_PERSON = {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}
+_COHORT_REF = {"type": "cohort", "value": 42}
+
+
class TestLeafShape(SimpleTestCase):
def _filters(self, *leaves: dict) -> dict:
return {"properties": {"type": "AND", "values": list(leaves)}}
def _behavioral(self, **overrides: object) -> dict:
- leaf = {
- "type": "behavioral",
- "key": "$pageview",
- "value": "performed_event_multiple",
- "time_value": 7,
- "time_interval": "day",
- "conditionHash": "cd0863735b457170",
- "operator": "gte",
- "operator_value": 3,
- }
- leaf.update(overrides)
- return leaf
+ return _behavioral_leaf(**overrides)
@parameterized.expand(
[
@@ -52,12 +66,94 @@ class TestLeafShape(SimpleTestCase):
extract_behavioral_leaf_shape_hash(changed),
)
- def test_behavioral_negation_and_leaf_order_do_not_change_the_hash(self) -> None:
- person = {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}
+ @parameterized.expand(
+ [
+ (
+ "root_group_operator",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("OR", _BEHAVIORAL, _PERSON)},
+ ),
+ (
+ "inner_group_operator",
+ {"properties": _group("AND", _group("AND", _BEHAVIORAL, _PERSON), _COHORT_REF)},
+ {"properties": _group("AND", _group("OR", _BEHAVIORAL, _PERSON), _COHORT_REF)},
+ ),
+ (
+ "behavioral_negation",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", {**_BEHAVIORAL, "negation": True}, _PERSON)},
+ ),
+ (
+ "person_negation",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", _BEHAVIORAL, {**_PERSON, "negation": True})},
+ ),
+ (
+ "cohort_reference_not_in",
+ {"properties": _group("AND", _BEHAVIORAL, _COHORT_REF)},
+ {"properties": _group("AND", _BEHAVIORAL, {**_COHORT_REF, "operator": "not_in"})},
+ ),
+ (
+ "leaf_moved_between_groups",
+ {"properties": _group("OR", _group("AND", _BEHAVIORAL, _PERSON), _group("AND", _OTHER_BEHAVIORAL))},
+ {"properties": _group("OR", _group("AND", _BEHAVIORAL), _group("AND", _OTHER_BEHAVIORAL, _PERSON))},
+ ),
+ (
+ "empty_and_group",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON, _group("AND"))},
+ ),
+ (
+ "empty_or_group",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON, _group("OR"))},
+ ),
+ ]
+ )
+ def test_composition_edits_move_only_the_full_hash(self, _name: str, before: dict, after: dict) -> None:
+ self.assertNotEqual(extract_leaf_shape_hash(before), extract_leaf_shape_hash(after))
self.assertEqual(
- extract_leaf_shape_hash(self._filters(self._behavioral(negation=False), person)),
- extract_leaf_shape_hash(self._filters(person, self._behavioral(negation=True))),
+ extract_behavioral_leaf_shape_hash(before),
+ extract_behavioral_leaf_shape_hash(after),
)
+ self.assertEqual(extract_person_leaf_shape_hash(before), extract_person_leaf_shape_hash(after))
+
+ @parameterized.expand(
+ [
+ (
+ "leaf_order",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", _PERSON, _BEHAVIORAL)},
+ ),
+ (
+ "single_child_wrapper",
+ {"properties": _group("AND", _BEHAVIORAL)},
+ {"properties": _group("OR", _group("AND", _group("OR", _BEHAVIORAL)))},
+ ),
+ (
+ "duplicate_leaf",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON, _PERSON)},
+ ),
+ (
+ "negation_absent_or_false",
+ {"properties": _group("AND", _BEHAVIORAL, _PERSON)},
+ {"properties": _group("AND", {**_BEHAVIORAL, "negation": False}, {**_PERSON, "negation": False})},
+ ),
+ (
+ "condition_hash_absent_or_null",
+ {"properties": _group("AND", _BEHAVIORAL, {"type": "person", "key": "email"})},
+ {"properties": _group("AND", _BEHAVIORAL, {"type": "person", "key": "email", "conditionHash": None})},
+ ),
+ ]
+ )
+ def test_semantically_null_edits_do_not_move_the_full_hash(self, _name: str, before: dict, after: dict) -> None:
+ # AND and OR are commutative and idempotent, and a group of one operand is that operand, so
+ # these edits describe the same cohort. Each one would otherwise fire a history replay for
+ # a definition that did not change. The last two are what the API's own re-validation does
+ # to an untouched definition, so they decide whether a plain rename fires a run.
+ self.assertNotEqual(extract_leaf_shape_hash(before), "")
+ self.assertEqual(extract_leaf_shape_hash(before), extract_leaf_shape_hash(after))
def test_person_and_cohort_reference_fields_are_included(self) -> None:
self.assertNotEqual(
@@ -156,5 +252,9 @@ class TestLeafShape(SimpleTestCase):
def test_empty_or_null_group_values_are_safe(self) -> None:
self.assertEqual(extract_leaf_shape_hash(None), "")
- self.assertEqual(extract_leaf_shape_hash(self._filters()), "")
+ self.assertNotEqual(extract_leaf_shape_hash(self._filters()), "")
+ self.assertEqual(
+ extract_leaf_shape_hash(self._filters()),
+ extract_leaf_shape_hash({"properties": {"type": "AND", "values": None}}),
+ )
self.assertEqual(list(walk_filter_leaves({"type": "AND", "values": None})), [])