: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 django foundation (#75079)
Matheus Batista6f9bf4aafe27
diff --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 273e74e505ee..660fb568f6e2 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@@ -159,6 +159,7 @@'last_calculation_duration_ms','last_realtime_cohort_calculation_at','name',+ 'person_filters_shape_hash','query',])# ---@@ -502,7 +503,7 @@'_insert_batch_via_personhog','_insert_resolved_batch','_insert_users_list_with_batching',- '_maintain_behavioral_shape',+ '_maintain_filter_shape_hashes','_meta','_safe_reset_calculating_state','_safe_save_cohort_state',diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.pyindex 2ad06fbe14c0..b5c8c0d3dc7b 100644--- a/posthog/settings/cohorts.py+++ b/posthog/settings/cohorts.py@@ -11,6 +11,22 @@ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED: bool = get_from_env(BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED: bool = get_from_env("BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED", False, type_cast=str_to_bool)+BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS: int = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS", 64, type_cast=int+)+BEHAVIORAL_BACKFILL_PERSON_DEFAULT_HORIZON_DAYS: int = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_DEFAULT_HORIZON_DAYS", 90, type_cast=int+)+# Bounds the estimated total person-seed bytes emitted by one team run.+BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET: int = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET", 0, type_cast=int+)+BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED: bool = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED", False, type_cast=str_to_bool+)+BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED: bool = get_from_env(+ "BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED", False, type_cast=str_to_bool+)BEHAVIORAL_BACKFILL_FINALIZER_ENABLED: bool = get_from_env("BEHAVIORAL_BACKFILL_FINALIZER_ENABLED", False, type_cast=str_to_bool)diff --git a/products/cohorts/backend/backfill/__init__.py b/products/cohorts/backend/backfill/__init__.pyindex 8d1646ed0b3f..5a68ac42b452 100644--- a/products/cohorts/backend/backfill/__init__.py+++ b/products/cohorts/backend/backfill/__init__.py@@ -1,19 +1,35 @@-from products.cohorts.backend.backfill.pinning import derive_window_days, pin_conditions_for_cohorts+from products.cohorts.backend.backfill.pinning import (+ PersonPinningCapExceeded,+ derive_window_days,+ pin_conditions_for_cohorts,+ pin_person_conditions_for_cohorts,+)from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash, stamp_events_readinessfrom products.cohorts.backend.backfill.runs import (+ check_person_run_preconditions,check_run_preconditions,create_backfill_run_for_cohort,+ create_person_backfill_run_for_cohort,+ create_person_team_backfill_run,create_team_backfill_run,supersede_active_runs,)+from products.cohorts.backend.backfill.sizing import PersonSeedEstimate, estimate_person_seed_topic_bytes__all__ = [+ "PersonPinningCapExceeded",+ "PersonSeedEstimate",+ "check_person_run_preconditions","check_run_preconditions","create_backfill_run_for_cohort",+ "create_person_backfill_run_for_cohort",+ "create_person_team_backfill_run","create_team_backfill_run","derive_window_days","ensure_filters_shape_hash",+ "estimate_person_seed_topic_bytes","pin_conditions_for_cohorts",+ "pin_person_conditions_for_cohorts","stamp_events_readiness","supersede_active_runs",]diff --git a/products/cohorts/backend/backfill/pinning.py b/products/cohorts/backend/backfill/pinning.pyindex d282e9402a99..92af067a38f3 100644--- a/products/cohorts/backend/backfill/pinning.py+++ b/products/cohorts/backend/backfill/pinning.py@@ -1,10 +1,17 @@from collections.abc import Iterablefrom typing import Any+import structlog+from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.leaf_shape import walk_filter_leaves_INTERVAL_DAYS = {"day": 1, "week": 7, "month": 30, "year": 365}+logger = structlog.get_logger(__name__)+++class PersonPinningCapExceeded(ValueError):+ passdef derive_window_days(time_value: object, time_interval: object) -> int:@@ -54,3 +61,31 @@ def pin_conditions_for_cohorts(cohorts: Iterable[Cohort]) -> tuple[dict[str, Anyconditions.sort(key=lambda item: (item["cohort_id"], item["condition_hash"], item["event_name"] or ""))return {"schema_version": 1, "conditions": conditions}, sorted(event_names)+++def pin_person_conditions_for_cohorts(cohorts: Iterable[Cohort], *, max_conditions: int) -> dict[str, Any]:+ conditions: list[dict[str, Any]] = []++ for cohort in sorted(cohorts, key=lambda item: item.id):+ dropped = 0+ properties = (cohort.filters or {}).get("properties")+ for leaf in walk_filter_leaves(properties):+ if leaf.get("type") != "person":+ continue+ condition_hash = leaf.get("conditionHash")+ if condition_hash is None:+ dropped += 1+ continue+ conditions.append({"cohort_id": cohort.id, "condition_hash": condition_hash})+ if len(conditions) > max_conditions:+ raise PersonPinningCapExceeded(f"Person backfill has more than {max_conditions} pinned conditions")++ if dropped:+ logger.warning(+ "cohort_person_backfill_hashless_leaves_dropped",+ cohort_id=cohort.id,+ dropped=dropped,+ )++ conditions.sort(key=lambda item: (item["cohort_id"], item["condition_hash"]))+ return {"schema_version": 1, "conditions": conditions}diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.pyindex 3eaecc4208d0..cc429cb51e61 100644--- a/products/cohorts/backend/backfill/readiness.py+++ b/products/cohorts/backend/backfill/readiness.py@@ -9,7 +9,11 @@ from products.cohorts.backend.models.backfill import (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+from products.cohorts.backend.models.leaf_shape import (+ extract_behavioral_leaf_shape_hash,+ extract_leaf_shape_hash,+ extract_person_leaf_shape_hash,+)logger = structlog.get_logger(__name__)@@ -38,6 +42,18 @@ def ensure_filters_shape_hash(cohort: Cohort) -> str:else:cohort.refresh_from_db(fields=["behavioral_filters_shape_hash"])+ if cohort.__dict__.get("person_filters_shape_hash") is None:+ person_shape_hash = extract_person_leaf_shape_hash(cohort.filters)+ updated = Cohort.objects.filter(+ id=cohort.id,+ team_id=cohort.team_id,+ person_filters_shape_hash__isnull=True,+ ).update(person_filters_shape_hash=person_shape_hash)+ if updated:+ cohort.person_filters_shape_hash = person_shape_hash+ else:+ cohort.refresh_from_db(fields=["person_filters_shape_hash"])+return cohort.filters_shape_hash or ""@@ -45,7 +61,7 @@ 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``).+ ``last_backfill_events_at`` when the behavioral leaves change (see ``_maintain_filter_shape_hashes``).A person-property or cohort-reference edit mid-backfill shifts the full hash without touchingevents readiness, so keying on the full hash would wrongly supersede a still-valid events backfill.diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.pyindex 7d60df39ad8c..e4bce4092f08 100644--- a/products/cohorts/backend/backfill/runs.py+++ b/products/cohorts/backend/backfill/runs.py@@ -1,5 +1,5 @@from collections.abc import Iterable-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom django.conf import settings@@ -7,10 +7,17 @@ from django.db import transactionfrom django.db.models.functions import Nowfrom django.utils import timezone as django_timezone+import structlog+from posthog.models.team.team import Team-from products.cohorts.backend.backfill.pinning import pin_conditions_for_cohorts+from products.cohorts.backend.backfill.pinning import (+ PersonPinningCapExceeded,+ pin_conditions_for_cohorts,+ pin_person_conditions_for_cohorts,+)from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash+from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytesfrom products.cohorts.backend.models.backfill import (ACTIVE_COHORT_BACKFILL_RUN_STATUSES,CohortBackfillKind,@@ -24,6 +31,8 @@ from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.leaf_shape import walk_filter_leavesfrom products.cohorts.backend.realtime_teams import is_realtime_cohort_team+logger = structlog.get_logger(__name__)+def check_run_preconditions() -> tuple[dict[str, Any], list[str]]:preconditions = {@@ -42,11 +51,57 @@ def check_run_preconditions() -> tuple[dict[str, Any], list[str]]:return preconditions, missing+def check_person_run_preconditions(*, requires_sizing_attestation: bool) -> tuple[dict[str, Any], list[str]]:+ """Person-run gates: the behavioral ones plus person-record TTL, and sizing for team runs.++ TTL is not scope-dependent — every person seed lands in the same ``cf_person_records`` store,+ whose retention Django cannot see (the seeder reads ``COHORT_PERSON_RECORD_TTL_DAYS``), so an+ operator has to attest it for any kind of person run. Only the team creator estimates topic+ bytes, so only it requires the sizing attestation.+ """+ preconditions, missing = check_run_preconditions()+ preconditions["person_ttl_attested"] = settings.BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED+ if not preconditions["person_ttl_attested"]:+ missing.append("person record TTL")+ if requires_sizing_attestation:+ preconditions["person_sizing_attested"] = settings.BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED+ if not preconditions["person_sizing_attested"]:+ missing.append("person seed sizing")+ 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 _has_pinnable_person_filters(cohort: Cohort) -> bool:+ properties = (cohort.filters or {}).get("properties")+ return any(+ leaf.get("type") == "person" and leaf.get("conditionHash") is not None+ for leaf in walk_filter_leaves(properties)+ )+++def _contains_person_metadata_leaf(cohort: Cohort) -> bool:+ properties = (cohort.filters or {}).get("properties")+ return any(leaf.get("type") == "person_metadata" for leaf in walk_filter_leaves(properties))+++def _person_backfill_ineligibility_reason(cohort: Cohort) -> str | None:+ if cohort.cohort_type != CohortType.REALTIME:+ return "not realtime"+ if cohort.is_static:+ return "static"+ if cohort.deleted:+ return "deleted"+ if _contains_person_metadata_leaf(cohort):+ return "contains person_metadata filters"+ if not _has_pinnable_person_filters(cohort):+ return "has no person filter with a condition hash"+ return None++def _run_status(preconditions_missing: list[str]) -> tuple[str, str]:if preconditions_missing:reason = f"Missing operator attestations: {', '.join(preconditions_missing)}"@@ -59,12 +114,13 @@ def _pinned_payload(cohorts: Iterable[Cohort]) -> dict[str, Any]:return {**pinned, "event_names": event_names}-def _active_participation_cohort_ids(team_id: int, cohort_ids: Iterable[int]) -> set[int]:+def _active_participation_cohort_ids(team_id: int, cohort_ids: Iterable[int], *, kind: CohortBackfillKind) -> set[int]:return set(CohortBackfillRunCohort.objects.for_team(team_id).filter(cohort_id__in=cohort_ids,superseded_at__isnull=True,+ run__backfill_kind=kind,run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,).values_list("cohort_id", flat=True)@@ -90,7 +146,7 @@ def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: sor not _has_behavioral_filters(cohort)):return None- if _active_participation_cohort_ids(team_id, [cohort_id]):+ if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.BEHAVIORAL):return Nonefilters_shape_hash = ensure_filters_shape_hash(cohort)@@ -120,6 +176,19 @@ def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: sreturn run+def _validate_boundary_at(trigger_kind: str, boundary_at: datetime | None) -> datetime | None:+ if boundary_at is None:+ return None+ if trigger_kind != CohortBackfillTrigger.DISASTER_RECOVERY:+ raise ValueError("boundary_at is only valid for disaster recovery runs")+ if django_timezone.is_naive(boundary_at):+ raise ValueError("boundary_at must include a UTC offset")+ try:+ return boundary_at.astimezone(UTC)+ except OverflowError as error:+ raise ValueError("boundary_at falls outside the supported UTC range") from error++def create_team_backfill_run(team_id: int,trigger_kind: str,@@ -130,15 +199,7 @@ def create_team_backfill_run(if not is_realtime_cohort_team(team_id):raise ValueError(f"Team {team_id} is not in the realtime cohort allowlist")- if boundary_at is not None:- if trigger_kind != CohortBackfillTrigger.DISASTER_RECOVERY:- raise ValueError("boundary_at is only valid for disaster recovery runs")- if django_timezone.is_naive(boundary_at):- raise ValueError("boundary_at must include a UTC offset")- try:- boundary_at = boundary_at.astimezone(UTC)- except OverflowError as error:- raise ValueError("boundary_at falls outside the supported UTC range") from error+ boundary_at = _validate_boundary_at(trigger_kind, boundary_at)requested_ids = set(cohort_ids) if cohort_ids is not None else Nonewith transaction.atomic():@@ -157,7 +218,9 @@ def create_team_backfill_run(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])+ conflicting_ids = _active_participation_cohort_ids(+ team_id, [cohort.id for cohort in cohorts], kind=CohortBackfillKind.BEHAVIORAL+ )if conflicting_ids:raise ValueError(f"Cohorts already have active backfill runs: {sorted(conflicting_ids)}")@@ -197,7 +260,206 @@ def create_team_backfill_run(return run-def supersede_active_runs(team_id: int, cohort_ids: Iterable[int]) -> int:+def create_person_backfill_run_for_cohort(+ team_id: int,+ cohort_id: int,+ trigger_kind: str,+ *,+ person_horizon_days: int | None = None,+) -> CohortBackfillRun | None:+ """Create one cohort's person-property run, on the signal path's contract.++ Unlike ``create_person_team_backfill_run`` this never raises and never touches ClickHouse: it+ becomes the target of the person counterpart to the behavioral shape-changed receiver (B7.3b),+ where a refusal has to warn and return rather than fail the Celery task. That is also why the+ horizon defaults from settings here but is required on the operator-driven team creator.+ """+ if not is_realtime_cohort_team(team_id):+ return None++ horizon_days = (+ person_horizon_days+ if person_horizon_days is not None+ else settings.BEHAVIORAL_BACKFILL_PERSON_DEFAULT_HORIZON_DAYS+ )+ if horizon_days < 1:+ logger.warning(+ "cohort_person_backfill_invalid_horizon",+ team_id=team_id,+ cohort_id=cohort_id,+ person_horizon_days=horizon_days,+ )+ 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 _person_backfill_ineligibility_reason(cohort) is not None:+ return None+ if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.PERSON_PROPERTY):+ return None++ try:+ pinned = pin_person_conditions_for_cohorts(+ [cohort],+ max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ )+ except PersonPinningCapExceeded:+ logger.warning(+ "cohort_person_backfill_pinning_cap_exceeded",+ team_id=team_id,+ cohort_id=cohort_id,+ max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ )+ return None++ filters_shape_hash = ensure_filters_shape_hash(cohort)+ person_filters_shape_hash = cohort.person_filters_shape_hash or ""+ preconditions, missing = check_person_run_preconditions(requires_sizing_attestation=False)+ status, blocked_reason = _run_status(missing)+ person_scan_since = django_timezone.now() - timedelta(days=horizon_days)+ run = CohortBackfillRun.objects.for_team(team_id).create(+ team_id=team_id,+ cohort=cohort,+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY,+ trigger_kind=trigger_kind,+ scope=CohortBackfillScope.COHORT,+ status=status,+ timezone=cohort.team.timezone,+ person_scan_since=person_scan_since,+ pinned={**pinned, "person_horizon_days": horizon_days},+ 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,+ person_filters_shape_hash=person_filters_shape_hash,+ pinned_filters=cohort.filters,+ )+ return run+++def _person_cohorts_for_team(team_id: int, requested_ids: set[int] | None, *, lock: bool) -> list[Cohort]:+ # Narrow on the SQL-expressible half of eligibility before locking: `select_for_update` locks+ # every row the query returns, so an unnarrowed team scan would hold `FOR UPDATE` on static,+ # deleted, and non-realtime cohorts that were never candidates, blocking edits to them.+ queryset = Cohort.objects.filter(+ team_id=team_id,+ cohort_type=CohortType.REALTIME,+ is_static=False,+ deleted=False,+ )+ if lock:+ queryset = queryset.select_for_update(of=("self",))+ if requested_ids is not None:+ queryset = queryset.filter(id__in=requested_ids)+ candidates = list(queryset.order_by("id"))+ cohorts = [cohort for cohort in candidates if _person_backfill_ineligibility_reason(cohort) is None]++ 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 person-property cohorts: {invalid_ids}")+ if not cohorts:+ raise ValueError(f"Team {team_id} has no eligible realtime person-property cohorts")+ return cohorts+++def create_person_team_backfill_run(+ team_id: int,+ trigger_kind: str,+ person_horizon_days: int,+ cohort_ids: Iterable[int] | None = None,+ created_by_id: int | None = None,+ boundary_at: datetime | None = None,+) -> CohortBackfillRun:+ if not is_realtime_cohort_team(team_id):+ raise ValueError(f"Team {team_id} is not in the realtime cohort allowlist")+ if person_horizon_days < 1:+ raise ValueError("person_horizon_days must be at least 1")++ boundary_at = _validate_boundary_at(trigger_kind, boundary_at)+ preconditions, missing = check_person_run_preconditions(requires_sizing_attestation=True)+ if missing:+ raise ValueError(f"Missing operator attestations: {', '.join(missing)}")++ requested_ids = set(cohort_ids) if cohort_ids is not None else None+ cohorts = _person_cohorts_for_team(team_id, requested_ids, lock=False)+ pinned = pin_person_conditions_for_cohorts(+ cohorts,+ max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ )+ person_scan_since = (boundary_at or django_timezone.now()) - timedelta(days=person_horizon_days)+ estimate = estimate_person_seed_topic_bytes(+ team_id,+ person_scan_since,+ len(pinned["conditions"]),+ )+ if estimate.over_budget:+ raise ValueError(+ f"Estimated person seed topic bytes {estimate.estimated_topic_bytes} exceed budget {estimate.budget_bytes}"+ )++ with transaction.atomic():+ team = Team.objects.get(id=team_id)+ cohorts = _person_cohorts_for_team(team_id, requested_ids, lock=True)+ locked_pinned = pin_person_conditions_for_cohorts(+ cohorts,+ max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ )+ if locked_pinned != pinned:+ raise ValueError("Cohort person-property definitions changed during sizing; retry the run")++ conflicting_ids = _active_participation_cohort_ids(+ team_id,+ [cohort.id for cohort in cohorts],+ kind=CohortBackfillKind.PERSON_PROPERTY,+ )+ if conflicting_ids:+ raise ValueError(f"Cohorts already have active person-property backfill runs: {sorted(conflicting_ids)}")++ hashes: dict[int, str] = {}+ person_hashes: dict[int, str] = {}+ for cohort in cohorts:+ hashes[cohort.id] = ensure_filters_shape_hash(cohort)+ person_hashes[cohort.id] = cohort.person_filters_shape_hash or ""++ run = CohortBackfillRun.objects.for_team(team_id).create(+ team_id=team_id,+ created_by_id=created_by_id,+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY,+ trigger_kind=trigger_kind,+ scope=CohortBackfillScope.TEAM,+ status=CohortBackfillRunStatus.AWAITING_BOUNDARY,+ boundary_at=boundary_at,+ person_scan_since=person_scan_since,+ timezone=team.timezone,+ pinned={**pinned, "person_horizon_days": person_horizon_days},+ preconditions={**preconditions, **estimate.as_preconditions()},+ )+ CohortBackfillRunCohort.objects.for_team(team_id).bulk_create(+ [+ CohortBackfillRunCohort(+ run=run,+ team_id=team_id,+ cohort=cohort,+ filters_shape_hash=hashes[cohort.id],+ person_filters_shape_hash=person_hashes[cohort.id],+ pinned_filters=cohort.filters,+ )+ for cohort in cohorts+ ]+ )+ return run+++def supersede_active_runs(team_id: int, cohort_ids: Iterable[int], *, kind: CohortBackfillKind) -> int:cohort_id_set = set(cohort_ids)if not cohort_id_set:return 0@@ -212,6 +474,7 @@ def supersede_active_runs(team_id: int, cohort_ids: Iterable[int]) -> int:.filter(cohort_id__in=cohort_id_set,superseded_at__isnull=True,+ run__backfill_kind=kind,run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,).values_list("id", "run_id", "run__scope")diff --git a/products/cohorts/backend/backfill/sizing.py b/products/cohorts/backend/backfill/sizing.pynew file mode 100644index 000000000000..33c4e51a1e60--- /dev/null+++ b/products/cohorts/backend/backfill/sizing.py@@ -0,0 +1,81 @@+from dataclasses import dataclass+from datetime import datetime+from typing import Any++from django.conf import settings++from posthog.clickhouse.client import sync_execute++# Calibrated against a serialized `PersonSeed` (rust/cohort-core/src/seed/person.rs): the fixed+# envelope (schema_version, kind, team_id, person_id, scanned_at_ms, run_id, claim_epoch) plus one+# quoted 16-char condition hash in both `evaluated` and `matched` — the worst case, where every+# pinned condition came back TRUE. Recalibrate when that struct's wire fields change.+PERSON_SEED_BASE_BYTES = 256+PERSON_SEED_PER_HASH_BYTES = 38+++@dataclass(frozen=True)+class PersonSeedEstimate:+ estimated_persons: int+ pinned_condition_count: int+ bytes_per_seed: int+ estimated_topic_bytes: int+ budget_bytes: int++ @property+ def over_budget(self) -> bool:+ return self.estimated_topic_bytes > self.budget_bytes++ def as_preconditions(self) -> dict[str, Any]:+ return {+ "person_seed_estimated_persons": self.estimated_persons,+ "person_seed_pinned_condition_count": self.pinned_condition_count,+ "person_seed_bytes_per_seed": self.bytes_per_seed,+ "person_seed_estimated_topic_bytes": self.estimated_topic_bytes,+ "person_seed_topic_bytes_budget": self.budget_bytes,+ }+++def estimate_person_seed_topic_bytes(+ team_id: int,+ person_scan_since: datetime,+ pinned_condition_count: int,+) -> PersonSeedEstimate:+ # `person` is ORDER BY (team_id, id) with only a minmax index on `_timestamp`, and rows are+ # rewritten in place on every update, so the window bound prunes close to nothing: this reads the+ # team's whole person history either way. `max_bytes_to_read` is what actually bounds it, and it+ # throws rather than letting the gate size a run off a partial scan.+ #+ # Collapsing versions per id before counting keeps persons whose latest in-window row is a+ # deletion out of the estimate — counting them inflates the topic-byte figure and biases the+ # budget gate toward refusing runs that would have fit.+ rows = sync_execute(+ """+ SELECT count()+ FROM (+ SELECT id+ FROM person+ WHERE team_id = %(team_id)s+ AND _timestamp >= %(person_scan_since)s+ GROUP BY id+ HAVING argMax(is_deleted, version) = 0+ )+ """,+ {"team_id": team_id, "person_scan_since": person_scan_since},+ settings={+ "max_execution_time": 30,+ "max_bytes_to_read": 10_000_000_000,+ "read_overflow_mode": "throw",+ },+ team_id=team_id,+ readonly=True,+ )+ estimated_persons = int(rows[0][0])+ bytes_per_seed = PERSON_SEED_BASE_BYTES + PERSON_SEED_PER_HASH_BYTES * pinned_condition_count+ return PersonSeedEstimate(+ estimated_persons=estimated_persons,+ pinned_condition_count=pinned_condition_count,+ bytes_per_seed=bytes_per_seed,+ estimated_topic_bytes=estimated_persons * bytes_per_seed,+ budget_bytes=settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET,+ )diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.pyindex 6297765a8879..160ff5a06fa6 100644--- a/products/cohorts/backend/backfill/test/test_finalize.py+++ b/products/cohorts/backend/backfill/test/test_finalize.py@@ -166,6 +166,29 @@ class TestBackfillFinalizer(BaseTest):self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)self.assertIsNone(cohorts[0].last_backfill_events_at)+ def test_observed_person_run_is_untouched(self) -> None:+ run = CohortBackfillRun.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY,+ trigger_kind=CohortBackfillTrigger.TEAM_ENABLEMENT,+ scope=CohortBackfillScope.TEAM,+ status=CohortBackfillRunStatus.RECONCILING,+ reconcile_observed_at=timezone.now(),+ timezone="UTC",+ )+ cohort, participation = self._make_participation(run, "completed")++ result = finalize_backfill_runs()++ run.refresh_from_db()+ cohort.refresh_from_db()+ participation.refresh_from_db()+ self.assertEqual(result.runs_scanned, 0)+ self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)+ self.assertIsNone(cohort.last_backfill_events_at)+ self.assertIsNone(cohort.last_backfill_person_properties_at)+ self.assertIsNone(participation.stamped_at)+def test_second_fire_is_a_noop(self) -> None:run, _cohorts = self._make_run(["completed", "completed"])diff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.pyindex 6a7e5cc1bb5b..af191767e572 100644--- a/products/cohorts/backend/backfill/test/test_management_command.py+++ b/products/cohorts/backend/backfill/test/test_management_command.py@@ -10,7 +10,13 @@ from django.test import override_settingsfrom parameterized import parameterized-from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBackfillRunCohort, CohortBackfillRunStatus+from products.cohorts.backend.backfill.sizing import PersonSeedEstimate+from products.cohorts.backend.models.backfill import (+ CohortBackfillKind,+ CohortBackfillRun,+ CohortBackfillRunCohort,+ CohortBackfillRunStatus,+)from products.cohorts.backend.models.cohort import Cohort, CohortType@@ -18,6 +24,9 @@ from products.cohorts.backend.models.cohort import Cohort, CohortTypeREALTIME_COHORT_TEAM_ALLOWLIST="all",BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,)class TestCreateCohortBackfillRunCommand(BaseTest):def setUp(self) -> None:@@ -50,6 +59,45 @@ class TestCreateCohortBackfillRunCommand(BaseTest):},)+ def _person_cohort(self, *, person_metadata: bool = False) -> Cohort:+ values = [+ {+ "type": "person",+ "key": "email",+ "value": ["[email protected]"],+ "operator": "exact",+ "conditionHash": "person0000000001",+ }+ ]+ if person_metadata:+ values.append(+ {+ "type": "person_metadata",+ "key": "created_at",+ "value": "2026-01-01",+ "operator": "is_date_after",+ }+ )+ return Cohort.objects.create(+ team=self.team,+ cohort_type=CohortType.REALTIME,+ filters={"properties": {"type": "AND", "values": values}},+ )++ def _estimate(+ self,+ *,+ estimated_topic_bytes: int = 2_940,+ budget_bytes: int = 1_000_000,+ ) -> PersonSeedEstimate:+ return PersonSeedEstimate(+ estimated_persons=10,+ pinned_condition_count=1,+ bytes_per_seed=294,+ estimated_topic_bytes=estimated_topic_bytes,+ budget_bytes=budget_bytes,+ )+@override_settings(BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=False)def test_missing_attestation_errors_without_writing(self) -> None:self._cohort("$pageview")@@ -185,3 +233,118 @@ class TestCreateCohortBackfillRunCommand(BaseTest):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")++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_person_kind_creates_sized_team_run(self, estimate: mock.Mock) -> None:+ cohort = self._person_cohort()+ estimate.return_value = self._estimate()+ stdout = StringIO()++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ kind="person_property",+ person_horizon_days=30,+ stdout=stdout,+ )++ run = CohortBackfillRun.objects.for_team(self.team.id).get()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(run.backfill_kind, CohortBackfillKind.PERSON_PROPERTY)+ self.assertEqual(run.pinned["person_horizon_days"], 30)+ self.assertEqual(participation.cohort_id, cohort.id)+ self.assertIn("Created person-property run", stdout.getvalue())+ self.assertIn("10 estimated persons", stdout.getvalue())++ @parameterized.expand(+ [+ (+ "person_missing",+ {"kind": "person_property"},+ "--person-horizon-days is required",+ ),+ (+ "behavioral_present",+ {"kind": "behavioral", "person_horizon_days": 30},+ "--person-horizon-days is only valid",+ ),+ ]+ )+ def test_person_horizon_kind_validation(+ self,+ _name: str,+ options: dict[str, object],+ expected_error: str,+ ) -> None:+ with self.assertRaisesMessage(CommandError, expected_error):+ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ **options,+ )++ @mock.patch(+ "products.cohorts.backend.management.commands.create_cohort_backfill_run.estimate_person_seed_topic_bytes"+ )+ def test_person_dry_run_prints_estimate_without_writing(self, estimate: mock.Mock) -> None:+ self._person_cohort()+ estimate.return_value = self._estimate()+ stdout = StringIO()++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ kind="person_property",+ person_horizon_days=30,+ dry_run=True,+ stdout=stdout,+ )++ self.assertIn("10 estimated persons", stdout.getvalue())+ self.assertIn("would refuse: no", stdout.getvalue())+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_person_over_budget_returns_clean_command_error(self, estimate: mock.Mock) -> None:+ self._person_cohort()+ estimate.return_value = self._estimate(+ estimated_topic_bytes=1_000_001,+ budget_bytes=1_000_000,+ )++ with self.assertRaisesMessage(CommandError, "exceed budget"):+ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ kind="person_property",+ person_horizon_days=30,+ )++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ @mock.patch(+ "products.cohorts.backend.management.commands.create_cohort_backfill_run.estimate_person_seed_topic_bytes"+ )+ def test_person_metadata_refusal_is_reported_in_dry_run(self, estimate: mock.Mock) -> None:+ eligible = self._person_cohort()+ refused = self._person_cohort(person_metadata=True)+ estimate.return_value = self._estimate()+ stdout = StringIO()++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="team_enablement",+ kind="person_property",+ person_horizon_days=30,+ dry_run=True,+ stdout=stdout,+ )++ self.assertIn(f"{refused.id} (contains person_metadata filters)", stdout.getvalue())+ self.assertIn("1 cohorts", stdout.getvalue())+ self.assertNotIn(f"{eligible.id} (", stdout.getvalue())diff --git a/products/cohorts/backend/backfill/test/test_pinning.py b/products/cohorts/backend/backfill/test/test_pinning.pyindex 8427f7136d43..8bdf3471b1e5 100644--- a/products/cohorts/backend/backfill/test/test_pinning.py+++ b/products/cohorts/backend/backfill/test/test_pinning.py@@ -1,8 +1,15 @@+from unittest import mock+from django.test import SimpleTestCasefrom parameterized import parameterized-from products.cohorts.backend.backfill.pinning import derive_window_days, pin_conditions_for_cohorts+from products.cohorts.backend.backfill.pinning import (+ PersonPinningCapExceeded,+ derive_window_days,+ pin_conditions_for_cohorts,+ pin_person_conditions_for_cohorts,+)from products.cohorts.backend.models.cohort import Cohort@@ -103,3 +110,88 @@ class TestBackfillPinning(SimpleTestCase):action = next(item for item in pinned["conditions"] if item["condition_hash"] == "cccccccccccccccc")self.assertTrue(action["is_action"])self.assertIsNone(action["event_name"])++ def test_person_conditions_are_sorted_and_preserved_per_cohort(self) -> None:+ second = Cohort(+ id=2,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {"type": "person", "conditionHash": "bbbbbbbbbbbbbbbb"},+ {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"},+ ],+ }+ },+ )+ first = Cohort(+ id=1,+ filters={+ "properties": {+ "type": "AND",+ "values": [{"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}],+ }+ },+ )++ pinned = pin_person_conditions_for_cohorts([second, first], max_conditions=3)++ self.assertEqual(+ pinned,+ {+ "schema_version": 1,+ "conditions": [+ {"cohort_id": 1, "condition_hash": "aaaaaaaaaaaaaaaa"},+ {"cohort_id": 2, "condition_hash": "aaaaaaaaaaaaaaaa"},+ {"cohort_id": 2, "condition_hash": "bbbbbbbbbbbbbbbb"},+ ],+ },+ )++ def test_hashless_person_leaf_is_dropped_with_warning(self) -> None:+ cohort = Cohort(+ id=7,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {"type": "person", "conditionHash": None},+ {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"},+ ],+ }+ },+ )++ with mock.patch("products.cohorts.backend.backfill.pinning.logger") as logger:+ pinned = pin_person_conditions_for_cohorts([cohort], max_conditions=1)++ self.assertEqual(+ pinned["conditions"],+ [{"cohort_id": 7, "condition_hash": "aaaaaaaaaaaaaaaa"}],+ )+ logger.warning.assert_called_once_with(+ "cohort_person_backfill_hashless_leaves_dropped",+ cohort_id=7,+ dropped=1,+ )++ def test_person_condition_cap_accepts_boundary_and_rejects_next_leaf(self) -> None:+ cohort = Cohort(+ id=7,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"},+ {"type": "person", "conditionHash": "bbbbbbbbbbbbbbbb"},+ ],+ }+ },+ )++ self.assertEqual(+ len(pin_person_conditions_for_cohorts([cohort], max_conditions=2)["conditions"]),+ 2,+ )+ with self.assertRaises(PersonPinningCapExceeded):+ pin_person_conditions_for_cohorts([cohort], max_conditions=1)diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.pyindex e9f7c425d4bc..5a5945ba75ba 100644--- a/products/cohorts/backend/backfill/test/test_readiness.py+++ b/products/cohorts/backend/backfill/test/test_readiness.py@@ -10,7 +10,7 @@ from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hasfrom products.cohorts.backend.backfill.runs import create_backfill_run_for_cohortfrom products.cohorts.backend.models.backfill import CohortBackfillRunCohort, CohortBackfillRunStatusfrom products.cohorts.backend.models.cohort import Cohort, CohortType-from products.cohorts.backend.models.leaf_shape import extract_leaf_shape_hash+from products.cohorts.backend.models.leaf_shape import extract_leaf_shape_hash, extract_person_leaf_shape_hash@override_settings(@@ -188,13 +188,24 @@ class TestBackfillReadiness(BaseTest):Cohort.objects.filter(id=cohort.id).update(filters_shape_hash=None,behavioral_filters_shape_hash=None,+ person_filters_shape_hash=None,)cohort.filters_shape_hash = Nonecohort.behavioral_filters_shape_hash = None+ cohort.person_filters_shape_hash = Noneself.assertEqual(ensure_filters_shape_hash(cohort), extract_leaf_shape_hash(cohort.filters))self.assertIsNotNone(cohort.behavioral_filters_shape_hash)+ self.assertEqual(+ cohort.person_filters_shape_hash,+ extract_person_leaf_shape_hash(cohort.filters),+ )- Cohort.objects.filter(id=cohort.id).update(filters_shape_hash="persisted")+ Cohort.objects.filter(id=cohort.id).update(+ filters_shape_hash="persisted",+ person_filters_shape_hash="persisted-person",+ )cohort.filters_shape_hash = None+ cohort.person_filters_shape_hash = Noneself.assertEqual(ensure_filters_shape_hash(cohort), "persisted")+ self.assertEqual(cohort.person_filters_shape_hash, "persisted-person")diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.pyindex e85ee7936cd5..9e57e56a8c43 100644--- a/products/cohorts/backend/backfill/test/test_runs.py+++ b/products/cohorts/backend/backfill/test/test_runs.py@@ -1,17 +1,27 @@+from datetime import UTC, datetime, timedelta+from posthog.test.base import BaseTestfrom unittest import mock+from django.db import IntegrityError, transactionfrom django.test import override_settings+from parameterized import parameterized+from posthog.tasks.calculate_cohort import trigger_cohort_events_backfill_task+from products.cohorts.backend.backfill.pinning import PersonPinningCapExceededfrom products.cohorts.backend.backfill.runs import (create_backfill_run_for_cohort,+ create_person_backfill_run_for_cohort,+ create_person_team_backfill_run,create_team_backfill_run,supersede_active_runs,)+from products.cohorts.backend.backfill.sizing import PersonSeedEstimatefrom products.cohorts.backend.models.backfill import (CohortBackfillChunk,+ CohortBackfillKind,CohortBackfillRun,CohortBackfillRunCohort,CohortBackfillRunStatus,@@ -117,7 +127,10 @@ class TestBackfillRuns(BaseTest):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)+ self.assertEqual(+ supersede_active_runs(self.team.id, [cohort.id], kind=CohortBackfillKind.BEHAVIORAL),+ 1,+ )run.refresh_from_db()participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)@@ -151,3 +164,340 @@ class TestBackfillRuns(BaseTest):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)+++@override_settings(+ REALTIME_COHORT_TEAM_ALLOWLIST="all",+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,+)+class TestPersonBackfillRuns(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,+ *,+ person_hashes: tuple[str | None, ...] = ("person0000000001",),+ behavioral: bool = True,+ person_metadata: bool = False,+ ) -> dict:+ values: list[dict] = [+ {+ "type": "person",+ "key": "email",+ "value": ["[email protected]"],+ "operator": "exact",+ "conditionHash": condition_hash,+ }+ for condition_hash in person_hashes+ ]+ if behavioral:+ values.append(+ {+ "type": "behavioral",+ "key": "$pageview",+ "event_type": "events",+ "value": "performed_event",+ "conditionHash": "behavior00000001",+ "time_value": 7,+ "time_interval": "day",+ }+ )+ if person_metadata:+ values.append(+ {+ "type": "person_metadata",+ "key": "created_at",+ "value": "2026-01-01",+ "operator": "is_date_after",+ }+ )+ return {"properties": {"type": "AND", "values": values}}++ def _cohort(self, **kwargs: object) -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ name="person cohort",+ cohort_type=CohortType.REALTIME,+ filters=self._filters(),+ **kwargs,+ )++ def _estimate(self, *, estimated_topic_bytes: int = 2_940, budget_bytes: int = 1_000_000) -> PersonSeedEstimate:+ return PersonSeedEstimate(+ estimated_persons=10,+ pinned_condition_count=1,+ bytes_per_seed=294,+ estimated_topic_bytes=estimated_topic_bytes,+ budget_bytes=budget_bytes,+ )++ @parameterized.expand(+ [+ ("explicit_horizon", 30, 30),+ ("default_horizon", None, 45),+ ]+ )+ def test_cohort_run_pins_person_definition_and_scan_horizon(+ self,+ _name: str,+ person_horizon_days: int | None,+ expected_horizon_days: int,+ ) -> None:+ cohort = self._cohort()+ now = datetime(2026, 7, 29, 12, tzinfo=UTC)++ with (+ self.settings(BEHAVIORAL_BACKFILL_PERSON_DEFAULT_HORIZON_DAYS=45),+ mock.patch(+ "products.cohorts.backend.backfill.runs.django_timezone.now",+ return_value=now,+ ),+ ):+ run = create_person_backfill_run_for_cohort(+ self.team.id,+ cohort.id,+ "cohort_created",+ person_horizon_days=person_horizon_days,+ )++ assert run is not None+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(run.backfill_kind, CohortBackfillKind.PERSON_PROPERTY)+ self.assertEqual(run.person_scan_since, now - timedelta(days=expected_horizon_days))+ self.assertEqual(+ run.pinned,+ {+ "schema_version": 1,+ "conditions": [{"cohort_id": cohort.id, "condition_hash": "person0000000001"}],+ "person_horizon_days": expected_horizon_days,+ },+ )+ self.assertEqual(participation.filters_shape_hash, cohort.filters_shape_hash)+ self.assertEqual(participation.behavioral_filters_shape_hash, "")+ self.assertEqual(participation.person_filters_shape_hash, cohort.person_filters_shape_hash)+ self.assertEqual(participation.pinned_filters, cohort.filters)++ def test_behavioral_and_person_runs_coexist_but_duplicate_person_run_is_refused(self) -> None:+ cohort = self._cohort()++ behavioral = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ person = create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")++ self.assertIsNotNone(behavioral)+ self.assertIsNotNone(person)+ self.assertIsNone(create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 2)++ def test_cohort_run_refuses_non_positive_horizon(self) -> None:+ cohort = self._cohort()++ with mock.patch("products.cohorts.backend.backfill.runs.logger") as logger:+ run = create_person_backfill_run_for_cohort(+ self.team.id,+ cohort.id,+ "cohort_created",+ person_horizon_days=0,+ )++ self.assertIsNone(run)+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)+ logger.warning.assert_called_once_with(+ "cohort_person_backfill_invalid_horizon",+ team_id=self.team.id,+ cohort_id=cohort.id,+ person_horizon_days=0,+ )++ @override_settings(BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS=0)+ def test_cohort_run_warns_and_refuses_pinning_cap(self) -> None:+ cohort = self._cohort()++ with mock.patch("products.cohorts.backend.backfill.runs.logger") as logger:+ run = create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")++ self.assertIsNone(run)+ logger.warning.assert_called_once_with(+ "cohort_person_backfill_pinning_cap_exceeded",+ team_id=self.team.id,+ cohort_id=cohort.id,+ max_conditions=0,+ )++ @parameterized.expand(+ [+ ("behavioral", CohortBackfillKind.BEHAVIORAL),+ ("person_property", CohortBackfillKind.PERSON_PROPERTY),+ ]+ )+ def test_supersession_is_scoped_to_run_kind(self, _name: str, superseded_kind: CohortBackfillKind) -> None:+ cohort = self._cohort()+ behavioral = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ person = create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")+ assert behavioral is not None+ assert person is not None++ self.assertEqual(+ supersede_active_runs(self.team.id, [cohort.id], kind=superseded_kind),+ 1,+ )++ behavioral.refresh_from_db()+ person.refresh_from_db()+ expected = {+ CohortBackfillKind.BEHAVIORAL: behavioral,+ CohortBackfillKind.PERSON_PROPERTY: person,+ }+ other = {+ CohortBackfillKind.BEHAVIORAL: person,+ CohortBackfillKind.PERSON_PROPERTY: behavioral,+ }+ self.assertEqual(expected[superseded_kind].status, CohortBackfillRunStatus.SUPERSEDED)+ self.assertEqual(other[superseded_kind].status, CohortBackfillRunStatus.AWAITING_BOUNDARY)++ @parameterized.expand(+ [+ ("behavioral_only", {"filters": None}),+ ("static", {"is_static": True}),+ ("deleted", {"deleted": True}),+ ("non_realtime", {"cohort_type": CohortType.BEHAVIORAL}),+ ("hashless", {"filters": "hashless"}),+ ("person_metadata", {"filters": "person_metadata"}),+ ]+ )+ def test_ineligible_cohort_is_refused(self, _name: str, overrides: dict[str, object]) -> None:+ filters = self._filters()+ if overrides.pop("filters", "") is None:+ filters = self._filters(person_hashes=(), behavioral=True)+ elif _name == "hashless":+ filters = self._filters(person_hashes=(None,), behavioral=False)+ elif _name == "person_metadata":+ filters = self._filters(person_metadata=True)+ cohort_type = overrides.pop("cohort_type", CohortType.REALTIME)+ cohort = Cohort.objects.create(+ team=self.team,+ cohort_type=cohort_type,+ filters=filters,+ **overrides,+ )++ self.assertIsNone(create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created"))++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_team_run_persists_estimate_and_uses_boundary_for_scan_horizon(self, estimate: mock.Mock) -> None:+ cohort = self._cohort()+ estimate.return_value = self._estimate()+ boundary = datetime(2026, 7, 20, 12, tzinfo=UTC)++ run = create_person_team_backfill_run(+ self.team.id,+ "disaster_recovery",+ 30,+ [cohort.id],+ boundary_at=boundary,+ )++ self.assertEqual(run.person_scan_since, boundary - timedelta(days=30))+ self.assertEqual(run.preconditions["person_seed_estimated_persons"], 10)+ self.assertEqual(run.preconditions["person_seed_estimated_topic_bytes"], 2_940)+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(participation.behavioral_filters_shape_hash, "")+ self.assertNotEqual(participation.person_filters_shape_hash, "")++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_per_kind_team_uniqueness(self, estimate: mock.Mock) -> None:+ self._cohort()+ estimate.return_value = self._estimate()+ behavioral = create_team_backfill_run(self.team.id, "team_enablement")+ person = create_person_team_backfill_run(self.team.id, "team_enablement", 30)++ self.assertEqual(behavioral.backfill_kind, CohortBackfillKind.BEHAVIORAL)+ self.assertEqual(person.backfill_kind, CohortBackfillKind.PERSON_PROPERTY)+ with self.assertRaisesMessage(ValueError, "active person-property backfill runs"):+ create_person_team_backfill_run(self.team.id, "team_enablement", 30)++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_team_run_refuses_when_pinned_conditions_drift_during_sizing(self, estimate: mock.Mock) -> None:+ cohort = self._cohort()++ def edit_cohort_mid_sizing(*args: object, **kwargs: object) -> PersonSeedEstimate:+ # The estimate is the whole window the run is sized outside the lock, so drifting the+ # definition here is what the re-pin under `select_for_update` has to catch.+ Cohort.objects.filter(id=cohort.id).update(filters=self._filters(person_hashes=("person0000000002",)))+ return self._estimate()++ estimate.side_effect = edit_cohort_mid_sizing++ with self.assertRaisesMessage(ValueError, "changed during sizing"):+ create_person_team_backfill_run(self.team.id, "team_enablement", 30)++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ def test_active_team_run_uniqueness_index_is_per_kind(self) -> None:+ # Bypasses the creators' pre-check on purpose: this pins the partial unique index migration+ # 0009 swapped in, which is the only guard left if the pre-check is ever refactored away.+ def create_team_run(kind: CohortBackfillKind) -> None:+ CohortBackfillRun.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ backfill_kind=kind,+ trigger_kind="team_enablement",+ scope=CohortBackfillScope.TEAM,+ status=CohortBackfillRunStatus.AWAITING_BOUNDARY,+ timezone="UTC",+ )++ create_team_run(CohortBackfillKind.BEHAVIORAL)+ create_team_run(CohortBackfillKind.PERSON_PROPERTY)++ with self.assertRaises(IntegrityError), transaction.atomic():+ create_team_run(CohortBackfillKind.PERSON_PROPERTY)++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_team_run_refuses_over_budget_estimate(self, estimate: mock.Mock) -> None:+ self._cohort()+ estimate.return_value = self._estimate(+ estimated_topic_bytes=1_000_001,+ budget_bytes=1_000_000,+ )++ with self.assertRaisesMessage(ValueError, "exceed budget"):+ create_person_team_backfill_run(self.team.id, "team_enablement", 30)++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)++ @override_settings(BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS=0)+ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_team_run_refuses_pinning_cap_before_sizing(self, estimate: mock.Mock) -> None:+ self._cohort()++ with self.assertRaises(PersonPinningCapExceeded):+ create_person_team_backfill_run(self.team.id, "team_enablement", 30)++ estimate.assert_not_called()++ @parameterized.expand(+ [+ ("sizing", "BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED", "person seed sizing"),+ ("ttl", "BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED", "person record TTL"),+ ]+ )+ def test_team_run_requires_person_attestations(+ self,+ _name: str,+ setting_name: str,+ expected_error: str,+ ) -> None:+ self._cohort()++ with self.settings(**{setting_name: False}), self.assertRaisesMessage(ValueError, expected_error):+ create_person_team_backfill_run(self.team.id, "team_enablement", 30)diff --git a/products/cohorts/backend/backfill/test/test_sizing.py b/products/cohorts/backend/backfill/test/test_sizing.pynew file mode 100644index 000000000000..0ad2632b2060--- /dev/null+++ b/products/cohorts/backend/backfill/test/test_sizing.py@@ -0,0 +1,48 @@+from datetime import UTC, datetime++from unittest import mock++from django.test import SimpleTestCase, override_settings++from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytes+++@override_settings(BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=10_000)+class TestPersonBackfillSizing(SimpleTestCase):+ @mock.patch(+ "products.cohorts.backend.backfill.sizing.sync_execute",+ return_value=[(10,)],+ )+ def test_estimate_counts_both_worst_case_hash_vectors(self, sync_execute: mock.Mock) -> None:+ person_scan_since = datetime(2026, 5, 1, tzinfo=UTC)++ estimate = estimate_person_seed_topic_bytes(7, person_scan_since, 2)++ self.assertEqual(estimate.estimated_persons, 10)+ self.assertEqual(estimate.bytes_per_seed, 332)+ self.assertEqual(estimate.estimated_topic_bytes, 3_320)+ self.assertEqual(estimate.budget_bytes, 10_000)+ self.assertFalse(estimate.over_budget)+ self.assertEqual(+ estimate.as_preconditions(),+ {+ "person_seed_estimated_persons": 10,+ "person_seed_pinned_condition_count": 2,+ "person_seed_bytes_per_seed": 332,+ "person_seed_estimated_topic_bytes": 3_320,+ "person_seed_topic_bytes_budget": 10_000,+ },+ )+ # Deleted persons must not inflate the estimate, and the read has to be byte-bounded so the+ # gate throws instead of sizing a run off a partial scan. Neither is observable without CH.+ self.assertIn("is_deleted", sync_execute.call_args.args[0])+ self.assertEqual(+ sync_execute.call_args.args[1],+ {"team_id": 7, "person_scan_since": person_scan_since},+ )+ self.assertEqual(+ sync_execute.call_args.kwargs["settings"],+ {"max_execution_time": 30, "max_bytes_to_read": 10_000_000_000, "read_overflow_mode": "throw"},+ )+ self.assertEqual(sync_execute.call_args.kwargs["team_id"], 7)+ self.assertTrue(sync_execute.call_args.kwargs["readonly"])diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.pyindex 8e178170ed2c..a0c0fcdb34cd 100644--- a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py@@ -1,6 +1,7 @@-from datetime import datetime+from datetime import datetime, timedeltafrom typing import Any+from django.conf import settingsfrom django.core.management.base import BaseCommand, CommandError, CommandParserfrom django.db import IntegrityErrorfrom django.utils import timezone as django_timezone@@ -8,9 +9,21 @@ from django.utils.dateparse import parse_datetimefrom 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.backfill.pinning import (+ PersonPinningCapExceeded,+ pin_conditions_for_cohorts,+ pin_person_conditions_for_cohorts,+)+from products.cohorts.backend.backfill.runs import (+ _person_backfill_ineligibility_reason,+ _validate_boundary_at,+ check_person_run_preconditions,+ check_run_preconditions,+ create_person_team_backfill_run,+ create_team_backfill_run,+)+from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytes+from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRunCohort, CohortBackfillTriggerfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.leaf_shape import walk_filter_leavesfrom products.cohorts.backend.realtime_teams import is_realtime_cohort_team@@ -37,7 +50,7 @@ def _parse_boundary_at(value: str | None) -> datetime | None:class Command(BaseCommand):- help = "Create a coordinated behavioral cohort backfill run"+ help = "Create a coordinated cohort backfill run"def add_arguments(self, parser: CommandParser) -> None:parser.add_argument("--team-id", type=int, required=True)@@ -46,20 +59,44 @@ class Command(BaseCommand):choices=[CohortBackfillTrigger.TEAM_ENABLEMENT, CohortBackfillTrigger.DISASTER_RECOVERY],required=True,)+ parser.add_argument(+ "--kind",+ choices=[value for value, _label in CohortBackfillKind.choices],+ default=CohortBackfillKind.BEHAVIORAL,+ )parser.add_argument("--cohort-ids", type=int, nargs="+")parser.add_argument("--boundary-at", help="ISO 8601 disaster recovery boundary with a UTC offset")+ parser.add_argument("--person-horizon-days", type=int)parser.add_argument("--dry-run", action="store_true")def handle(self, *args: Any, **options: Any) -> None:team_id: int = options["team_id"]trigger: str = options["trigger"]+ kind: str = options["kind"]+ person_horizon_days: int | None = options.get("person_horizon_days")boundary_at = _parse_boundary_at(options.get("boundary_at"))if boundary_at is not None and trigger != CohortBackfillTrigger.DISASTER_RECOVERY:raise CommandError("--boundary-at is only valid with --trigger disaster_recovery")+ if kind == CohortBackfillKind.PERSON_PROPERTY and person_horizon_days is None:+ raise CommandError("--person-horizon-days is required with --kind person_property")+ if kind == CohortBackfillKind.BEHAVIORAL and person_horizon_days is not None:+ raise CommandError("--person-horizon-days is only valid with --kind person_property")if not is_realtime_cohort_team(team_id):raise CommandError(f"Team {team_id} is not in the realtime cohort allowlist")+ if kind == CohortBackfillKind.PERSON_PROPERTY:+ assert person_horizon_days is not None+ self._handle_person_run(+ team_id=team_id,+ trigger=trigger,+ person_horizon_days=person_horizon_days,+ cohort_ids=options.get("cohort_ids"),+ boundary_at=boundary_at,+ dry_run=options["dry_run"],+ )+ return+_, missing = check_run_preconditions()if missing:raise CommandError(f"Missing operator attestations: {', '.join(missing)}")@@ -97,3 +134,117 @@ class Command(BaseCommand):f"{len(run.pinned['conditions'])} conditions, {len(run.pinned['event_names'])} event names"))++ def _handle_person_run(+ self,+ *,+ team_id: int,+ trigger: str,+ person_horizon_days: int,+ cohort_ids: list[int] | None,+ boundary_at: datetime | None,+ dry_run: bool,+ ) -> None:+ _, missing = check_person_run_preconditions(requires_sizing_attestation=True)+ if missing:+ raise CommandError(f"Missing operator attestations: {', '.join(missing)}")+ if person_horizon_days < 1:+ raise CommandError("--person-horizon-days must be at least 1")++ if dry_run:+ self._person_dry_run(+ team_id=team_id,+ trigger=trigger,+ person_horizon_days=person_horizon_days,+ cohort_ids=cohort_ids,+ boundary_at=boundary_at,+ )+ return++ try:+ run = create_person_team_backfill_run(+ team_id,+ trigger,+ person_horizon_days,+ cohort_ids,+ boundary_at=boundary_at,+ )+ 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 person-property team backfill run") from error++ self.stdout.write(+ self.style.SUCCESS(+ f"Created person-property run {run.id}: "+ f"{CohortBackfillRunCohort.objects.for_team(team_id).filter(run=run).count()} cohorts, "+ f"{len(run.pinned['conditions'])} conditions, "+ f"{run.preconditions['person_seed_estimated_persons']} estimated persons, "+ f"{run.preconditions['person_seed_estimated_topic_bytes']} estimated topic bytes"+ )+ )++ def _person_dry_run(+ self,+ *,+ team_id: int,+ trigger: str,+ person_horizon_days: int,+ cohort_ids: list[int] | None,+ boundary_at: datetime | None,+ ) -> None:+ requested_ids = set(cohort_ids) if cohort_ids is not None else None+ # Deliberately wider than `_person_cohorts_for_team`, which narrows the SQL-expressible half+ # of eligibility away before it locks: the dry run's whole job is naming *why* each cohort was+ # refused, and it takes no locks. Both sides decide with `_person_backfill_ineligibility_reason`.+ queryset = Cohort.objects.filter(team_id=team_id)+ if requested_ids is not None:+ queryset = queryset.filter(id__in=requested_ids)+ candidates = [(cohort, _person_backfill_ineligibility_reason(cohort)) for cohort in queryset.order_by("id")]++ refusals = [(cohort.id, reason) for cohort, reason in candidates if reason is not None]+ if requested_ids is not None:+ candidate_ids = {cohort.id for cohort, _ in candidates}+ refusals.extend((cohort_id, "not found") for cohort_id in sorted(requested_ids - candidate_ids))++ if refusals:+ self.stdout.write(+ "Refused cohorts: " + ", ".join(f"{cohort_id} ({reason})" for cohort_id, reason in refusals)+ )+ if requested_ids is not None and refusals:+ raise CommandError("One or more --cohort-ids are not eligible realtime person-property cohorts")++ cohorts = [cohort for cohort, reason in candidates if reason is None]+ if not cohorts:+ raise CommandError(f"Team {team_id} has no eligible realtime person-property cohorts")+ try:+ pinned = pin_person_conditions_for_cohorts(+ cohorts,+ max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ )+ except PersonPinningCapExceeded as error:+ raise CommandError(str(error)) from error++ dropped = sum(+ 1+ for cohort in cohorts+ for leaf in walk_filter_leaves((cohort.filters or {}).get("properties"))+ if leaf.get("type") == "person" and leaf.get("conditionHash") is None+ )+ try:+ normalized_boundary = _validate_boundary_at(trigger, boundary_at)+ person_scan_since = (normalized_boundary or django_timezone.now()) - timedelta(days=person_horizon_days)+ except (OverflowError, ValueError) as error:+ raise CommandError(str(error)) from error+ estimate = estimate_person_seed_topic_bytes(+ team_id,+ person_scan_since,+ len(pinned["conditions"]),+ )+ verdict = "yes" if estimate.over_budget else "no"+ self.stdout.write(+ f"Dry run: {len(cohorts)} cohorts, {len(pinned['conditions'])} conditions, "+ f"{dropped} hash-less person leaves dropped, {estimate.estimated_persons} estimated persons, "+ f"{estimate.estimated_topic_bytes} estimated topic bytes, budget {estimate.budget_bytes}, "+ f"would refuse: {verdict}"+ )diff --git a/products/cohorts/backend/migrations/0008_person_property_backfill_foundation.py b/products/cohorts/backend/migrations/0008_person_property_backfill_foundation.pynew file mode 100644index 000000000000..f048e010f8c9--- /dev/null+++ b/products/cohorts/backend/migrations/0008_person_property_backfill_foundation.py@@ -0,0 +1,38 @@+# Generated by Django 5.2.14 on 2026-07-29 20:29++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0007_cohortbackfillrun_cohort_bfr_reconciling_idx"),+ ("posthog", "1271_add_pardot_integration_kind"),+ ]++ operations = [+ migrations.AddField(+ model_name="cohort",+ name="person_filters_shape_hash",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ migrations.AddField(+ model_name="cohortbackfillchunk",+ name="person_range_hi",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="cohortbackfillchunk",+ name="person_range_lo",+ field=models.UUIDField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="cohortbackfillrun",+ name="person_scan_since",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="cohortbackfillruncohort",+ name="person_filters_shape_hash",+ field=models.CharField(default="", max_length=64),+ ),+ ]diff --git a/products/cohorts/backend/migrations/0009_cohort_backfill_per_kind_uniqueness.py b/products/cohorts/backend/migrations/0009_cohort_backfill_per_kind_uniqueness.pynew file mode 100644index 000000000000..ee54aceeee9a--- /dev/null+++ b/products/cohorts/backend/migrations/0009_cohort_backfill_per_kind_uniqueness.py@@ -0,0 +1,94 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently, DropIndexConcurrently++ACTIVE_STATUSES = ("awaiting_boundary", "blocked", "seeding", "reconciling")+COHORT_WHERE = "WHERE cohort_id IS NOT NULL AND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling')"+TEAM_WHERE = "WHERE scope = 'team' AND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling')"+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("cohorts", "0008_person_property_backfill_foundation"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddConstraint(+ model_name="cohortbackfillrun",+ constraint=models.UniqueConstraint(+ fields=("cohort", "backfill_kind"),+ condition=models.Q(cohort__isnull=False, status__in=ACTIVE_STATUSES),+ name="cohort_bfr_active_cohort_kind_uq",+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="cohort_bfr_active_cohort_kind_uq",+ table_name="cohort_backfill_runs",+ columns="(cohort_id, backfill_kind)",+ unique=True,+ where=COHORT_WHERE,+ ),+ ],+ ),+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddConstraint(+ model_name="cohortbackfillrun",+ constraint=models.UniqueConstraint(+ fields=("team", "backfill_kind"),+ condition=models.Q(scope="team", status__in=ACTIVE_STATUSES),+ name="cohort_bfr_active_team_kind_uq",+ ),+ ),+ ],+ database_operations=[+ CreateIndexConcurrently(+ index_name="cohort_bfr_active_team_kind_uq",+ table_name="cohort_backfill_runs",+ columns="(team_id, backfill_kind)",+ unique=True,+ where=TEAM_WHERE,+ ),+ ],+ ),+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveConstraint(+ model_name="cohortbackfillrun",+ name="cohort_bfr_active_cohort_uq",+ ),+ ],+ database_operations=[+ DropIndexConcurrently(+ index_name="cohort_bfr_active_cohort_uq",+ table_name="cohort_backfill_runs",+ columns="(cohort_id)",+ unique=True,+ where=COHORT_WHERE,+ ),+ ],+ ),+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.RemoveConstraint(+ model_name="cohortbackfillrun",+ name="cohort_bfr_active_team_uq",+ ),+ ],+ database_operations=[+ DropIndexConcurrently(+ index_name="cohort_bfr_active_team_uq",+ table_name="cohort_backfill_runs",+ columns="(team_id)",+ unique=True,+ where=TEAM_WHERE,+ ),+ ],+ ),+ ]diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txtindex 88d30e14d573..2b9921d527b8 100644--- a/products/cohorts/backend/migrations/max_migration.txt+++ b/products/cohorts/backend/migrations/max_migration.txt@@ -1 +1 @@-0007_cohortbackfillrun_cohort_bfr_reconciling_idx+0009_cohort_backfill_per_kind_uniquenessdiff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.pyindex c0c0560e7c43..1abc804de9e7 100644--- a/products/cohorts/backend/models/backfill.py+++ b/products/cohorts/backend/models/backfill.py@@ -66,6 +66,7 @@ class CohortBackfillRun(TeamScopedRootMixin, UUIDTModel):)timezone = models.CharField(max_length=240)boundary_at = models.DateTimeField(null=True, blank=True)+ person_scan_since = 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)@@ -106,14 +107,14 @@ class CohortBackfillRun(TeamScopedRootMixin, UUIDTModel):]constraints = [models.UniqueConstraint(- fields=["cohort"],+ fields=["cohort", "backfill_kind"],condition=Q(cohort__isnull=False, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES),- name="cohort_bfr_active_cohort_uq",+ name="cohort_bfr_active_cohort_kind_uq",),models.UniqueConstraint(- fields=["team"],+ fields=["team", "backfill_kind"],condition=Q(scope=CohortBackfillScope.TEAM, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES),- name="cohort_bfr_active_team_uq",+ name="cohort_bfr_active_team_kind_uq",),]@@ -124,6 +125,7 @@ class CohortBackfillRunCohort(TeamScopedRootMixin, UUIDModel):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="")+ person_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)@@ -159,6 +161,8 @@ class CohortBackfillChunk(TeamScopedRootMixin, UUIDModel):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)+ person_range_lo = models.UUIDField(null=True, blank=True)+ person_range_hi = models.UUIDField(null=True, blank=True)attempts = models.IntegerField(default=0)last_error = models.TextField(blank=True, default="")tiles_produced = models.BigIntegerField(default=0)diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex 0f48eae93dfe..6600263ecd56 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -35,7 +35,11 @@ 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.models.leaf_shape import (+ extract_behavioral_leaf_shape_hash,+ extract_leaf_shape_hash,+ extract_person_leaf_shape_hash,+)from products.cohorts.backend.realtime_teams import is_realtime_cohort_teamif TYPE_CHECKING:@@ -231,6 +235,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):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)+ person_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)@@ -292,22 +297,24 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):(`validate_filters_and_compute_realtime_support`) — so a direct `Cohort.objects.create(...)`gets a fresh `condition_type` but a stale/absent `cohort_type`."""# 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.+ # or as a keyword. Intercept it so _maintain_filter_shape_hashes can extend the frozen set.update_fields = args[3] if len(args) > 3 else kwargs.get("update_fields")if update_fields is None or "filters" in update_fields:self.condition_type = Cohort.compute_condition_type(self.filters)if update_fields is not None and "condition_type" not in update_fields:update_fields = [*update_fields, "condition_type"]- maintained_update_fields = self._maintain_behavioral_shape(update_fields)+ maintained_update_fields = self._maintain_filter_shape_hashes(update_fields)if len(args) > 3:args = (*args[:3], maintained_update_fields, *args[4:])else:kwargs["update_fields"] = maintained_update_fieldssuper().save(*args, **kwargs)- def _maintain_behavioral_shape(self, update_fields: Iterable[str] | None) -> set[str] | None:+ def _maintain_filter_shape_hashes(self, update_fields: Iterable[str] | None) -> set[str] | None:+ """Maintain full, behavioral, and person filter-shape hashes."""self._leaf_shape_changed = False+ self._person_shape_changed = Falsemaintained_update_fields = set(update_fields) if update_fields is not None else Nonetry:if not self.team_id or not is_realtime_cohort_team(self.team_id):@@ -319,14 +326,24 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):new_shape_hash = extract_leaf_shape_hash(self.filters)new_behavioral_shape_hash = extract_behavioral_leaf_shape_hash(self.filters)+ new_person_shape_hash = extract_person_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")+ stored_person_shape_hash = self.__dict__.get("person_filters_shape_hash")previous_behavioral_shape_hash = stored_behavioral_shape_hash+ previous_person_shape_hash = stored_person_shape_hash- if not self._state.adding and (stored_shape_hash is None or stored_behavioral_shape_hash is None):+ if not self._state.adding and (+ stored_shape_hash is None or stored_behavioral_shape_hash is None or stored_person_shape_hash is None+ ):persisted = (Cohort.objects.filter(id=self.pk, team_id=self.team_id)- .values("filters", "filters_shape_hash", "behavioral_filters_shape_hash")+ .values(+ "filters",+ "filters_shape_hash",+ "behavioral_filters_shape_hash",+ "person_filters_shape_hash",+ ).first())if persisted is not None:@@ -339,18 +356,34 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):if stored_behavioral_shape_hash is not Noneelse extract_behavioral_leaf_shape_hash(persisted["filters"]))+ if stored_person_shape_hash is None:+ stored_person_shape_hash = persisted["person_filters_shape_hash"]+ previous_person_shape_hash = (+ stored_person_shape_hash+ if stored_person_shape_hash is not None+ else extract_person_leaf_shape_hash(persisted["filters"])+ )shape_hash_needs_update = stored_shape_hash != new_shape_hashbehavioral_shape_hash_needs_update = stored_behavioral_shape_hash != new_behavioral_shape_hash+ person_shape_hash_needs_update = stored_person_shape_hash != new_person_shape_hashbehavioral_shape_changed = (not self._state.adding and previous_behavioral_shape_hash != new_behavioral_shape_hash)+ person_shape_changed = not self._state.adding and previous_person_shape_hash != new_person_shape_hashself.filters_shape_hash = new_shape_hashself.behavioral_filters_shape_hash = new_behavioral_shape_hash+ self.person_filters_shape_hash = new_person_shape_hashif behavioral_shape_changed:self.last_backfill_events_at = Noneself._leaf_shape_changed = True+ if person_shape_changed:+ self.last_backfill_person_properties_at = None+ # Nothing reads this yet: the receiver that supersedes active person-property runs+ # on a person-leaf edit — the counterpart to `_leaf_shape_changed` in+ # dependencies.py — lands with the person-run trigger (B7.3b).+ self._person_shape_changed = Trueif maintained_update_fields is None:return None@@ -358,8 +391,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):maintained_update_fields.add("filters_shape_hash")if behavioral_shape_hash_needs_update:maintained_update_fields.add("behavioral_filters_shape_hash")+ if person_shape_hash_needs_update:+ maintained_update_fields.add("person_filters_shape_hash")if behavioral_shape_changed:maintained_update_fields.add("last_backfill_events_at")+ if person_shape_changed:+ maintained_update_fields.add("last_backfill_person_properties_at")return maintained_update_fieldsexcept Exception as error:logger.exception(diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.pyindex 43c373d93d05..f07907977f9f 100644--- a/products/cohorts/backend/models/dependencies.py+++ b/products/cohorts/backend/models/dependencies.py@@ -16,6 +16,7 @@ from structlog import get_loggerfrom posthog.models.team.team import Teamfrom posthog.redis import get_client as get_redis_client+from products.cohorts.backend.models.backfill import CohortBackfillKindfrom products.cohorts.backend.models.cohort import Cohort, CohortType, is_cohort_recalculation_only_savefrom products.cohorts.backend.models.leaf_shape import walk_filter_leavesfrom products.cohorts.backend.realtime_teams import is_realtime_cohort_team@@ -505,7 +506,7 @@ def _supersede_cohort_events_backfills(cohort: Cohort) -> None:supersede_active_runs, # noqa: PLC0415 — avoids a model-load cycle)- supersede_active_runs(cohort.team_id, [cohort.id])+ supersede_active_runs(cohort.team_id, [cohort.id], kind=CohortBackfillKind.BEHAVIORAL)except Exception as error:logger.exception("failed_to_supersede_cohort_events_backfills",diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.pyindex be1c57065870..32bb3ca72e1c 100644--- a/products/cohorts/backend/models/leaf_shape.py+++ b/products/cohorts/backend/models/leaf_shape.py@@ -1,6 +1,7 @@import jsonimport hashlibfrom collections.abc import Iterator+from enum import StrEnumfrom typing import NamedTuple_I32_MIN = -(2**31)@@ -81,17 +82,23 @@ def _hash_keys(keys: list[list[object]]) -> str:return hashlib.sha256(json.dumps(serialized, separators=(",", ":")).encode()).hexdigest()-def _extract_leaf_shape_keys(filters: dict | None, *, behavioral_only: bool) -> list[list[object]]:+class _LeafShapeMode(StrEnum):+ FULL = "full"+ BEHAVIORAL_ONLY = "behavioral_only"+ PERSON_ONLY = "person_only"+++def _extract_leaf_shape_keys(filters: dict | None, *, mode: _LeafShapeMode) -> 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 leaf_type == "person" and mode != _LeafShapeMode.BEHAVIORAL_ONLY:if (condition_hash := leaf.get("conditionHash")) is not None:keys.append(["person", condition_hash])- elif leaf_type == "behavioral":+ elif leaf_type == "behavioral" and mode != _LeafShapeMode.PERSON_ONLY:if (condition_hash := leaf.get("conditionHash")) is not None:keys.append([@@ -108,7 +115,7 @@ def _extract_leaf_shape_keys(filters: dict | None, *, behavioral_only: bool) ->),])- elif leaf_type == "cohort" and not behavioral_only:+ elif leaf_type == "cohort" and mode == _LeafShapeMode.FULL:keys.append(["cohort", leaf.get("value"), bool(leaf.get("negation", False))])return keys@@ -120,9 +127,14 @@ def extract_leaf_shape_hash(filters: dict | None) -> str:`LeafStateKey::for_behavioral` uses a 16-byte digest of one leaf. Keep these fields in lockstep:behavioral leaves via `BehavioralLeafKey`; person conditionHash; cohort value and negation."""- return _hash_keys(_extract_leaf_shape_keys(filters, behavioral_only=False))+ return _hash_keys(_extract_leaf_shape_keys(filters, mode=_LeafShapeMode.FULL))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))+ return _hash_keys(_extract_leaf_shape_keys(filters, mode=_LeafShapeMode.BEHAVIORAL_ONLY))+++def extract_person_leaf_shape_hash(filters: dict | None) -> str:+ """Fingerprint only person-property condition hashes."""+ return _hash_keys(_extract_leaf_shape_keys(filters, mode=_LeafShapeMode.PERSON_ONLY))diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.pyindex 3f0b970b3125..81a0b0ebfdd1 100644--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py@@ -60,20 +60,27 @@ class TestBehavioralBackfillDependencies(BaseTest):return COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed")._value._valuedef test_window_edit_writes_hash_and_nulls_readiness_in_one_save(self) -> None:- cohort = self._cohort(7)+ cohort = self._cohort(7, person_hash="person-a")old_hash = cohort.filters_shape_hashold_behavioral_hash = cohort.behavioral_filters_shape_hash- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())+ old_person_hash = cohort.person_filters_shape_hash+ person_ready_at = timezone.now()+ Cohort.objects.filter(id=cohort.id).update(+ last_backfill_events_at=timezone.now(),+ last_backfill_person_properties_at=person_ready_at,+ )cohort.refresh_from_db()before = self._orphan_count()- cohort.filters = self._filters(30)+ cohort.filters = self._filters(30, person_hash="person-a")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.assertEqual(cohort.person_filters_shape_hash, old_person_hash)self.assertIsNone(cohort.last_backfill_events_at)+ self.assertEqual(cohort.last_backfill_person_properties_at, person_ready_at)self.assertEqual(self._orphan_count(), before + 1)def test_filter_only_update_persists_maintained_fields(self) -> None:@@ -137,7 +144,11 @@ class TestBehavioralBackfillDependencies(BaseTest):ready_at = timezone.now()old_hash = cohort.filters_shape_hashold_behavioral_hash = cohort.behavioral_filters_shape_hash- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)+ old_person_hash = cohort.person_filters_shape_hash+ Cohort.objects.filter(id=cohort.id).update(+ last_backfill_events_at=ready_at,+ last_backfill_person_properties_at=ready_at,+ )cohort.refresh_from_db()before = self._orphan_count()self.feature_enabled.return_value = True@@ -152,12 +163,14 @@ class TestBehavioralBackfillDependencies(BaseTest):) as event_enqueue,):cohort.filters = self._filters(7, person_hash="person-b")- cohort.save()+ cohort.save(update_fields=["filters"])cohort.refresh_from_db()self.assertNotEqual(cohort.filters_shape_hash, old_hash)self.assertEqual(cohort.behavioral_filters_shape_hash, old_behavioral_hash)+ self.assertNotEqual(cohort.person_filters_shape_hash, old_person_hash)self.assertEqual(cohort.last_backfill_events_at, ready_at)+ self.assertIsNone(cohort.last_backfill_person_properties_at)self.assertEqual(self._orphan_count(), before)person_enqueue.assert_called_once()event_enqueue.assert_not_called()@@ -168,6 +181,7 @@ class TestBehavioralBackfillDependencies(BaseTest):Cohort.objects.filter(id=cohort.id).update(filters_shape_hash=None,behavioral_filters_shape_hash=None,+ person_filters_shape_hash=None,last_backfill_events_at=ready_at,)cohort.refresh_from_db()@@ -181,6 +195,7 @@ class TestBehavioralBackfillDependencies(BaseTest):cohort.refresh_from_db()self.assertIsNotNone(cohort.filters_shape_hash)self.assertIsNotNone(cohort.behavioral_filters_shape_hash)+ self.assertIsNotNone(cohort.person_filters_shape_hash)self.assertEqual(cohort.last_backfill_events_at, ready_at)self.assertEqual(self._orphan_count(), before)enqueue.assert_not_called()@@ -217,6 +232,7 @@ class TestBehavioralBackfillDependencies(BaseTest):cohort.refresh_from_db()self.assertIsNone(cohort.filters_shape_hash)self.assertIsNone(cohort.behavioral_filters_shape_hash)+ self.assertIsNone(cohort.person_filters_shape_hash)self.assertEqual(cohort.last_backfill_events_at, ready_at)self.assertEqual(self._orphan_count(), before)@@ -290,7 +306,7 @@ class TestBehavioralBackfillDependencies(BaseTest):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+ # _maintain_filter_shape_hashes 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)diff --git a/products/cohorts/backend/models/test/test_leaf_shape.py b/products/cohorts/backend/models/test/test_leaf_shape.pyindex 61b5dae610d8..4ebe6e4ece9a 100644--- a/products/cohorts/backend/models/test/test_leaf_shape.py+++ b/products/cohorts/backend/models/test/test_leaf_shape.py@@ -5,6 +5,7 @@ from parameterized import parameterizedfrom products.cohorts.backend.models.leaf_shape import (extract_behavioral_leaf_shape_hash,extract_leaf_shape_hash,+ extract_person_leaf_shape_hash,walk_filter_leaves,)@@ -88,6 +89,36 @@ class TestLeafShape(SimpleTestCase):extract_behavioral_leaf_shape_hash(self._filters(self._behavioral(), after)),)+ def test_person_hash_uses_only_hashed_person_leaves(self) -> None:+ person = {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}+ baseline = extract_person_leaf_shape_hash(self._filters(person))++ self.assertNotEqual(baseline, "")+ self.assertEqual(+ baseline,+ extract_person_leaf_shape_hash(+ self._filters(+ self._behavioral(),+ {"type": "cohort", "value": 42, "negation": False},+ {"type": "person", "conditionHash": None},+ person,+ )+ ),+ )+ self.assertNotEqual(+ baseline,+ extract_person_leaf_shape_hash(self._filters({"type": "person", "conditionHash": "bbbbbbbbbbbbbbbb"})),+ )+ self.assertEqual(extract_person_leaf_shape_hash(None), "")++ def test_behavioral_edit_does_not_change_person_hash(self) -> None:+ person = {"type": "person", "conditionHash": "aaaaaaaaaaaaaaaa"}++ self.assertEqual(+ extract_person_leaf_shape_hash(self._filters(person, self._behavioral(time_value=7))),+ extract_person_leaf_shape_hash(self._filters(person, self._behavioral(time_value=30))),+ )+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))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 1894f5ed43a4..9812bca68259 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@@ -789,6 +789,7 @@"posthog_cohort"."last_backfill_events_at","posthog_cohort"."filters_shape_hash","posthog_cohort"."behavioral_filters_shape_hash",+ "posthog_cohort"."person_filters_shape_hash","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",@@ -1161,6 +1162,7 @@"posthog_cohort"."last_backfill_events_at","posthog_cohort"."filters_shape_hash","posthog_cohort"."behavioral_filters_shape_hash",+ "posthog_cohort"."person_filters_shape_hash","posthog_cohort"."last_realtime_cohort_calculation_at","posthog_cohort"."is_static","posthog_cohort"."kind",diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sqlsimilarity index 85%rename from rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sqlrename to rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sqlindex d7e0b5404fcd..beddc4ae4356 100644--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0009.sql@@ -1,6 +1,5 @@--- Snapshot pinned to products/cohorts/backend/migrations/0007_cohortbackfillrun_cohort_bfr_reconciling_idx.py--- (the 0004 DDL, the six columns 0006 adds, and the partial index 0007 adds). External Team/Cohort--- foreign keys are omitted so the contract test stays schema-local.+-- Snapshot pinned to products/cohorts/backend/migrations/0009_cohort_backfill_per_kind_uniqueness.py.+-- External Team/Cohort foreign keys are omitted so the contract test stays schema-local.CREATE TABLE cohort_backfill_runs (id uuid PRIMARY KEY,@@ -11,6 +10,7 @@ CREATE TABLE cohort_backfill_runs (status varchar(32) NOT NULL DEFAULT 'awaiting_boundary',timezone varchar(240) NOT NULL,boundary_at timestamptz,+ person_scan_since timestamptz,boundary_established_at timestamptz,pinned jsonb NOT NULL DEFAULT '{}'::jsonb,preconditions jsonb NOT NULL DEFAULT '{}'::jsonb,@@ -35,12 +35,12 @@ CREATE INDEX cohort_bfr_team_created_idx ON cohort_backfill_runs(team_id, createCREATE INDEX cohort_bfr_reconciling_idxON cohort_backfill_runs(backfill_kind, reconcile_observed_at)WHERE status = 'reconciling';-CREATE UNIQUE INDEX cohort_bfr_active_cohort_uq- ON cohort_backfill_runs(cohort_id)+CREATE UNIQUE INDEX cohort_bfr_active_cohort_kind_uq+ ON cohort_backfill_runs(cohort_id, backfill_kind)WHERE cohort_id IS NOT NULLAND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling');-CREATE UNIQUE INDEX cohort_bfr_active_team_uq- ON cohort_backfill_runs(team_id)+CREATE UNIQUE INDEX cohort_bfr_active_team_kind_uq+ ON cohort_backfill_runs(team_id, backfill_kind)WHERE scope = 'team'AND status IN ('awaiting_boundary', 'blocked', 'seeding', 'reconciling');@@ -54,6 +54,8 @@ CREATE TABLE cohort_backfill_chunks (claimed_at timestamptz,lease_expires_at timestamptz,s_chunk_at timestamptz,+ person_range_lo uuid,+ person_range_hi uuid,attempts integer NOT NULL DEFAULT 0,last_error text NOT NULL DEFAULT '',tiles_produced bigint NOT NULL DEFAULT 0,@@ -72,6 +74,7 @@ CREATE TABLE cohort_backfill_run_cohorts (id uuid PRIMARY KEY,filters_shape_hash varchar(64) NOT NULL,behavioral_filters_shape_hash varchar(64) NOT NULL DEFAULT '',+ person_filters_shape_hash varchar(64) NOT NULL DEFAULT '',pinned_filters jsonb NOT NULL,stamped_at timestamptz,superseded_at timestamptz,@@ -92,5 +95,6 @@ CREATE TABLE posthog_cohort (id integer PRIMARY KEY,team_id integer NOT NULL,behavioral_filters_shape_hash varchar(64),+ person_filters_shape_hash varchar(64),deleted boolean NOT NULL DEFAULT false);diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rsindex 61e9539ed020..5f51fb3aff01 100644--- a/rust/cohort-seeder/tests/support/mod.rs+++ b/rust/cohort-seeder/tests/support/mod.rs@@ -25,8 +25,8 @@ use sqlx::{Connection, PgConnection, PgPool};use uuid::Uuid;/// The `cohort_backfill_*` DDL (plus a schema-local `posthog_cohort` projection), pinned to Django-/// migration 0007, applied fresh into each test schema.-pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0007.sql");+/// migration 0009, applied fresh into each test schema.+pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0009.sql");/// A live cohort condition hash used by the superseded-load fixtures.pub const ACTIVE_HASH: &str = "active0000000000";/// A superseded cohort condition hash used by the superseded-load fixtures.