: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): implement backfill coordination foundation (#70613)
Matheus Batista99a1bf368415
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 15096ac5f95f..270db163613d 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -87,6 +87,9 @@ rules:|CodeWorkflowConfig|CodeWorkstream|Cohort+ |CohortBackfillChunk+ |CohortBackfillRun+ |CohortBackfillRunCohort|Comment|Conversation|ConversationRestoreToken@@ -384,6 +387,9 @@ rules:|CodeWorkflowConfig|CodeWorkstream|Cohort+ |CohortBackfillChunk+ |CohortBackfillRun+ |CohortBackfillRunCohort|Comment|Conversation|ConversationRestoreTokendiff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex c8bffbc288b2..163fd037f9fc 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -16,10 +16,14 @@# ---# name: TestVisitorFieldSnapshots.test_excluded_fields_Cohortlist([+ 'behavioral_filters_shape_hash','count','errors_calculating',+ 'filters_shape_hash','groups','is_calculating',+ 'last_backfill_events_at',+ 'last_backfill_person_properties_at','last_calculation','last_error_at','pending_version',@@ -151,8 +155,6 @@'filters','is_static','kind',- 'last_backfill_events_at',- 'last_backfill_person_properties_at','last_calculation_duration_ms','last_realtime_cohort_calculation_at','name',@@ -494,9 +496,13 @@'_insert_batch_via_personhog','_insert_resolved_batch','_insert_users_list_with_batching',+ '_maintain_behavioral_shape','_meta','_safe_reset_calculating_state','_safe_save_cohort_state',+ 'backfill_participations',+ 'backfill_runs',+ 'behavioral_filters_shape_hash','calculate_people_ch','cohortcalculationhistory_set','cohortpeople_set',@@ -506,6 +512,7 @@'errors_calculating','errortrackingissuecohort_set','experiment_set',+ 'filters_shape_hash','get_analytics_metadata','get_cohort_type_display','get_file_system_representation',@@ -520,6 +527,8 @@'insert_users_list_by_uuid_into_pg_only','is_calculating','is_flag_compatible',+ 'last_backfill_events_at',+ 'last_backfill_person_properties_at','last_calculation','last_error_at','objects',@@ -527,6 +536,7 @@'people','properties','remove_user_by_uuid',+ 'save','team_id','to_dict','version',diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.pyindex 501a1d5838ee..6661175229da 100644--- a/posthog/models/resource_transfer/visitors/cohort.py+++ b/posthog/models/resource_transfer/visitors/cohort.py@@ -21,6 +21,10 @@ class CohortVisitor("last_calculation","errors_calculating","last_error_at",+ "last_backfill_events_at",+ "last_backfill_person_properties_at",+ "filters_shape_hash",+ "behavioral_filters_shape_hash","count","version","pending_version",diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex b97c0563e1d2..cf5f9420a08c 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -26,6 +26,7 @@ from posthog.settings.agents import *from posthog.settings.async_migrations import *from posthog.settings.batch_exports import *from posthog.settings.celery import *+from posthog.settings.cohorts import *from posthog.settings.kafka import *from posthog.settings.data_stores import *from posthog.settings.dagster import *diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.pynew file mode 100644index 000000000000..116506d5db58--- /dev/null+++ b/posthog/settings/cohorts.py@@ -0,0 +1,13 @@+import os++from posthog.settings.utils import get_from_env, str_to_bool++# Off by default ("none"); enable per environment via the env override+# A set-but-empty value survives as "", which the parser reads as "all teams".+REALTIME_COHORT_TEAM_ALLOWLIST: str = os.getenv("REALTIME_COHORT_TEAM_ALLOWLIST", "none")+BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED: bool = get_from_env(+ "BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED", False, type_cast=str_to_bool+)+BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED: bool = get_from_env(+ "BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED", False, type_cast=str_to_bool+)diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex 78394acc1c2e..0afc6d01df86 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -28,6 +28,7 @@ from posthog.models.user import Userfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue+from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohortfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.cohorts.backend.models.util import (@@ -868,3 +869,34 @@ def trigger_cohort_backfill_task(team_id: int, cohort_id: int) -> None:error=str(e),)raise+++@shared_task(ignore_result=True, max_retries=3)+def trigger_cohort_events_backfill_task(team_id: int, cohort_id: int, trigger_kind: str) -> None:+ try:+ run = create_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)+ if run is None:+ logger.info(+ "skipping_cohort_events_backfill_task",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ )+ return+ logger.info(+ "created_cohort_events_backfill_run",+ run_id=str(run.id),+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ status=run.status,+ )+ except Exception as error:+ logger.exception(+ "failed_to_trigger_cohort_events_backfill_task",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ error=str(error),+ )+ raisediff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex b793899fc320..e11fd18c0aee 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -19,6 +19,7 @@'posthog.tasks.calculate_cohort.insert_cohort_from_filters','posthog.tasks.calculate_cohort.insert_cohort_from_query','posthog.tasks.calculate_cohort.trigger_cohort_backfill_task',+ 'posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task','posthog.tasks.demo_create_data.create_data_for_demo_team','posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change','posthog.tasks.email.login_from_new_device_notification',diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex fcd318b3d6aa..213123f36c56 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -145,6 +145,7 @@ post_save:products.cdp.backend.models.plugin.plugin_attachement_reload_neededpost_save:products.cdp.backend.models.plugin.plugin_config_reload_neededpost_save:products.cdp.backend.models.plugin.plugin_reload_neededpost_save:products.cdp.backend.models.plugin.preinstall_plugins_for_new_organization+post_save:products.cohorts.backend.models.dependencies.cohort_behavioral_shape_changed_backfillpost_save:products.cohorts.backend.models.dependencies.cohort_changedpost_save:products.cohorts.backend.models.dependencies.cohort_conditions_changed_backfillpost_save:products.conversations.backend.signals.emit_ticket_created_eventdiff --git a/products/cohorts/backend/backfill/__init__.py b/products/cohorts/backend/backfill/__init__.pynew file mode 100644index 000000000000..8d1646ed0b3f--- /dev/null+++ b/products/cohorts/backend/backfill/__init__.py@@ -0,0 +1,19 @@+from products.cohorts.backend.backfill.pinning import derive_window_days, pin_conditions_for_cohorts+from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash, stamp_events_readiness+from products.cohorts.backend.backfill.runs import (+ check_run_preconditions,+ create_backfill_run_for_cohort,+ create_team_backfill_run,+ supersede_active_runs,+)++__all__ = [+ "check_run_preconditions",+ "create_backfill_run_for_cohort",+ "create_team_backfill_run",+ "derive_window_days",+ "ensure_filters_shape_hash",+ "pin_conditions_for_cohorts",+ "stamp_events_readiness",+ "supersede_active_runs",+]diff --git a/products/cohorts/backend/backfill/pinning.py b/products/cohorts/backend/backfill/pinning.pynew file mode 100644index 000000000000..d282e9402a99--- /dev/null+++ b/products/cohorts/backend/backfill/pinning.py@@ -0,0 +1,56 @@+from collections.abc import Iterable+from typing import Any++from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.leaf_shape import walk_filter_leaves++_INTERVAL_DAYS = {"day": 1, "week": 7, "month": 30, "year": 365}+++def derive_window_days(time_value: object, time_interval: object) -> int:+ if not isinstance(time_interval, str):+ return 0+ if not isinstance(time_value, (int, float, str)):+ return 0+ try:+ normalized_time_value = max(0, int(time_value))+ except (TypeError, ValueError):+ return 0+ return normalized_time_value * _INTERVAL_DAYS.get(time_interval, 0)+++def pin_conditions_for_cohorts(cohorts: Iterable[Cohort]) -> tuple[dict[str, Any], list[str]]:+ conditions: list[dict[str, Any]] = []+ event_names: set[str] = set()++ for cohort in sorted(cohorts, key=lambda item: item.id):+ properties = (cohort.filters or {}).get("properties")+ for leaf in walk_filter_leaves(properties):+ if leaf.get("type") != "behavioral" or leaf.get("conditionHash") is None:+ continue++ event_key = leaf.get("key")+ is_action = leaf.get("event_type") == "actions" or isinstance(event_key, int)+ event_name = event_key if isinstance(event_key, str) and not is_action else None+ if event_name is not None:+ event_names.add(event_name)++ conditions.append(+ {+ "cohort_id": cohort.id,+ "condition_hash": leaf.get("conditionHash"),+ "value": leaf.get("value"),+ "time_value": leaf.get("time_value"),+ "time_interval": leaf.get("time_interval"),+ "explicit_datetime": leaf.get("explicit_datetime"),+ "explicit_datetime_to": leaf.get("explicit_datetime_to"),+ "operator": leaf.get("operator"),+ "operator_value": leaf.get("operator_value"),+ "window_days": derive_window_days(leaf.get("time_value"), leaf.get("time_interval")),+ "event_name": event_name,+ "is_action": is_action,+ }+ )++ conditions.sort(key=lambda item: (item["cohort_id"], item["condition_hash"], item["event_name"] or ""))+ return {"schema_version": 1, "conditions": conditions}, sorted(event_names)diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.pynew file mode 100644index 000000000000..d13c632e4222--- /dev/null+++ b/products/cohorts/backend/backfill/readiness.py@@ -0,0 +1,98 @@+from django.db.models.functions import Now++import structlog++from products.cohorts.backend.models.backfill import (+ CohortBackfillRun,+ CohortBackfillRunCohort,+ CohortBackfillRunStatus,+ CohortBackfillScope,+)+from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.leaf_shape import extract_behavioral_leaf_shape_hash, extract_leaf_shape_hash++logger = structlog.get_logger(__name__)+++def ensure_filters_shape_hash(cohort: Cohort) -> str:+ current_hash = cohort.__dict__.get("filters_shape_hash")+ if current_hash is None:+ shape_hash = extract_leaf_shape_hash(cohort.filters)+ updated = Cohort.objects.filter(id=cohort.id, team_id=cohort.team_id, filters_shape_hash__isnull=True).update(+ filters_shape_hash=shape_hash+ )+ if updated:+ cohort.filters_shape_hash = shape_hash+ else:+ cohort.refresh_from_db(fields=["filters_shape_hash"])++ if cohort.__dict__.get("behavioral_filters_shape_hash") is None:+ behavioral_shape_hash = extract_behavioral_leaf_shape_hash(cohort.filters)+ updated = Cohort.objects.filter(+ id=cohort.id,+ team_id=cohort.team_id,+ behavioral_filters_shape_hash__isnull=True,+ ).update(behavioral_filters_shape_hash=behavioral_shape_hash)+ if updated:+ cohort.behavioral_filters_shape_hash = behavioral_shape_hash+ else:+ cohort.refresh_from_db(fields=["behavioral_filters_shape_hash"])++ return cohort.filters_shape_hash or ""+++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_behavioral_shape``).+ 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.++ This update intentionally bypasses signals. B5 must explicitly invalidate feature-flag and+ behavioral-cohort caches after a successful stamp.+ """+ participation = CohortBackfillRunCohort.objects.for_team(run.team_id).get(run_id=run.id, cohort_id=cohort_id)+ updated = Cohort.objects.filter(+ id=cohort_id,+ team_id=run.team_id,+ behavioral_filters_shape_hash=participation.behavioral_filters_shape_hash,+ last_backfill_events_at__isnull=True,+ ).update(last_backfill_events_at=Now())+ if updated:+ CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(+ stamped_at=Now(), error=""+ )+ return True++ current_readiness = (+ Cohort.objects.filter(id=cohort_id, team_id=run.team_id)+ .values_list("behavioral_filters_shape_hash", "last_backfill_events_at")+ .first()+ )+ if (+ current_readiness is not None+ and current_readiness[0] == participation.behavioral_filters_shape_hash+ and current_readiness[1] is not None+ ):+ CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(+ stamped_at=Now(), error=""+ )+ return True++ error = "Cohort definition changed before readiness was stamped"+ CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(+ superseded_at=Now(), error=error+ )+ if run.scope == CohortBackfillScope.COHORT:+ CohortBackfillRun.objects.for_team(run.team_id).filter(+ id=run.id,+ status__in=(+ CohortBackfillRunStatus.AWAITING_BOUNDARY,+ CohortBackfillRunStatus.BLOCKED,+ CohortBackfillRunStatus.SEEDING,+ CohortBackfillRunStatus.RECONCILING,+ ),+ ).update(status=CohortBackfillRunStatus.SUPERSEDED, finished_at=Now(), error=error)+ logger.info("cohort_backfill_readiness_stamp_superseded", run_id=str(run.id), cohort_id=cohort_id)+ return Falsediff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.pynew file mode 100644index 000000000000..f0802dd1eb38--- /dev/null+++ b/products/cohorts/backend/backfill/runs.py@@ -0,0 +1,208 @@+from collections.abc import Iterable+from typing import Any++from django.conf import settings+from django.db import transaction+from django.db.models.functions import Now++from posthog.models.team.team import Team++from products.cohorts.backend.backfill.pinning import pin_conditions_for_cohorts+from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash+from products.cohorts.backend.models.backfill import (+ ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ CohortBackfillKind,+ CohortBackfillRun,+ CohortBackfillRunCohort,+ CohortBackfillRunStatus,+ CohortBackfillScope,+)+from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.leaf_shape import walk_filter_leaves+from products.cohorts.backend.realtime_teams import is_realtime_cohort_team+++def check_run_preconditions() -> tuple[dict[str, Any], list[str]]:+ preconditions = {+ "merge_gate_attested": settings.BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED,+ "durability_attested": settings.BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED,+ "catalog_consume_floor": "not_implemented_b8",+ }+ missing = [+ name+ for name, met in (+ ("merge gate", preconditions["merge_gate_attested"]),+ ("processor durability", preconditions["durability_attested"]),+ )+ if not met+ ]+ return preconditions, missing+++def _has_behavioral_filters(cohort: Cohort) -> bool:+ properties = (cohort.filters or {}).get("properties")+ return any(leaf.get("type") == "behavioral" for leaf in walk_filter_leaves(properties))+++def _run_status(preconditions_missing: list[str]) -> tuple[str, str]:+ if preconditions_missing:+ reason = f"Missing operator attestations: {', '.join(preconditions_missing)}"+ return CohortBackfillRunStatus.BLOCKED, reason+ return CohortBackfillRunStatus.AWAITING_BOUNDARY, ""+++def _pinned_payload(cohorts: Iterable[Cohort]) -> dict[str, Any]:+ pinned, event_names = pin_conditions_for_cohorts(cohorts)+ return {**pinned, "event_names": event_names}+++def _active_participation_cohort_ids(team_id: int, cohort_ids: Iterable[int]) -> set[int]:+ return set(+ CohortBackfillRunCohort.objects.for_team(team_id)+ .filter(+ cohort_id__in=cohort_ids,+ superseded_at__isnull=True,+ run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ )+ .values_list("cohort_id", flat=True)+ )+++def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: str) -> CohortBackfillRun | None:+ if not is_realtime_cohort_team(team_id):+ return None++ with transaction.atomic():+ cohort = (+ Cohort.objects.select_for_update(of=("self",))+ .select_related("team")+ .filter(id=cohort_id, team_id=team_id)+ .first()+ )+ if (+ cohort is None+ or cohort.cohort_type != CohortType.REALTIME+ or cohort.is_static+ or cohort.deleted+ or not _has_behavioral_filters(cohort)+ ):+ return None+ if _active_participation_cohort_ids(team_id, [cohort_id]):+ return None++ filters_shape_hash = ensure_filters_shape_hash(cohort)+ behavioral_filters_shape_hash = cohort.behavioral_filters_shape_hash or ""+ preconditions, missing = check_run_preconditions()+ status, blocked_reason = _run_status(missing)+ run = CohortBackfillRun.objects.for_team(team_id).create(+ team_id=team_id,+ cohort=cohort,+ backfill_kind=CohortBackfillKind.BEHAVIORAL,+ trigger_kind=trigger_kind,+ scope=CohortBackfillScope.COHORT,+ status=status,+ timezone=cohort.team.timezone,+ pinned=_pinned_payload([cohort]),+ preconditions=preconditions,+ blocked_reason=blocked_reason,+ )+ CohortBackfillRunCohort.objects.for_team(team_id).create(+ run=run,+ team_id=team_id,+ cohort=cohort,+ filters_shape_hash=filters_shape_hash,+ behavioral_filters_shape_hash=behavioral_filters_shape_hash,+ pinned_filters=cohort.filters,+ )+ return run+++def create_team_backfill_run(+ team_id: int,+ trigger_kind: str,+ cohort_ids: Iterable[int] | None = None,+ created_by_id: int | None = None,+) -> CohortBackfillRun:+ if not is_realtime_cohort_team(team_id):+ raise ValueError(f"Team {team_id} is not in the realtime cohort allowlist")++ requested_ids = set(cohort_ids) if cohort_ids is not None else None+ with transaction.atomic():+ team = Team.objects.get(id=team_id)+ queryset = Cohort.objects.select_for_update(of=("self",)).filter(+ team_id=team_id,+ cohort_type=CohortType.REALTIME,+ is_static=False,+ deleted=False,+ )+ if requested_ids is not None:+ queryset = queryset.filter(id__in=requested_ids)+ cohorts = [cohort for cohort in queryset.order_by("id") if _has_behavioral_filters(cohort)]+ if requested_ids is not None and {cohort.id for cohort in cohorts} != requested_ids:+ invalid_ids = sorted(requested_ids - {cohort.id for cohort in cohorts})+ raise ValueError(f"Cohorts are not eligible realtime behavioral cohorts: {invalid_ids}")+ if not cohorts:+ raise ValueError(f"Team {team_id} has no eligible realtime behavioral cohorts")+ conflicting_ids = _active_participation_cohort_ids(team_id, [cohort.id for cohort in cohorts])+ if conflicting_ids:+ raise ValueError(f"Cohorts already have active backfill runs: {sorted(conflicting_ids)}")++ hashes: dict[int, str] = {}+ behavioral_hashes: dict[int, str] = {}+ for cohort in cohorts:+ hashes[cohort.id] = ensure_filters_shape_hash(cohort)+ behavioral_hashes[cohort.id] = cohort.behavioral_filters_shape_hash or ""+ preconditions, missing = check_run_preconditions()+ status, blocked_reason = _run_status(missing)+ run = CohortBackfillRun.objects.for_team(team_id).create(+ team_id=team_id,+ created_by_id=created_by_id,+ backfill_kind=CohortBackfillKind.BEHAVIORAL,+ trigger_kind=trigger_kind,+ scope=CohortBackfillScope.TEAM,+ status=status,+ timezone=team.timezone,+ pinned=_pinned_payload(cohorts),+ preconditions=preconditions,+ blocked_reason=blocked_reason,+ )+ CohortBackfillRunCohort.objects.for_team(team_id).bulk_create(+ [+ CohortBackfillRunCohort(+ run=run,+ team_id=team_id,+ cohort=cohort,+ filters_shape_hash=hashes[cohort.id],+ behavioral_filters_shape_hash=behavioral_hashes[cohort.id],+ pinned_filters=cohort.filters,+ )+ for cohort in cohorts+ ]+ )+ return run+++def supersede_active_runs(team_id: int, cohort_ids: Iterable[int]) -> int:+ cohort_id_set = set(cohort_ids)+ if not cohort_id_set:+ return 0++ with transaction.atomic():+ participations = CohortBackfillRunCohort.objects.for_team(team_id).filter(+ cohort_id__in=cohort_id_set,+ superseded_at__isnull=True,+ run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ )+ cohort_run_ids = list(+ participations.filter(run__scope=CohortBackfillScope.COHORT).values_list("run_id", flat=True)+ )+ participation_count = participations.update(+ superseded_at=Now(), error="Cohort definition changed during backfill"+ )+ if cohort_run_ids:+ CohortBackfillRun.objects.for_team(team_id).filter(id__in=cohort_run_ids).update(+ status=CohortBackfillRunStatus.SUPERSEDED,+ finished_at=Now(),+ error="Cohort definition changed during backfill",+ )+ return participation_countdiff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.pynew file mode 100644index 000000000000..494ea96b3347--- /dev/null+++ b/products/cohorts/backend/backfill/test/test_management_command.py@@ -0,0 +1,136 @@+from io import StringIO++from posthog.test.base import BaseTest+from unittest import mock++from django.core.management import call_command+from django.core.management.base import CommandError+from django.test import override_settings++from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBackfillRunCohort+from products.cohorts.backend.models.cohort import Cohort, CohortType+++@override_settings(+ REALTIME_COHORT_TEAM_ALLOWLIST="all",+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+)+class TestCreateCohortBackfillRunCommand(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ feature_patch = mock.patch(+ "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False+ )+ feature_patch.start()+ self.addCleanup(feature_patch.stop)++ def _cohort(self, event: str) -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "behavioral",+ "key": event,+ "event_type": "events",+ "value": "performed_event",+ "conditionHash": f"hash-{event}",+ "time_value": 7,+ "time_interval": "day",+ }+ ],+ }+ },+ )++ @override_settings(BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=False)+ def test_missing_attestation_errors_without_writing(self) -> None:+ self._cohort("$pageview")++ with self.assertRaisesMessage(CommandError, "processor durability"):+ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement")++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ def test_success_creates_team_run_for_every_behavioral_cohort(self) -> None:+ first = self._cohort("$pageview")+ second = self._cohort("signup")+ stdout = StringIO()++ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement", stdout=stdout)++ run = CohortBackfillRun.objects.for_team(self.team.id).get()+ self.assertIn(str(run.id), stdout.getvalue())+ self.assertEqual(+ set(+ CohortBackfillRunCohort.objects.for_team(self.team.id)+ .filter(run=run)+ .values_list("cohort_id", flat=True)+ ),+ {first.id, second.id},+ )++ def test_cohort_ids_limit_the_run(self) -> None:+ selected = self._cohort("$pageview")+ self._cohort("signup")++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="disaster_recovery",+ cohort_ids=[selected.id],+ )++ run = CohortBackfillRun.objects.for_team(self.team.id).get()+ self.assertEqual(+ list(+ CohortBackfillRunCohort.objects.for_team(self.team.id)+ .filter(run=run)+ .values_list("cohort_id", flat=True)+ ),+ [selected.id],+ )++ def test_active_team_run_returns_clean_command_error(self) -> None:+ first = self._cohort("$pageview")+ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ cohort_ids=[first.id],+ )+ second = self._cohort("signup")++ with self.assertRaisesMessage(CommandError, "already has an active team backfill run"):+ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ cohort_ids=[second.id],+ )++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)++ def test_dry_run_writes_nothing(self) -> None:+ self._cohort("$pageview")+ stdout = StringIO()++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ dry_run=True,+ stdout=stdout,+ )++ self.assertIn("Dry run", stdout.getvalue())+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none")+ def test_non_allowlisted_team_errors(self) -> None:+ with self.assertRaisesMessage(CommandError, "realtime cohort allowlist"):+ call_command("create_cohort_backfill_run", team_id=self.team.id, trigger="team_enablement")diff --git a/products/cohorts/backend/backfill/test/test_pinning.py b/products/cohorts/backend/backfill/test/test_pinning.pynew file mode 100644index 000000000000..8427f7136d43--- /dev/null+++ b/products/cohorts/backend/backfill/test/test_pinning.py@@ -0,0 +1,105 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.cohorts.backend.backfill.pinning import derive_window_days, pin_conditions_for_cohorts+from products.cohorts.backend.models.cohort import Cohort+++class TestBackfillPinning(SimpleTestCase):+ @parameterized.expand(+ [+ ("day", 3, 3),+ ("week", 3, 21),+ ("month", 3, 90),+ ("year", 3, 1095),+ ("hour", 3, 0),+ ("minute", 3, 0),+ ("invalid", "bad", 0),+ ]+ )+ def test_derive_window_days(self, interval: str, value: object, expected: int) -> None:+ self.assertEqual(derive_window_days(value, interval), expected)++ def test_pins_leaf_state_fields_and_event_union(self) -> None:+ cohort = Cohort(+ id=7,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "behavioral",+ "key": "$pageview",+ "event_type": "events",+ "value": "performed_event_multiple",+ "conditionHash": "bbbbbbbbbbbbbbbb",+ "time_value": 7,+ "time_interval": "day",+ "explicit_datetime": None,+ "explicit_datetime_to": None,+ "operator": "gte",+ "operator_value": 3,+ },+ {+ "type": "behavioral",+ "key": "$pageview",+ "event_type": "events",+ "value": "performed_event",+ "conditionHash": "aaaaaaaaaaaaaaaa",+ },+ {+ "type": "behavioral",+ "key": 42,+ "event_type": "actions",+ "value": "performed_event",+ "conditionHash": "cccccccccccccccc",+ },+ ],+ }+ },+ )++ pinned, event_names = pin_conditions_for_cohorts([cohort])++ self.assertEqual(pinned["schema_version"], 1)+ self.assertEqual(event_names, ["$pageview"])+ self.assertEqual(+ [condition["condition_hash"] for condition in pinned["conditions"]],+ sorted(+ [+ "aaaaaaaaaaaaaaaa",+ "bbbbbbbbbbbbbbbb",+ "cccccccccccccccc",+ ]+ ),+ )+ multiple = next(item for item in pinned["conditions"] if item["condition_hash"] == "bbbbbbbbbbbbbbbb")+ self.assertEqual(+ {+ field: multiple[field]+ for field in (+ "condition_hash",+ "value",+ "time_value",+ "time_interval",+ "explicit_datetime",+ "explicit_datetime_to",+ "operator",+ "operator_value",+ )+ },+ {+ "condition_hash": "bbbbbbbbbbbbbbbb",+ "value": "performed_event_multiple",+ "time_value": 7,+ "time_interval": "day",+ "explicit_datetime": None,+ "explicit_datetime_to": None,+ "operator": "gte",+ "operator_value": 3,+ },+ )+ action = next(item for item in pinned["conditions"] if item["condition_hash"] == "cccccccccccccccc")+ self.assertTrue(action["is_action"])+ self.assertIsNone(action["event_name"])diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.pynew file mode 100644index 000000000000..7b09b9c0936c--- /dev/null+++ b/products/cohorts/backend/backfill/test/test_readiness.py@@ -0,0 +1,149 @@+from posthog.test.base import BaseTest+from unittest import mock++from django.db import connection+from django.test import override_settings+from django.test.utils import CaptureQueriesContext+from django.utils import timezone++from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash, stamp_events_readiness+from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohort+from products.cohorts.backend.models.backfill import CohortBackfillRunCohort, CohortBackfillRunStatus+from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.leaf_shape import extract_leaf_shape_hash+++@override_settings(+ REALTIME_COHORT_TEAM_ALLOWLIST="all",+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+)+class TestBackfillReadiness(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ feature_patch = mock.patch(+ "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False+ )+ feature_patch.start()+ self.addCleanup(feature_patch.stop)++ def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:+ values: list[dict] = [+ {+ "type": "behavioral",+ "key": "$pageview",+ "event_type": "events",+ "value": "performed_event_multiple",+ "conditionHash": "same-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_and_run(self):+ cohort = Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters=self._filters(7),+ )+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ assert run is not None+ return cohort, run++ def test_stamp_uses_one_conditional_cohort_update(self) -> None:+ cohort, run = self._cohort_and_run()++ with CaptureQueriesContext(connection) as queries:+ self.assertTrue(stamp_events_readiness(run, cohort.id))++ cohort.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertIsNotNone(cohort.last_backfill_events_at)+ self.assertIsNotNone(participation.stamped_at)+ cohort_updates = [query["sql"] for query in queries if query["sql"].startswith('UPDATE "posthog_cohort"')]+ self.assertEqual(len(cohort_updates), 1)+ self.assertIn('"behavioral_filters_shape_hash"', cohort_updates[0])+ self.assertIn('"last_backfill_events_at" IS NULL', cohort_updates[0])++ def test_edit_between_completion_and_stamp_fails_cas(self) -> None:+ cohort, run = self._cohort_and_run()+ cohort.filters = self._filters(30)+ cohort.save(update_fields=["filters"])++ self.assertFalse(stamp_events_readiness(run, cohort.id))++ cohort.refresh_from_db()+ run.refresh_from_db()+ self.assertIsNone(cohort.last_backfill_events_at)+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)++ def test_person_only_edit_between_completion_and_stamp_stamps_readiness(self) -> None:+ # A person-property edit shifts the full filters hash but not the behavioral one, and does+ # not null events readiness. The events backfill is still valid, so the stamp must succeed+ # rather than supersede the run (the sibling behavioral edit above correctly supersedes).+ cohort = Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters=self._filters(7, person_hash="person-a"),+ )+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ assert run is not None+ old_full_hash = cohort.filters_shape_hash++ cohort.filters = self._filters(7, person_hash="person-b")+ cohort.save(update_fields=["filters"])+ cohort.refresh_from_db()+ self.assertNotEqual(cohort.filters_shape_hash, old_full_hash)++ self.assertTrue(stamp_events_readiness(run, cohort.id))++ cohort.refresh_from_db()+ run.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertIsNotNone(cohort.last_backfill_events_at)+ self.assertIsNotNone(participation.stamped_at)+ self.assertIsNone(participation.superseded_at)+ self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)++ def test_already_stamped_readiness_is_not_overwritten(self) -> None:+ cohort, run = self._cohort_and_run()+ first_stamp = timezone.now()+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=first_stamp)++ self.assertTrue(stamp_events_readiness(run, cohort.id))++ cohort.refresh_from_db()+ run.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(cohort.last_backfill_events_at, first_stamp)+ self.assertIsNotNone(participation.stamped_at)+ self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)++ def test_ensure_shape_hash_only_fills_null_column(self) -> None:+ cohort, _ = self._cohort_and_run()+ Cohort.objects.filter(id=cohort.id).update(+ filters_shape_hash=None,+ behavioral_filters_shape_hash=None,+ )+ cohort.filters_shape_hash = None+ cohort.behavioral_filters_shape_hash = None++ self.assertEqual(ensure_filters_shape_hash(cohort), extract_leaf_shape_hash(cohort.filters))+ self.assertIsNotNone(cohort.behavioral_filters_shape_hash)++ Cohort.objects.filter(id=cohort.id).update(filters_shape_hash="persisted")+ cohort.filters_shape_hash = None+ self.assertEqual(ensure_filters_shape_hash(cohort), "persisted")diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.pynew file mode 100644index 000000000000..e85ee7936cd5--- /dev/null+++ b/products/cohorts/backend/backfill/test/test_runs.py@@ -0,0 +1,153 @@+from posthog.test.base import BaseTest+from unittest import mock++from django.test import override_settings++from posthog.tasks.calculate_cohort import trigger_cohort_events_backfill_task++from products.cohorts.backend.backfill.runs import (+ create_backfill_run_for_cohort,+ create_team_backfill_run,+ supersede_active_runs,+)+from products.cohorts.backend.models.backfill import (+ CohortBackfillChunk,+ CohortBackfillRun,+ CohortBackfillRunCohort,+ CohortBackfillRunStatus,+ CohortBackfillScope,+)+from products.cohorts.backend.models.cohort import Cohort, CohortType+++@override_settings(+ REALTIME_COHORT_TEAM_ALLOWLIST="all",+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+)+class TestBackfillRuns(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ feature_patch = mock.patch(+ "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False+ )+ feature_patch.start()+ self.addCleanup(feature_patch.stop)++ def _filters(self, event: str = "$pageview", window_days: int = 7) -> dict:+ return {+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "behavioral",+ "key": event,+ "event_type": "events",+ "value": "performed_event_multiple",+ "conditionHash": f"hash-{event}",+ "time_value": window_days,+ "time_interval": "day",+ "operator": "gte",+ "operator_value": 2,+ }+ ],+ }+ }++ def _cohort(self, event: str = "$pageview") -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ name=event,+ cohort_type=CohortType.REALTIME,+ filters=self._filters(event),+ )++ def test_cohort_run_pins_definition_timezone_and_preconditions(self) -> None:+ cohort = self._cohort()++ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")++ assert run is not None+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)+ self.assertEqual(run.scope, CohortBackfillScope.COHORT)+ self.assertEqual(run.timezone, self.team.timezone)+ self.assertEqual(run.pinned["event_names"], ["$pageview"])+ self.assertEqual(run.preconditions["catalog_consume_floor"], "not_implemented_b8")+ self.assertEqual(participation.filters_shape_hash, cohort.filters_shape_hash)+ self.assertEqual(participation.pinned_filters, cohort.filters)+ self.assertEqual(CohortBackfillChunk.objects.for_team(self.team.id).filter(run=run).count(), 0)++ @override_settings(BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=False)+ def test_signal_path_records_blocked_run_when_attestation_is_missing(self) -> None:+ cohort = self._cohort()++ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")++ assert run is not None+ self.assertEqual(run.status, CohortBackfillRunStatus.BLOCKED)+ self.assertIn("merge gate", run.blocked_reason)++ def test_task_revalidates_fresh_cohort_state(self) -> None:+ cohort = self._cohort()+ Cohort.objects.filter(id=cohort.id).update(deleted=True)++ self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ def test_team_run_pins_sorted_union_and_join_rows(self) -> None:+ second = self._cohort("signup")+ first = self._cohort("$pageview")++ run = create_team_backfill_run(self.team.id, "team_enablement")++ self.assertEqual(run.scope, CohortBackfillScope.TEAM)+ self.assertEqual(run.pinned["event_names"], ["$pageview", "signup"])+ self.assertEqual(+ set(+ CohortBackfillRunCohort.objects.for_team(self.team.id)+ .filter(run=run)+ .values_list("cohort_id", flat=True)+ ),+ {first.id, second.id},+ )++ def test_supersession_marks_cohort_run_and_participation(self) -> None:+ cohort = self._cohort()+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ assert run is not None++ self.assertEqual(supersede_active_runs(self.team.id, [cohort.id]), 1)++ run.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)+ self.assertIsNotNone(participation.superseded_at)++ def test_second_active_cohort_run_is_a_benign_noop(self) -> None:+ cohort = self._cohort()+ self.assertIsNotNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created"))++ self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)++ def test_active_team_run_prevents_overlapping_cohort_run(self) -> None:+ cohort = self._cohort()+ create_team_backfill_run(self.team.id, "team_enablement")++ self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)++ def test_active_cohort_run_prevents_overlapping_team_run(self) -> None:+ cohort = self._cohort()+ self.assertIsNotNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created"))++ with self.assertRaisesMessage(ValueError, "Cohorts already have active backfill runs"):+ create_team_backfill_run(self.team.id, "team_enablement")++ def test_celery_task_uses_explicit_team_scope(self) -> None:+ cohort = self._cohort()++ trigger_cohort_events_backfill_task.run(self.team.id, cohort.id, "cohort_created")++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).filter(cohort=cohort).count(), 1)diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.pynew file mode 100644index 000000000000..f33a9bf12142--- /dev/null+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py@@ -0,0 +1,76 @@+from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser+from django.db import IntegrityError++from posthog.models.team.team import Team++from products.cohorts.backend.backfill.pinning import pin_conditions_for_cohorts+from products.cohorts.backend.backfill.runs import check_run_preconditions, create_team_backfill_run+from products.cohorts.backend.models.backfill import CohortBackfillRunCohort, CohortBackfillTrigger+from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.leaf_shape import walk_filter_leaves+from products.cohorts.backend.realtime_teams import is_realtime_cohort_team+++def _has_behavioral_filters(cohort: Cohort) -> bool:+ return any(+ leaf.get("type") == "behavioral" for leaf in walk_filter_leaves((cohort.filters or {}).get("properties"))+ )+++class Command(BaseCommand):+ help = "Create a coordinated behavioral cohort backfill run"++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument(+ "--trigger",+ choices=[CohortBackfillTrigger.TEAM_ENABLEMENT, CohortBackfillTrigger.DISASTER_RECOVERY],+ required=True,+ )+ parser.add_argument("--cohort-ids", type=int, nargs="+")+ parser.add_argument("--dry-run", action="store_true")++ def handle(self, *args: Any, **options: Any) -> None:+ team_id: int = options["team_id"]+ if not is_realtime_cohort_team(team_id):+ raise CommandError(f"Team {team_id} is not in the realtime cohort allowlist")++ _, missing = check_run_preconditions()+ if missing:+ raise CommandError(f"Missing operator attestations: {', '.join(missing)}")++ cohort_ids = options.get("cohort_ids")+ if options["dry_run"]:+ queryset = Cohort.objects.filter(+ team_id=team_id,+ cohort_type=CohortType.REALTIME,+ is_static=False,+ deleted=False,+ )+ if cohort_ids is not None:+ queryset = queryset.filter(id__in=cohort_ids)+ cohorts = [cohort for cohort in queryset.order_by("id") if _has_behavioral_filters(cohort)]+ if cohort_ids is not None and {cohort.id for cohort in cohorts} != set(cohort_ids):+ raise CommandError("One or more --cohort-ids are not eligible realtime behavioral cohorts")+ pinned, event_names = pin_conditions_for_cohorts(cohorts)+ self.stdout.write(+ f"Dry run: {len(cohorts)} cohorts, {len(pinned['conditions'])} conditions, "+ f"{len(event_names)} event names"+ )+ return++ try:+ run = create_team_backfill_run(team_id, options["trigger"], cohort_ids)+ except (Team.DoesNotExist, ValueError) as error:+ raise CommandError(str(error)) from error+ except IntegrityError as error:+ raise CommandError(f"Team {team_id} already has an active team backfill run") from error+ self.stdout.write(+ self.style.SUCCESS(+ f"Created run {run.id}: "+ f"{CohortBackfillRunCohort.objects.for_team(team_id).filter(run=run).count()} cohorts, "+ f"{len(run.pinned['conditions'])} conditions, {len(run.pinned['event_names'])} event names"+ )+ )diff --git a/products/cohorts/backend/migrations/0003_cohort_filters_shape_hash.py b/products/cohorts/backend/migrations/0003_cohort_filters_shape_hash.pynew file mode 100644index 000000000000..867a61d3a70c--- /dev/null+++ b/products/cohorts/backend/migrations/0003_cohort_filters_shape_hash.py@@ -0,0 +1,20 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0002_cohort_last_backfill_events_at"),+ ]++ operations = [+ migrations.AddField(+ model_name="cohort",+ name="filters_shape_hash",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ migrations.AddField(+ model_name="cohort",+ name="behavioral_filters_shape_hash",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ ]diff --git a/products/cohorts/backend/migrations/0004_cohort_backfill_tables.py b/products/cohorts/backend/migrations/0004_cohort_backfill_tables.pynew file mode 100644index 000000000000..7ecd0dff54fe--- /dev/null+++ b/products/cohorts/backend/migrations/0004_cohort_backfill_tables.py@@ -0,0 +1,283 @@+# Generated by Django 5.2.14 on 2026-07-14 04:31++import django.utils.timezone+import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0003_cohort_filters_shape_hash"),+ ("posthog", "1252_datadeletionrequest_property_removal_marker"),+ ]++ operations = [+ migrations.CreateModel(+ name="CohortBackfillRun",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),+ (+ "backfill_kind",+ models.CharField(+ choices=[+ ("behavioral", "Behavioral"),+ ("person_property", "Person property"),+ ],+ default="behavioral",+ max_length=32,+ ),+ ),+ (+ "trigger_kind",+ models.CharField(+ choices=[+ ("team_enablement", "Team enablement"),+ ("cohort_created", "Cohort created"),+ ("cohort_edited", "Cohort edited"),+ ("disaster_recovery", "Disaster recovery"),+ ],+ max_length=32,+ ),+ ),+ (+ "scope",+ models.CharField(choices=[("team", "Team"), ("cohort", "Cohort")], max_length=16),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("awaiting_boundary", "Awaiting boundary"),+ ("blocked", "Blocked"),+ ("seeding", "Seeding"),+ ("reconciling", "Reconciling"),+ ("completed", "Completed"),+ ("superseded", "Superseded"),+ ("cancelled", "Cancelled"),+ ("failed", "Failed"),+ ],+ default="awaiting_boundary",+ max_length=32,+ ),+ ),+ ("timezone", models.CharField(max_length=240)),+ ("boundary_at", models.DateTimeField(blank=True, null=True)),+ (+ "boundary_established_at",+ models.DateTimeField(blank=True, null=True),+ ),+ ("pinned", models.JSONField(default=dict)),+ ("preconditions", models.JSONField(default=dict)),+ ("reconcile_hwms", models.JSONField(blank=True, null=True)),+ ("blocked_reason", models.TextField(blank=True, default="")),+ ("error", models.TextField(blank=True, default="")),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("finished_at", models.DateTimeField(blank=True, null=True)),+ (+ "cohort",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="backfill_runs",+ to="cohorts.cohort",+ ),+ ),+ (+ "superseded_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="superseded_runs",+ to="cohorts.cohortbackfillrun",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "cohort_backfill_runs",+ },+ ),+ migrations.CreateModel(+ name="CohortBackfillChunk",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("day", models.DateField()),+ ("band", models.SmallIntegerField(default=0)),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("scanning", "Scanning"),+ ("produced", "Produced"),+ ("confirmed", "Confirmed"),+ ("failed", "Failed"),+ ],+ default="pending",+ max_length=16,+ ),+ ),+ ("claim_epoch", models.IntegerField(default=0)),+ (+ "claimed_by",+ models.CharField(blank=True, default="", max_length=255),+ ),+ ("claimed_at", models.DateTimeField(blank=True, null=True)),+ ("lease_expires_at", models.DateTimeField(blank=True, null=True)),+ ("s_chunk_at", models.DateTimeField(blank=True, null=True)),+ ("attempts", models.IntegerField(default=0)),+ ("last_error", models.TextField(blank=True, default="")),+ ("tiles_produced", models.BigIntegerField(default=0)),+ ("produce_hwms", models.JSONField(blank=True, null=True)),+ ("confirmed_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "run",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="chunks",+ to="cohorts.cohortbackfillrun",+ ),+ ),+ ],+ options={+ "db_table": "cohort_backfill_chunks",+ },+ ),+ migrations.CreateModel(+ name="CohortBackfillRunCohort",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("filters_shape_hash", models.CharField(max_length=64)),+ ("behavioral_filters_shape_hash", models.CharField(default="", max_length=64)),+ ("pinned_filters", models.JSONField()),+ ("stamped_at", models.DateTimeField(blank=True, null=True)),+ ("superseded_at", models.DateTimeField(blank=True, null=True)),+ ("error", models.TextField(blank=True, default="")),+ (+ "cohort",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="backfill_participations",+ to="cohorts.cohort",+ ),+ ),+ (+ "run",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="run_cohorts",+ to="cohorts.cohortbackfillrun",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "cohort_backfill_run_cohorts",+ },+ ),+ migrations.AddIndex(+ model_name="cohortbackfillrun",+ index=models.Index(fields=["team", "status"], name="cohort_bfr_team_status_idx"),+ ),+ migrations.AddIndex(+ model_name="cohortbackfillrun",+ index=models.Index(fields=["team", "-created_at"], name="cohort_bfr_team_created_idx"),+ ),+ migrations.AddConstraint(+ model_name="cohortbackfillrun",+ constraint=models.UniqueConstraint(+ condition=models.Q(+ ("cohort__isnull", False),+ (+ "status__in",+ ("awaiting_boundary", "blocked", "seeding", "reconciling"),+ ),+ ),+ fields=("cohort",),+ name="cohort_bfr_active_cohort_uq",+ ),+ ),+ migrations.AddConstraint(+ model_name="cohortbackfillrun",+ constraint=models.UniqueConstraint(+ condition=models.Q(+ ("scope", "team"),+ (+ "status__in",+ ("awaiting_boundary", "blocked", "seeding", "reconciling"),+ ),+ ),+ fields=("team",),+ name="cohort_bfr_active_team_uq",+ ),+ ),+ migrations.AddIndex(+ model_name="cohortbackfillchunk",+ index=models.Index(fields=["run", "status", "day"], name="cohort_bfc_run_status_day_idx"),+ ),+ migrations.AddConstraint(+ model_name="cohortbackfillchunk",+ constraint=models.UniqueConstraint(fields=("run", "day", "band"), name="cohort_bfc_run_day_band_uq"),+ ),+ migrations.AddConstraint(+ model_name="cohortbackfillruncohort",+ constraint=models.UniqueConstraint(fields=("run", "cohort"), name="cohort_bfrc_run_cohort_uq"),+ ),+ ]diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txtindex 95693715736a..da7555feff07 100644--- a/products/cohorts/backend/migrations/max_migration.txt+++ b/products/cohorts/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_cohort_last_backfill_events_at+0004_cohort_backfill_tablesdiff --git a/products/cohorts/backend/models/__init__.py b/products/cohorts/backend/models/__init__.pyindex 24c74b8898fc..129cf99b223c 100644--- a/products/cohorts/backend/models/__init__.py+++ b/products/cohorts/backend/models/__init__.py@@ -1,4 +1,14 @@from . import dependencies as _dependencies # noqa: F401 — import for Django signal handler registration+from .backfill import (+ CohortBackfillChunk,+ CohortBackfillChunkStatus,+ CohortBackfillKind,+ CohortBackfillRun,+ CohortBackfillRunCohort,+ CohortBackfillRunStatus,+ CohortBackfillScope,+ CohortBackfillTrigger,+)from .calculation_history import CohortCalculationHistoryfrom .cohort import (DEFAULT_COHORT_INSERT_BATCH_SIZE,@@ -14,6 +24,14 @@ from .cohort import (__all__ = ["DEFAULT_COHORT_INSERT_BATCH_SIZE","Cohort",+ "CohortBackfillChunk",+ "CohortBackfillChunkStatus",+ "CohortBackfillKind",+ "CohortBackfillRun",+ "CohortBackfillRunCohort",+ "CohortBackfillRunStatus",+ "CohortBackfillScope",+ "CohortBackfillTrigger","CohortCalculationHistory","CohortKind","CohortManager",diff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.pynew file mode 100644index 000000000000..72fa79cc9804--- /dev/null+++ b/products/cohorts/backend/models/backfill.py@@ -0,0 +1,148 @@+from django.db import models+from django.db.models import Q+from django.utils import timezone as django_timezone++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel, UUIDTModel+++class CohortBackfillKind(models.TextChoices):+ BEHAVIORAL = "behavioral", "Behavioral"+ PERSON_PROPERTY = "person_property", "Person property"+++class CohortBackfillTrigger(models.TextChoices):+ TEAM_ENABLEMENT = "team_enablement", "Team enablement"+ COHORT_CREATED = "cohort_created", "Cohort created"+ COHORT_EDITED = "cohort_edited", "Cohort edited"+ DISASTER_RECOVERY = "disaster_recovery", "Disaster recovery"+++class CohortBackfillScope(models.TextChoices):+ TEAM = "team", "Team"+ COHORT = "cohort", "Cohort"+++class CohortBackfillRunStatus(models.TextChoices):+ AWAITING_BOUNDARY = "awaiting_boundary", "Awaiting boundary"+ BLOCKED = "blocked", "Blocked"+ SEEDING = "seeding", "Seeding"+ RECONCILING = "reconciling", "Reconciling"+ COMPLETED = "completed", "Completed"+ SUPERSEDED = "superseded", "Superseded"+ CANCELLED = "cancelled", "Cancelled"+ FAILED = "failed", "Failed"+++ACTIVE_COHORT_BACKFILL_RUN_STATUSES = (+ CohortBackfillRunStatus.AWAITING_BOUNDARY,+ CohortBackfillRunStatus.BLOCKED,+ CohortBackfillRunStatus.SEEDING,+ CohortBackfillRunStatus.RECONCILING,+)+++class CohortBackfillChunkStatus(models.TextChoices):+ PENDING = "pending", "Pending"+ SCANNING = "scanning", "Scanning"+ PRODUCED = "produced", "Produced"+ CONFIRMED = "confirmed", "Confirmed"+ FAILED = "failed", "Failed"+++class CohortBackfillRun(TeamScopedRootMixin, UUIDTModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ cohort = models.ForeignKey(+ "cohorts.Cohort", on_delete=models.SET_NULL, null=True, blank=True, related_name="backfill_runs"+ )+ created_by_id = models.BigIntegerField(null=True, blank=True)+ backfill_kind = models.CharField(+ max_length=32, choices=CohortBackfillKind.choices, default=CohortBackfillKind.BEHAVIORAL+ )+ trigger_kind = models.CharField(max_length=32, choices=CohortBackfillTrigger.choices)+ scope = models.CharField(max_length=16, choices=CohortBackfillScope.choices)+ status = models.CharField(+ max_length=32, choices=CohortBackfillRunStatus.choices, default=CohortBackfillRunStatus.AWAITING_BOUNDARY+ )+ timezone = models.CharField(max_length=240)+ boundary_at = models.DateTimeField(null=True, blank=True)+ boundary_established_at = models.DateTimeField(null=True, blank=True)+ pinned = models.JSONField(default=dict)+ preconditions = models.JSONField(default=dict)+ reconcile_hwms = models.JSONField(null=True, blank=True)+ blocked_reason = models.TextField(blank=True, default="")+ error = models.TextField(blank=True, default="")+ superseded_by = models.ForeignKey(+ "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="superseded_runs"+ )+ created_at = models.DateTimeField(default=django_timezone.now)+ updated_at = models.DateTimeField(auto_now=True)+ finished_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ db_table = "cohort_backfill_runs"+ indexes = [+ models.Index(fields=["team", "status"], name="cohort_bfr_team_status_idx"),+ models.Index(fields=["team", "-created_at"], name="cohort_bfr_team_created_idx"),+ ]+ constraints = [+ models.UniqueConstraint(+ fields=["cohort"],+ condition=Q(cohort__isnull=False, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES),+ name="cohort_bfr_active_cohort_uq",+ ),+ models.UniqueConstraint(+ fields=["team"],+ condition=Q(scope=CohortBackfillScope.TEAM, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES),+ name="cohort_bfr_active_team_uq",+ ),+ ]+++class CohortBackfillRunCohort(TeamScopedRootMixin, UUIDModel):+ run = models.ForeignKey(CohortBackfillRun, on_delete=models.CASCADE, related_name="run_cohorts")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ cohort = models.ForeignKey("cohorts.Cohort", on_delete=models.CASCADE, related_name="backfill_participations")+ filters_shape_hash = models.CharField(max_length=64)+ behavioral_filters_shape_hash = models.CharField(max_length=64, default="")+ pinned_filters = models.JSONField()+ stamped_at = models.DateTimeField(null=True, blank=True)+ superseded_at = models.DateTimeField(null=True, blank=True)+ error = models.TextField(blank=True, default="")++ class Meta:+ db_table = "cohort_backfill_run_cohorts"+ constraints = [+ models.UniqueConstraint(fields=["run", "cohort"], name="cohort_bfrc_run_cohort_uq"),+ ]+++class CohortBackfillChunk(TeamScopedRootMixin, UUIDModel):+ run = models.ForeignKey(CohortBackfillRun, on_delete=models.CASCADE, related_name="chunks")+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ day = models.DateField()+ band = models.SmallIntegerField(default=0)+ status = models.CharField(+ max_length=16, choices=CohortBackfillChunkStatus.choices, default=CohortBackfillChunkStatus.PENDING+ )+ claim_epoch = models.IntegerField(default=0)+ claimed_by = models.CharField(max_length=255, blank=True, default="")+ claimed_at = models.DateTimeField(null=True, blank=True)+ lease_expires_at = models.DateTimeField(null=True, blank=True)+ s_chunk_at = models.DateTimeField(null=True, blank=True)+ attempts = models.IntegerField(default=0)+ last_error = models.TextField(blank=True, default="")+ tiles_produced = models.BigIntegerField(default=0)+ produce_hwms = models.JSONField(null=True, blank=True)+ confirmed_at = models.DateTimeField(null=True, blank=True)+ created_at = models.DateTimeField(default=django_timezone.now)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "cohort_backfill_chunks"+ indexes = [+ models.Index(fields=["run", "status", "day"], name="cohort_bfc_run_status_day_idx"),+ ]+ constraints = [+ models.UniqueConstraint(fields=["run", "day", "band"], name="cohort_bfc_run_day_band_uq"),+ ]diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 2867f70217b7..8e9bf9974440 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -1,6 +1,6 @@import reimport time-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom datetime import datetimefrom enum import StrEnumfrom typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast@@ -35,6 +35,9 @@ from posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.schema_enums import ProductKeyfrom posthog.settings.base_variables import TEST+from products.cohorts.backend.models.leaf_shape import extract_behavioral_leaf_shape_hash, extract_leaf_shape_hash+from products.cohorts.backend.realtime_teams import is_realtime_cohort_team+if TYPE_CHECKING:from posthog.models.team import Team@@ -202,6 +205,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):last_error_at = models.DateTimeField(blank=True, null=True)last_backfill_person_properties_at = models.DateTimeField(blank=True, null=True)last_backfill_events_at = models.DateTimeField(blank=True, null=True)+ filters_shape_hash = models.CharField(max_length=64, null=True, blank=True)+ behavioral_filters_shape_hash = models.CharField(max_length=64, null=True, blank=True)last_realtime_cohort_calculation_at = models.DateTimeField(blank=True, null=True)is_static = models.BooleanField(default=False)@@ -245,6 +250,81 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):def __str__(self):return self.name or "Untitled cohort"+ def save(self, *args: Any, **kwargs: Any) -> None:+ # update_fields can arrive positionally (4th positional, after force_insert/force_update/using)+ # or as a keyword. Intercept it so _maintain_behavioral_shape can extend the frozen set.+ positional_update_fields = args[3] if len(args) > 3 else kwargs.get("update_fields")+ maintained_update_fields = self._maintain_behavioral_shape(positional_update_fields)+ if len(args) > 3:+ args = (*args[:3], maintained_update_fields, *args[4:])+ else:+ kwargs["update_fields"] = maintained_update_fields+ super().save(*args, **kwargs)++ def _maintain_behavioral_shape(self, update_fields: Iterable[str] | None) -> set[str] | None:+ self._leaf_shape_changed = False+ maintained_update_fields = set(update_fields) if update_fields is not None else None+ try:+ if not self.team_id or not is_realtime_cohort_team(self.team_id):+ return maintained_update_fields+ if self.cohort_type != CohortType.REALTIME or self.is_static or self.deleted:+ return maintained_update_fields+ if maintained_update_fields is not None and "filters" not in maintained_update_fields:+ return maintained_update_fields++ new_shape_hash = extract_leaf_shape_hash(self.filters)+ new_behavioral_shape_hash = extract_behavioral_leaf_shape_hash(self.filters)+ stored_shape_hash = self.__dict__.get("filters_shape_hash")+ stored_behavioral_shape_hash = self.__dict__.get("behavioral_filters_shape_hash")+ previous_behavioral_shape_hash = stored_behavioral_shape_hash++ if not self._state.adding and (stored_shape_hash is None or stored_behavioral_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")+ .first()+ )+ if persisted is not 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"])+ )++ shape_hash_needs_update = stored_shape_hash != new_shape_hash+ behavioral_shape_hash_needs_update = stored_behavioral_shape_hash != new_behavioral_shape_hash+ behavioral_shape_changed = (+ not self._state.adding and previous_behavioral_shape_hash != new_behavioral_shape_hash+ )++ self.filters_shape_hash = new_shape_hash+ self.behavioral_filters_shape_hash = new_behavioral_shape_hash+ if behavioral_shape_changed:+ self.last_backfill_events_at = None+ self._leaf_shape_changed = True++ if maintained_update_fields is None:+ return None+ if shape_hash_needs_update:+ maintained_update_fields.add("filters_shape_hash")+ if behavioral_shape_hash_needs_update:+ maintained_update_fields.add("behavioral_filters_shape_hash")+ if behavioral_shape_changed:+ maintained_update_fields.add("last_backfill_events_at")+ return maintained_update_fields+ except Exception as error:+ logger.exception(+ "failed_to_maintain_cohort_behavioral_shape",+ cohort_id=self.pk,+ team_id=self.team_id,+ error=str(error),+ )+ return maintained_update_fields+@classmethoddef get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["Cohort"]:base_qs = cls.objects.filter(team=team, deleted=False)diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.pyindex 67e8f5d25f12..b8773e3a5aa1 100644--- a/products/cohorts/backend/models/dependencies.py+++ b/products/cohorts/backend/models/dependencies.py@@ -17,6 +17,8 @@ from posthog.models.team.team import Teamfrom posthog.redis import get_client as get_redis_clientfrom products.cohorts.backend.models.cohort import Cohort, CohortType, is_cohort_recalculation_only_save+from products.cohorts.backend.models.leaf_shape import walk_filter_leaves+from products.cohorts.backend.realtime_teams import is_realtime_cohort_teamlogger = get_logger(__name__)DEPENDENCY_CACHE_TIMEOUT = 7 * 24 * 60 * 60 # 1 week@@ -31,6 +33,12 @@ COHORT_DEPENDENCY_CACHE_COUNTER = Counter(labelnames=["cache_type", "result"],)+COHORT_REALTIME_STATE_ORPHANED_COUNTER = Counter(+ "posthog_cohort_realtime_state_orphaned_total",+ "Realtime cohort edits that changed the Stage 1 LeafStateKey input set",+ labelnames=["reason"],+)+def _cohort_dependencies_key(cohort_id: int) -> str:return f"cohort:dependencies:{cohort_id}"@@ -309,6 +317,11 @@ def _has_person_property_filters(cohort: Cohort) -> bool:return bool(_extract_person_property_filters(cohort))+def _has_behavioral_filters(cohort: Cohort) -> bool:+ properties = (cohort.filters or {}).get("properties")+ return any(leaf.get("type") == "behavioral" for leaf in walk_filter_leaves(properties))++def _person_property_filters_changed(cohort: Cohort) -> bool:"""Check if person property filters have changed by comparing current filters@@ -442,6 +455,61 @@ def _trigger_cohort_backfill(cohort: Cohort) -> None:)+def _trigger_cohort_events_backfill(cohort: Cohort, trigger_kind: str) -> None:+ try:+ from posthog.tasks.calculate_cohort import (+ trigger_cohort_events_backfill_task, # noqa: PLC0415 — avoids task import during model loading+ )++ redis_client = get_redis_client()+ lock_key = f"cohort_backfill_events_pending:{cohort.pk}"+ if redis_client.set(lock_key, 1, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):+ logger.info(+ "triggering_cohort_events_backfill",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ trigger_kind=trigger_kind,+ debounce_seconds=COHORT_BACKFILL_DEBOUNCE_SECONDS,+ )+ try:+ trigger_cohort_events_backfill_task.apply_async(+ args=[cohort.team_id, cohort.pk, trigger_kind],+ countdown=COHORT_BACKFILL_DEBOUNCE_SECONDS,+ )+ except Exception:+ redis_client.delete(lock_key)+ raise+ else:+ logger.info(+ "cohort_events_backfill_already_pending",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ )+ except Exception as error:+ logger.exception(+ "failed_to_trigger_cohort_events_backfill",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ error=str(error),+ )+++def _supersede_cohort_events_backfills(cohort: Cohort) -> None:+ try:+ from products.cohorts.backend.backfill.runs import (+ supersede_active_runs, # noqa: PLC0415 — avoids a model-load cycle+ )++ supersede_active_runs(cohort.team_id, [cohort.id])+ except Exception as error:+ logger.exception(+ "failed_to_supersede_cohort_events_backfills",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ error=str(error),+ )++@receiver(pre_save, sender=Cohort)def cohort_pre_save(sender, instance, **kwargs):"""@@ -542,6 +610,51 @@ def cohort_conditions_changed_backfill(sender, instance, **kwargs):transaction.on_commit(lambda: _trigger_cohort_backfill(instance))+@receiver(post_save, sender=Cohort)+def cohort_behavioral_shape_changed_backfill(sender, instance, **kwargs):+ try:+ if is_cohort_recalculation_only_save(kwargs):+ return++ update_fields = kwargs.get("update_fields")+ if update_fields is not None and "filters" not in update_fields:+ return+ if not is_realtime_cohort_team(instance.team_id):+ return+ if instance.cohort_type != CohortType.REALTIME or instance.is_static or instance.deleted:+ return+ if not _has_behavioral_filters(instance):+ return++ created = kwargs.get("created", False)+ if not created and not getattr(instance, "_leaf_shape_changed", False):+ return++ if created:+ trigger_kind = "cohort_created"+ else:+ trigger_kind = "cohort_edited"+ COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed").inc()+ transaction.on_commit(lambda: _supersede_cohort_events_backfills(instance))++ if not posthoganalytics.feature_enabled(+ "behavioral-cohort-backfill-runs",+ str(instance.team_id),+ groups={"team": str(instance.team_id)},+ send_feature_flag_events=False,+ ):+ return++ transaction.on_commit(lambda: _trigger_cohort_events_backfill(instance, trigger_kind))+ except Exception as error:+ logger.exception(+ "failed_to_handle_cohort_behavioral_shape_change",+ cohort_id=instance.pk,+ team_id=instance.team_id,+ error=str(error),+ )++@receiver(post_delete, sender=Cohort)def cohort_deleted(sender, instance, **kwargs):"""diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.pynew file mode 100644index 000000000000..d312bf626947--- /dev/null+++ b/products/cohorts/backend/models/leaf_shape.py@@ -0,0 +1,78 @@+import json+import hashlib+from collections.abc import Iterator++_I32_MIN = -(2**31)+_I32_MAX = 2**31 - 1+++def walk_filter_leaves(node: object) -> Iterator[dict]:+ if not isinstance(node, dict):+ return+ if node.get("type") in ("AND", "OR"):+ for child in node.get("values") or []:+ yield from walk_filter_leaves(child)+ else:+ yield node+++def _effective_i32(value: object) -> int:+ return value if isinstance(value, int) and not isinstance(value, bool) and _I32_MIN <= value <= _I32_MAX else 0+++def _effective_string(value: object) -> str:+ return value if isinstance(value, str) else ""+++def _hash_keys(keys: list[list[object]]) -> str:+ if not keys:+ return ""++ serialized = sorted(json.dumps(key, sort_keys=True) for key in keys)+ return hashlib.sha256(json.dumps(serialized, separators=(",", ":")).encode()).hexdigest()+++def _extract_leaf_shape_keys(filters: dict | None, *, behavioral_only: bool) -> list[list[object]]:+ if not filters or not (properties := filters.get("properties")):+ return []++ keys: list[list[object]] = []+ for leaf in walk_filter_leaves(properties):+ leaf_type = leaf.get("type")+ if leaf_type == "person" and not behavioral_only:+ if (condition_hash := leaf.get("conditionHash")) is not None:+ keys.append(["person", condition_hash])+ elif leaf_type == "behavioral":+ if (condition_hash := leaf.get("conditionHash")) is not None:+ keys.append(+ [+ "behavioral",+ condition_hash,+ _effective_string(leaf.get("value")),+ _effective_i32(leaf.get("time_value")),+ _effective_string(leaf.get("time_interval")),+ _effective_string(leaf.get("explicit_datetime")),+ _effective_string(leaf.get("explicit_datetime_to")),+ _effective_string(leaf.get("operator")),+ _effective_i32(leaf.get("operator_value")),+ ]+ )+ elif leaf_type == "cohort" and not behavioral_only:+ 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`.++ 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 conditionHash, value, time_value, time_interval, explicit_datetime,+ explicit_datetime_to, operator, operator_value; person conditionHash; cohort value and negation.+ """+ return _hash_keys(_extract_leaf_shape_keys(filters, behavioral_only=False))+++def extract_behavioral_leaf_shape_hash(filters: dict | None) -> str:+ """Fingerprint only the leaf inputs backed by behavioral event state."""+ return _hash_keys(_extract_leaf_shape_keys(filters, behavioral_only=True))diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.pynew file mode 100644index 000000000000..3f0b970b3125--- /dev/null+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py@@ -0,0 +1,312 @@+from posthog.test.base import BaseTest+from unittest import mock++from django.test import override_settings+from django.utils import timezone+from django.utils.deprecation import RemovedInDjango60Warning++from products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.models.dependencies import COHORT_REALTIME_STATE_ORPHANED_COUNTER+++@override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")+class TestBehavioralBackfillDependencies(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ on_commit_patch = mock.patch("django.db.transaction.on_commit", side_effect=lambda callback: callback())+ self.on_commit = on_commit_patch.start()+ self.addCleanup(on_commit_patch.stop)++ feature_patch = mock.patch(+ "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False+ )+ self.feature_enabled = feature_patch.start()+ self.addCleanup(feature_patch.stop)++ def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:+ values = [+ {+ "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:+ return Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters=self._filters(window_days, person_hash=person_hash),+ )++ def _orphan_count(self) -> float:+ return COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed")._value._value++ def test_window_edit_writes_hash_and_nulls_readiness_in_one_save(self) -> None:+ cohort = self._cohort(7)+ old_hash = cohort.filters_shape_hash+ old_behavioral_hash = cohort.behavioral_filters_shape_hash+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())+ cohort.refresh_from_db()+ before = self._orphan_count()++ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertNotEqual(cohort.filters_shape_hash, old_hash)+ self.assertNotEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)+ self.assertIsNone(cohort.last_backfill_events_at)+ self.assertEqual(self._orphan_count(), before + 1)++ def test_filter_only_update_persists_maintained_fields(self) -> None:+ cohort = self._cohort(7)+ old_hash = cohort.filters_shape_hash+ old_behavioral_hash = cohort.behavioral_filters_shape_hash+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())+ cohort.refresh_from_db()++ cohort.filters = self._filters(30)+ cohort.save(update_fields=["filters"])++ cohort.refresh_from_db()+ self.assertNotEqual(cohort.filters_shape_hash, old_hash)+ self.assertNotEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)+ self.assertIsNone(cohort.last_backfill_events_at)++ def test_positional_filter_update_persists_maintained_fields(self) -> None:+ cohort = self._cohort(7)+ old_hash = cohort.filters_shape_hash+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())+ cohort.refresh_from_db()++ cohort.filters = self._filters(30)+ with self.assertWarns(RemovedInDjango60Warning):+ cohort.save(False, False, None, ["filters"])++ cohort.refresh_from_db()+ self.assertNotEqual(cohort.filters_shape_hash, old_hash)+ self.assertIsNone(cohort.last_backfill_events_at)++ def test_non_filter_partial_save_does_not_maintain_shape(self) -> None:+ cohort = self._cohort(7)+ old_hash = cohort.filters_shape_hash+ ready_at = timezone.now()+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)+ cohort.refresh_from_db()++ cohort.filters = self._filters(30)+ cohort.name = "renamed"+ cohort.save(update_fields=["name"])++ cohort.refresh_from_db()+ self.assertEqual(cohort.filters_shape_hash, old_hash)+ self.assertEqual(cohort.last_backfill_events_at, ready_at)++ def test_flag_off_still_nulls_readiness_without_enqueue(self) -> None:+ cohort = self._cohort(7)+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())+ cohort.refresh_from_db()+ with mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue:+ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertIsNone(cohort.last_backfill_events_at)+ enqueue.assert_not_called()++ def test_person_only_edit_preserves_events_readiness(self) -> None:+ cohort = self._cohort(7, person_hash="person-a")+ ready_at = timezone.now()+ old_hash = cohort.filters_shape_hash+ old_behavioral_hash = cohort.behavioral_filters_shape_hash+ Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)+ cohort.refresh_from_db()+ before = self._orphan_count()+ self.feature_enabled.return_value = True+ redis = mock.Mock()+ redis.set.return_value = True++ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task.apply_async") as person_enqueue,+ mock.patch(+ "posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async"+ ) as event_enqueue,+ ):+ cohort.filters = self._filters(7, person_hash="person-b")+ cohort.save()++ cohort.refresh_from_db()+ self.assertNotEqual(cohort.filters_shape_hash, old_hash)+ self.assertEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)+ self.assertEqual(cohort.last_backfill_events_at, ready_at)+ self.assertEqual(self._orphan_count(), before)+ person_enqueue.assert_called_once()+ event_enqueue.assert_not_called()++ def test_first_legacy_save_initializes_hashes_without_invalidating_readiness(self) -> None:+ cohort = self._cohort(7)+ ready_at = timezone.now()+ Cohort.objects.filter(id=cohort.id).update(+ filters_shape_hash=None,+ behavioral_filters_shape_hash=None,+ last_backfill_events_at=ready_at,+ )+ cohort.refresh_from_db()+ before = self._orphan_count()+ self.feature_enabled.return_value = True++ with mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue:+ cohort.name = "renamed"+ cohort.save()++ cohort.refresh_from_db()+ self.assertIsNotNone(cohort.filters_shape_hash)+ self.assertIsNotNone(cohort.behavioral_filters_shape_hash)+ self.assertEqual(cohort.last_backfill_events_at, ready_at)+ self.assertEqual(self._orphan_count(), before)+ enqueue.assert_not_called()++ def test_first_legacy_behavioral_edit_invalidates_readiness(self) -> None:+ cohort = self._cohort(7)+ Cohort.objects.filter(id=cohort.id).update(+ filters_shape_hash=None,+ behavioral_filters_shape_hash=None,+ last_backfill_events_at=timezone.now(),+ )+ cohort.refresh_from_db()++ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertIsNone(cohort.last_backfill_events_at)++ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="999999999")+ def test_non_allowlisted_save_path_is_unchanged(self) -> None:+ ready_at = timezone.now()+ cohort = Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters=self._filters(7),+ last_backfill_events_at=ready_at,+ )+ before = self._orphan_count()++ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertIsNone(cohort.filters_shape_hash)+ self.assertIsNone(cohort.behavioral_filters_shape_hash)+ self.assertEqual(cohort.last_backfill_events_at, ready_at)+ self.assertEqual(self._orphan_count(), before)++ def test_two_edits_share_the_events_debounce_key(self) -> None:+ cohort = self._cohort(7)+ self.feature_enabled.return_value = True+ redis = mock.Mock()+ redis.set.side_effect = [True, False]+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue,+ ):+ cohort.filters = self._filters(14)+ cohort.save()+ cohort.filters = self._filters(30)+ cohort.save()++ enqueue.assert_called_once_with(+ args=[self.team.id, cohort.id, "cohort_edited"],+ countdown=300,+ )++ def test_person_and_behavioral_changes_enqueue_separate_tasks(self) -> None:+ cohort = self._cohort(7, person_hash="person-a")+ self.feature_enabled.return_value = True+ redis = mock.Mock()+ redis.set.return_value = True+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task.apply_async") as person_enqueue,+ mock.patch(+ "posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async"+ ) as event_enqueue,+ ):+ cohort.filters = self._filters(30, person_hash="person-b")+ cohort.save()++ person_enqueue.assert_called_once()+ event_enqueue.assert_called_once()+ self.assertEqual(+ {call.args[0] for call in redis.set.call_args_list},+ {f"cohort_backfill_pending:{cohort.id}", f"cohort_backfill_events_pending:{cohort.id}"},+ )++ def test_create_path_enqueues_behavioral_backfill(self) -> None:+ self.feature_enabled.return_value = True+ redis = mock.Mock()+ redis.set.return_value = True+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue,+ ):+ cohort = self._cohort(7)++ enqueue.assert_called_once_with(+ args=[self.team.id, cohort.id, "cohort_created"],+ countdown=300,+ )++ def test_receiver_failure_does_not_break_save(self) -> None:+ cohort = self._cohort(7)++ with mock.patch(+ "products.cohorts.backend.models.dependencies._has_behavioral_filters",+ side_effect=RuntimeError("broken detector"),+ ):+ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertIsNone(cohort.last_backfill_events_at)++ def test_hashing_failure_in_maintain_shape_does_not_break_save(self) -> None:+ # _maintain_behavioral_shape swallows hashing errors so a hashing bug can't take down every+ # realtime cohort save. The receiver-guard test above patches a different try/except in the+ # signal path; this one exercises the save-path guard directly by making the hash raise.+ 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()++ with mock.patch(+ "products.cohorts.backend.models.cohort.extract_leaf_shape_hash",+ side_effect=RuntimeError("hash boom"),+ ):+ cohort.name = "renamed"+ cohort.filters = self._filters(30)+ cohort.save()++ cohort.refresh_from_db()+ self.assertEqual(cohort.name, "renamed")+ # The guard bailed before the readiness-null branch, so events readiness is left intact.+ self.assertEqual(cohort.last_backfill_events_at, ready_at)diff --git a/products/cohorts/backend/models/test/test_leaf_shape.py b/products/cohorts/backend/models/test/test_leaf_shape.pynew file mode 100644index 000000000000..61b5dae610d8--- /dev/null+++ b/products/cohorts/backend/models/test/test_leaf_shape.py@@ -0,0 +1,129 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.cohorts.backend.models.leaf_shape import (+ extract_behavioral_leaf_shape_hash,+ extract_leaf_shape_hash,+ walk_filter_leaves,+)+++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++ @parameterized.expand(+ [+ ("condition_hash", "conditionHash", "ffffffffffffffff"),+ ("value", "value", "performed_event"),+ ("time_value", "time_value", 30),+ ("time_interval", "time_interval", "week"),+ ("explicit_datetime", "explicit_datetime", "2026-01-01T00:00:00Z"),+ ("explicit_datetime_to", "explicit_datetime_to", "2026-02-01T00:00:00Z"),+ ("operator", "operator", "lte"),+ ("operator_value", "operator_value", 5),+ ]+ )+ def test_each_behavioral_state_field_changes_the_hash(self, _name: str, field: str, changed_value: object) -> None:+ baseline = self._filters(self._behavioral())+ changed = self._filters(self._behavioral(**{field: changed_value}))+ self.assertNotEqual(+ extract_leaf_shape_hash(baseline),+ extract_leaf_shape_hash(changed),+ )+ self.assertNotEqual(+ extract_behavioral_leaf_shape_hash(baseline),+ 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"}+ self.assertEqual(+ extract_leaf_shape_hash(self._filters(self._behavioral(negation=False), person)),+ extract_leaf_shape_hash(self._filters(person, self._behavioral(negation=True))),+ )++ def test_person_and_cohort_reference_fields_are_included(self) -> None:+ self.assertNotEqual(+ extract_leaf_shape_hash(self._filters({"type": "person", "conditionHash": "a"})),+ extract_leaf_shape_hash(self._filters({"type": "person", "conditionHash": "b"})),+ )+ self.assertNotEqual(+ extract_leaf_shape_hash(self._filters({"type": "cohort", "value": 42, "negation": False})),+ extract_leaf_shape_hash(self._filters({"type": "cohort", "value": 42, "negation": True})),+ )++ @parameterized.expand(+ [+ (+ "person",+ {"type": "person", "conditionHash": "a"},+ {"type": "person", "conditionHash": "b"},+ ),+ (+ "cohort",+ {"type": "cohort", "value": 42, "negation": False},+ {"type": "cohort", "value": 43, "negation": True},+ ),+ ]+ )+ def test_non_behavioral_edits_do_not_change_behavioral_hash(self, _name: str, before: dict, after: dict) -> None:+ self.assertEqual(+ extract_behavioral_leaf_shape_hash(self._filters(self._behavioral(), before)),+ extract_behavioral_leaf_shape_hash(self._filters(self._behavioral(), after)),+ )++ def test_numeric_fields_match_rust_integer_parsing(self) -> None:+ rust_defaults = self._filters(self._behavioral(time_value=None, operator_value=None))+ invalid_numbers = self._filters(self._behavioral(time_value="30", operator_value=3.0))+ integers = self._filters(self._behavioral(time_value=30, operator_value=3))++ self.assertEqual(+ extract_behavioral_leaf_shape_hash(rust_defaults),+ extract_behavioral_leaf_shape_hash(invalid_numbers),+ )+ self.assertNotEqual(+ extract_behavioral_leaf_shape_hash(rust_defaults),+ extract_behavioral_leaf_shape_hash(integers),+ )++ def test_leaves_nested_in_inner_groups_are_walked(self) -> None:+ # Real cohorts nest leaves inside inner OR/AND groups; the hash must be identical to the+ # flat form and non-empty, so a regression that stopped recursing past the top level+ # (silently dropping nested leaves to an empty hash) is caught.+ nested = {+ "properties": {+ "type": "OR",+ "values": [+ {+ "type": "AND",+ "values": [+ {"type": "OR", "values": [self._behavioral()]},+ ],+ }+ ],+ }+ }+ flat_hash = extract_behavioral_leaf_shape_hash(self._filters(self._behavioral()))+ self.assertNotEqual(flat_hash, "")+ self.assertEqual(extract_behavioral_leaf_shape_hash(nested), flat_hash)++ 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.assertEqual(list(walk_filter_leaves({"type": "AND", "values": None})), [])diff --git a/products/cohorts/backend/realtime_teams.py b/products/cohorts/backend/realtime_teams.pynew file mode 100644index 000000000000..19227bf642c5--- /dev/null+++ b/products/cohorts/backend/realtime_teams.py@@ -0,0 +1,37 @@+from django.conf import settings++# Matches the Rust range-span cap in rust/common/types/src/cohort.rs.+_MAX_RANGE_SPAN = 100_000+++def is_realtime_cohort_team(team_id: int) -> bool:+ """Whether the realtime-cohort pipeline is scoped to ``team_id``.++ Mirrors the Rust ``TeamAllowlist`` grammar (``rust/common/types/src/cohort.rs``) that parses+ ``REALTIME_COHORT_TEAM_ALLOWLIST`` — keep the two in sync so Django's edit-time readiness+ invalidation covers exactly the teams Rust maintains realtime membership for.++ Grammar: empty / ``all`` / ``*`` match every team; ``none`` matches none; otherwise a comma list+ of signed integer ids and inclusive ``start:end`` ranges (each capped at ``_MAX_RANGE_SPAN``).+ Malformed tokens are ignored — the Rust side rejects the whole value at startup.+ """+ raw_allowlist = settings.REALTIME_COHORT_TEAM_ALLOWLIST.strip()+ if raw_allowlist == "" or raw_allowlist.lower() == "all" or raw_allowlist == "*":+ return True+ if raw_allowlist.lower() == "none":+ return False++ for part in (segment.strip() for segment in raw_allowlist.split(",")):+ if not part:+ continue+ start_raw, is_range, end_raw = part.partition(":")+ try:+ if is_range:+ start, end = int(start_raw.strip()), int(end_raw.strip())+ else:+ start = end = int(part)+ except ValueError:+ continue+ if start <= end <= start + _MAX_RANGE_SPAN - 1 and start <= team_id <= end:+ return True+ return Falsediff --git a/products/cohorts/backend/test/test_realtime_teams.py b/products/cohorts/backend/test/test_realtime_teams.pynew file mode 100644index 000000000000..8fe90cc37abc--- /dev/null+++ b/products/cohorts/backend/test/test_realtime_teams.py@@ -0,0 +1,60 @@+import os+import importlib++from unittest import mock++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++import posthog.settings.cohorts as cohorts_settings++from products.cohorts.backend.realtime_teams import is_realtime_cohort_team+++class TestIsRealtimeCohortTeam(SimpleTestCase):+ @parameterized.expand(+ [+ ("all_keyword", "all", 999, True),+ ("all_uppercase", "ALL", 999, True),+ ("star", "*", 999, True),+ ("empty", "", 999, True),+ ("whitespace_only", " ", 999, True),+ ("none_keyword", "none", 2, False),+ ("none_uppercase", "NONE", 2, False),+ ("single_match", "2", 2, True),+ ("single_miss", "2", 3, False),+ ("list_match", "2, 42 ,7", 42, True),+ ("list_miss", "2, 42 ,7", 8, False),+ ("range_low_bound", "1:3", 1, True),+ ("range_mid", "1:3", 2, True),+ ("range_high_bound", "1:3", 3, True),+ ("range_miss", "1:3", 4, False),+ ("range_and_id_hits_id", "1:2,5", 5, True),+ ("range_and_id_hits_range", "1:2,5", 1, True),+ ("max_span_range_ok", "1:100000", 100000, True),+ ("garbage", "nope", 2, False),+ ("inverted_range", "3:1", 2, False),+ ("oversized_range", "1:100002", 2, False),+ ("valid_id_beside_garbage", "2,x", 2, True),+ ]+ )+ def test_membership_matches_rust_grammar(self, _name: str, allowlist: str, team_id: int, expected: bool) -> None:+ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST=allowlist):+ self.assertEqual(is_realtime_cohort_team(team_id), expected)+++class TestRealtimeCohortAllowlistSetting(SimpleTestCase):+ def _reload_allowlist(self) -> str:+ self.addCleanup(importlib.reload, cohorts_settings)+ importlib.reload(cohorts_settings)+ return cohorts_settings.REALTIME_COHORT_TEAM_ALLOWLIST++ def test_unset_defaults_to_off(self) -> None:+ with mock.patch.dict(os.environ):+ os.environ.pop("REALTIME_COHORT_TEAM_ALLOWLIST", None)+ self.assertEqual(self._reload_allowlist(), "none")++ def test_set_but_empty_value_is_preserved(self) -> None:+ with mock.patch.dict(os.environ, {"REALTIME_COHORT_TEAM_ALLOWLIST": ""}):+ self.assertEqual(self._reload_allowlist(), "")diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 9d181fbafa7d..7ea5278749f6 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -765,6 +765,8 @@"posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at","posthog_cohort"."last_backfill_events_at",+ "posthog_cohort"."filters_shape_hash",+ "posthog_cohort"."behavioral_filters_shape_hash","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -1135,6 +1137,8 @@"posthog_cohort"."last_error_at","posthog_cohort"."last_backfill_person_properties_at","posthog_cohort"."last_backfill_events_at",+ "posthog_cohort"."filters_shape_hash",+ "posthog_cohort"."behavioral_filters_shape_hash","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",