: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): wire person-prop seed trigger (#77000)
Matheus Batistab3dd174c8316
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 9f9368775053..96af2a3af85e 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@@ -504,8 +504,10 @@'_insert_batch_via_personhog','_insert_resolved_batch','_insert_users_list_with_batching',+ '_leaf_shape_changed','_maintain_filter_shape_hashes','_meta',+ '_person_shape_changed','_safe_reset_calculating_state','_safe_save_cohort_state','backfill_participations',diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.pyindex 8a20a2beb3d7..565387a6e1fd 100644--- a/posthog/settings/cohorts.py+++ b/posthog/settings/cohorts.py@@ -5,6 +5,18 @@ 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")+# Teams whose cohort saves enqueue a backfill run for rust/cohort-seeder to claim. Same grammar as+# the allowlist above, except that a set-but-empty value means no teams: nothing outside Python+# parses this setting, so it can fail closed on empty where the realtime allowlist cannot. It is+# deliberately a separate setting, an opt-in on top of realtime membership rather than something a+# team inherits by it: replaying a team's history costs ClickHouse scans and seed-topic bytes, so it+# stays an explicit operator decision. A team listed here but not above enqueues nothing.+#+# Order this against the seeder's own arming: Django cannot see `SEEDER_PERSON_SEEDS_ENABLED`, so a+# team with person-leaf cohorts opted in before that switch files person runs that park in+# `awaiting_boundary`, each holding its cohort's uniqueness slot and blocking the operator's team+# command until the seeder starts discovering them.+COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST: str = os.getenv("COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST", "none")BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED: bool = get_from_env("BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED", False, type_cast=str_to_bool)@@ -45,12 +57,12 @@ BEHAVIORAL_BACKFILL_FINALIZER_ENABLED: bool = get_from_env(# "in cohort" targeting and over-matches negated targeting. `Cohort.is_flag_compatible` fail-closes# on this; the flags service does not.#-# Also keep it off until a person-leaf edit supersedes the cohort's active person-property runs,-# the way `_supersede_cohort_events_backfills` does for behavioral ones (the B7.3b receiver).-# Without that, the person stamp's only edit-time fence is the hash CAS in `_stamp_readiness`,-# which passes again after an A->B->A revert and stamps readiness over a backfill whose Stage 2-# state went stale in the B window — the `superseded_at` refusal that closes this for behavioral-# runs never fires because nothing sets it on the person path.+# The stamp's other precondition is already met: `cohort_person_shape_changed_supersede` supersedes+# a cohort's active person-property runs when its person leaves change, so an A->B->A revert can no+# longer stamp readiness over a backfill whose Stage 2 state went stale in the B window. That fence+# arms only on saves that maintain the shape hashes: an edit that drops the cohort out of realtime+# support (`cohort_type` cleared) or a delete/undelete round-trip skips maintenance and supersedes+# nothing, the same exposure the behavioral fence has.BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED: bool = get_from_env("BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED", False, type_cast=str_to_bool)diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.pyindex e9a53a627b9f..e36dbfc64391 100644--- a/posthog/tasks/calculate_cohort.py+++ b/posthog/tasks/calculate_cohort.py@@ -23,6 +23,13 @@ from posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueuefrom products.cohorts.backend.backfill.finalize import finalize_backfill_runs+from products.cohorts.backend.backfill.runs import (+ check_person_run_preconditions,+ check_run_preconditions,+ create_backfill_run_for_cohort,+ create_person_backfill_run_for_cohort,+)+from products.cohorts.backend.models.backfill import CohortBackfillKindfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.cohorts.backend.models.util import (@@ -32,6 +39,7 @@ from products.cohorts.backend.models.util import (get_clickhouse_query_stats,sort_cohorts_topologically,)+from products.cohorts.backend.realtime_teams import is_cohort_backfill_trigger_teamCOHORT_RECALCULATIONS_BACKLOG_GAUGE = Gauge("cohort_recalculations_backlog",@@ -839,6 +847,103 @@ def collect_cohort_query_stats(raise+COHORT_BACKFILL_TRIGGER_TASK_COUNTER = Counter(+ "posthog_cohort_backfill_trigger_task_total",+ "Outcomes of debounced cohort backfill run-creation tasks",+ labelnames=["backfill_kind", "outcome"],+)+++# acks_late: a countdown message acked on receipt sits in one worker's memory for the whole window+# and dies with it, after the edit's supersession already ran. The creators refuse duplicates, so+# the redelivery this trades into is harmless. The queue matches the module's other+# ClickHouse-touching tasks: the person creator runs a sizing scan capped at 30 s.+@shared_task(+ ignore_result=True,+ acks_late=True,+ autoretry_for=(Exception,),+ retry_backoff=True,+ max_retries=3,+ queue=CeleryQueue.LONG_RUNNING.value,+)+def trigger_cohort_backfill_run_task(team_id: int, cohort_id: int, trigger_kind: str, backfill_kind: str) -> None:+ """Create the run a debounced cohort save asked for, reading the cohort's current definition.++ The creators re-check eligibility under a row lock, so a cohort that was edited again, deleted,+ or made static during the debounce window returns None here. That is a normal outcome, not a+ failure, and must not raise: a raise burns the task's retries re-deciding the same refusal.++ A missing operator attestation is the same kind of outcome on this path. The creators record a+ `blocked` row when called directly, which is right for operator-driven runs, but a blocked row+ holds the per-cohort uniqueness slot and nothing ever advances it, so the signal path skips+ instead of parking one on every cohort a freshly allowlisted team saves.+ """+ try:+ if not is_cohort_backfill_trigger_team(team_id):+ # The enqueue-side check ran up to the debounce countdown ago; re-checking here makes+ # shrinking the allowlist stop tasks already in flight, not only new enqueues.+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="not_allowlisted").inc()+ logger.info(+ "skipping_cohort_backfill_run_task_team_not_allowlisted",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ backfill_kind=backfill_kind,+ )+ return+ person = backfill_kind == CohortBackfillKind.PERSON_PROPERTY+ _, missing = check_person_run_preconditions() if person else check_run_preconditions()+ if missing:+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(+ backfill_kind=backfill_kind, outcome="missing_attestations"+ ).inc()+ logger.info(+ "skipping_cohort_backfill_run_task_missing_attestations",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ backfill_kind=backfill_kind,+ missing=missing,+ )+ return+ run = (+ create_person_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)+ if person+ else create_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)+ )+ if run is None:+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="refused").inc()+ logger.info(+ "skipping_cohort_backfill_run_task",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ backfill_kind=backfill_kind,+ )+ return+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="created").inc()+ logger.info(+ "created_cohort_backfill_run",+ run_id=str(run.id),+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ backfill_kind=backfill_kind,+ status=run.status,+ )+ except Exception as error:+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="error").inc()+ logger.exception(+ "failed_to_trigger_cohort_backfill_run_task",+ cohort_id=cohort_id,+ team_id=team_id,+ trigger_kind=trigger_kind,+ backfill_kind=backfill_kind,+ error=str(error),+ )+ raise++@shared_task(ignore_result=True)def finalize_cohort_backfill_runs() -> None:"""Terminalize behavioral backfill runs the Rust seeder has fully observed. Gated off bydiff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex ca48628d1ca7..dfb7ebb56a03 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -18,6 +18,7 @@'posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag','posthog.tasks.calculate_cohort.insert_cohort_from_filters','posthog.tasks.calculate_cohort.insert_cohort_from_query',+ 'posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task','posthog.tasks.demo_create_data.create_data_for_demo_team','posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature','posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change',diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.pyindex 839eafc5c197..a7783aa991a9 100644--- a/posthog/tasks/test/test_calculate_cohort.py+++ b/posthog/tasks/test/test_calculate_cohort.py@@ -4,6 +4,7 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.test import override_settingsfrom django.utils import timezonefrom dateutil.relativedelta import relativedelta@@ -21,14 +22,30 @@ from posthog.tasks.calculate_cohort import (increment_version_and_enqueue_calculate_cohort,insert_cohort_from_filters,reset_stuck_cohorts,+ trigger_cohort_backfill_run_task,update_cohort_metrics,)-from products.cohorts.backend.models.cohort import Cohort+from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRun+from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_idsMISSING_COHORT_ID = 12345+BACKFILL_KINDS = [("behavioral", CohortBackfillKind.BEHAVIORAL), ("person", CohortBackfillKind.PERSON_PROPERTY)]++# What the task needs to reach the creators: both allowlists open, every attestation the two kinds+# check between them, and a person seed budget. Tests peel these back to exercise the guards.+BACKFILL_TASK_SETTINGS = {+ "REALTIME_COHORT_TEAM_ALLOWLIST": "all",+ "COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST": "all",+ "BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED": True,+ "BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED": True,+ "BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED": True,+ "BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED": True,+ "BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET": 1_000_000,+}+def calculate_cohort_test_factory(event_factory: Callable, person_factory: Callable): # type: ignoreclass TestCalculateCohort(APIBaseTest):@@ -1053,6 +1070,112 @@ def calculate_cohort_test_factory(event_factory: Callable, person_factory: Callaclass TestCohortCalculationTasks(APIBaseTest):+ def _backfillable_cohort(self) -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ name="backfill trigger",+ cohort_type=CohortType.REALTIME,+ filters={+ "properties": {+ "type": "AND",+ "values": [+ {+ "type": "behavioral",+ "key": "$pageview",+ "event_type": "events",+ "value": "performed_event",+ "conditionHash": "behavior00000001",+ "time_value": 7,+ "time_interval": "day",+ },+ {+ "type": "person",+ "key": "email",+ "value": ["[email protected]"],+ "operator": "exact",+ "conditionHash": "person0000000001",+ },+ ],+ }+ },+ )++ @parameterized.expand(BACKFILL_KINDS)+ @override_settings(**BACKFILL_TASK_SETTINGS)+ def test_trigger_backfill_run_task_returns_quietly_when_the_run_is_refused(+ self, _name: str, backfill_kind: CohortBackfillKind+ ) -> None:+ # The cohort can be deleted or edited into ineligibility during the debounce window, and+ # then the creator refuses. Raising there would spend the task's retries re-deciding the+ # same refusal. The allowlists and attestations are open here so the refusal under test is+ # the creator's own, not an earlier guard's.+ trigger_cohort_backfill_run_task(self.team.pk, MISSING_COHORT_ID, "cohort_edited", backfill_kind.value)++ self.assertFalse(CohortBackfillRun.objects.for_team(self.team.pk).exists())++ @parameterized.expand(BACKFILL_KINDS)+ def test_trigger_backfill_run_task_creates_a_run_of_the_requested_kind(+ self, _name: str, backfill_kind: CohortBackfillKind+ ) -> None:+ # The worker receives the kind as a plain string after JSON serialization, and the task's+ # branch on it picks the creator. A person trigger that filed a behavioral run would leave+ # the person conditions unseeded with nothing going red.+ cohort = self._backfillable_cohort()++ with override_settings(**BACKFILL_TASK_SETTINGS):+ trigger_cohort_backfill_run_task(self.team.pk, cohort.pk, "cohort_created", backfill_kind.value)++ run = CohortBackfillRun.objects.for_team(self.team.pk).get()+ self.assertEqual(run.backfill_kind, backfill_kind)+ self.assertEqual(run.cohort_id, cohort.pk)++ @parameterized.expand(BACKFILL_KINDS)+ def test_trigger_backfill_run_task_skips_instead_of_parking_a_blocked_run(+ self, _name: str, backfill_kind: CohortBackfillKind+ ) -> None:+ # With the attestations unset the creators would record a `blocked` row, which counts as+ # active, occupies the per-cohort uniqueness slot, and nothing ever advances. A team opted+ # into the trigger allowlist before the operator attests would wedge every cohort it saves.+ cohort = self._backfillable_cohort()++ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all", COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"):+ trigger_cohort_backfill_run_task(self.team.pk, cohort.pk, "cohort_created", backfill_kind.value)++ self.assertFalse(CohortBackfillRun.objects.for_team(self.team.pk).exists())++ def test_trigger_backfill_run_task_skips_when_the_person_budget_is_unset(self) -> None:+ # All four attestations on but no byte budget: `over_budget` is a strict comparison against+ # it, so every sized run would refuse, after paying for a full-team sizing scan each time.+ # The precondition check has to catch this before the scan.+ cohort = self._backfillable_cohort()++ with (+ override_settings(**{**BACKFILL_TASK_SETTINGS, "BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET": 0}),+ patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes") as estimate,+ ):+ trigger_cohort_backfill_run_task(+ self.team.pk, cohort.pk, "cohort_created", CohortBackfillKind.PERSON_PROPERTY.value+ )++ estimate.assert_not_called()+ self.assertFalse(CohortBackfillRun.objects.for_team(self.team.pk).exists())++ def test_trigger_backfill_run_task_rechecks_the_allowlist_at_execution_time(self) -> None:+ # Tasks sit in the queue for the debounce countdown, so an operator shrinking the allowlist+ # during an incident has to stop those too, not only new enqueues.+ cohort = self._backfillable_cohort()++ with override_settings(+ REALTIME_COHORT_TEAM_ALLOWLIST="all",+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,+ ):+ trigger_cohort_backfill_run_task(+ self.team.pk, cohort.pk, "cohort_edited", CohortBackfillKind.BEHAVIORAL.value+ )++ self.assertFalse(CohortBackfillRun.objects.for_team(self.team.pk).exists())+def test_safe_save_cohort_state_handles_errors(self) -> None:cohort = Cohort.objects.create(team_id=self.team.pk,diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex f852436b3d80..94a4dc02f6f2 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -157,8 +157,11 @@ 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_behavioral_shape_changed_supersedepost_save:products.cohorts.backend.models.dependencies.cohort_changed+post_save:products.cohorts.backend.models.dependencies.cohort_person_shape_changed_backfill+post_save:products.cohorts.backend.models.dependencies.cohort_person_shape_changed_supersedepost_save:products.conversations.backend.signals.emit_ticket_created_eventpost_save:products.conversations.backend.signals.post_github_reply_on_team_messagepost_save:products.conversations.backend.signals.post_slack_reply_on_team_messagediff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.pyindex 678bde0a1204..091306ad621e 100644--- a/products/cohorts/backend/backfill/runs.py+++ b/products/cohorts/backend/backfill/runs.py@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedeltafrom typing import Anyfrom django.conf import settings-from django.db import transaction+from django.db import IntegrityError, transactionfrom django.db.models.functions import Nowfrom django.utils import timezone as django_timezone@@ -17,7 +17,11 @@ from products.cohorts.backend.backfill.pinning import (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_bytes+from products.cohorts.backend.backfill.sizing import (+ PersonSeedEstimate,+ PersonSeedEstimateScanCapExceeded,+ estimate_person_seed_topic_bytes,+)from products.cohorts.backend.models.backfill import (ACTIVE_COHORT_BACKFILL_RUN_STATUSES,CohortBackfillKind,@@ -51,26 +55,31 @@ 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.+def check_person_run_preconditions() -> tuple[dict[str, Any], list[str]]:+ """Person-run gates: the behavioral ones plus person-record TTL and seed sizing.- TTL is not scope-dependent — every person seed lands in the same ``cf_person_records`` store,+ Neither is 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.+ operator has to attest it for any kind of person run. And both person creators size their seed+ emission against ``BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET``, so sizing is attested for+ any kind of person run too. An unset budget is itself a missing precondition: `over_budget` is a+ strict comparison against it, so with the default of 0 every sized run would refuse anyway,+ after paying for the sizing scan."""preconditions, missing = check_run_preconditions()preconditions["person_ttl_attested"] = settings.BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTEDif 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")+ preconditions["person_sizing_attested"] = settings.BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED+ if not preconditions["person_sizing_attested"]:+ missing.append("person seed sizing")+ preconditions["person_topic_bytes_budget"] = settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET+ if settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET <= 0:+ missing.append("person seed topic-bytes budget")return preconditions, missing-def _has_behavioral_filters(cohort: Cohort) -> bool:+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))@@ -88,7 +97,9 @@ def _contains_person_metadata_leaf(cohort: Cohort) -> bool:return any(leaf.get("type") == "person_metadata" for leaf in walk_filter_leaves(properties))-def _person_backfill_ineligibility_reason(cohort: Cohort) -> str | None:+def person_backfill_ineligibility_reason(cohort: Cohort) -> str | None:+ """The single person-run eligibility predicate, shared by the creators, the management command,+ and the dispatch receiver so none of them can judge a cohort backfillable that another refuses."""if cohort.cohort_type != CohortType.REALTIME:return "not realtime"if cohort.is_static:@@ -127,53 +138,106 @@ def _active_participation_cohort_ids(team_id: int, cohort_ids: Iterable[int], *,)+def _has_active_cohort_run(team_id: int, cohort_id: int, *, kind: CohortBackfillKind) -> bool:+ """Mirror of the ``cohort_bfr_active_cohort_kind_uq`` predicate. The participation check above+ misses a run whose participation the seeder already superseded (``record_participation_partial``)+ while the run itself stays active and so still holds the per-cohort uniqueness slot."""+ return (+ CohortBackfillRun.objects.for_team(team_id)+ .filter(cohort_id=cohort_id, backfill_kind=kind, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES)+ .exists()+ )+++def _has_active_team_run(team_id: int, *, kind: CohortBackfillKind) -> bool:+ """Mirror of the ``cohort_bfr_active_team_kind_uq`` predicate, for the same divergent state as+ ``_has_active_cohort_run``: a team run whose participations are all superseded is invisible to+ the participation check but still violates the constraint."""+ return (+ CohortBackfillRun.objects.for_team(team_id)+ .filter(scope=CohortBackfillScope.TEAM, backfill_kind=kind, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES)+ .exists()+ )+++def _active_person_seed_topic_bytes(team_id: int) -> int:+ """Sum of the sizing estimates recorded on the team's active person runs.++ The budget has to bound the team's in-flight person seed bytes as a whole, not each run alone:+ the seeder's person scan is team-wide per run, and the per-cohort uniqueness constraint lets one+ run per cohort stack, so runs that each fit the budget can still add up to many multiples of it.+ """+ return sum(+ preconditions.get("person_seed_estimated_topic_bytes", 0)+ for preconditions in CohortBackfillRun.objects.for_team(team_id)+ .filter(+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY,+ status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ )+ .values_list("preconditions", 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], kind=CohortBackfillKind.BEHAVIORAL):- 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(+ try:+ 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], kind=CohortBackfillKind.BEHAVIORAL):+ return None+ if _has_active_cohort_run(team_id, cohort_id, kind=CohortBackfillKind.BEHAVIORAL):+ 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+ except IntegrityError:+ # A writer this transaction could not see won the unique-constraint race after the conflict+ # checks passed. Refusing is this creator's contract, so return None rather than raise.+ logger.warning(+ "cohort_backfill_run_conflict_race",team_id=team_id,- cohort=cohort,+ cohort_id=cohort_id,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+ return Nonedef _validate_boundary_at(trigger_kind: str, boundary_at: datetime | None) -> datetime | None:@@ -212,7 +276,7 @@ def create_team_backfill_run()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)]+ 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}")@@ -223,6 +287,8 @@ def create_team_backfill_run()if conflicting_ids:raise ValueError(f"Cohorts already have active backfill runs: {sorted(conflicting_ids)}")+ if _has_active_team_run(team_id, kind=CohortBackfillKind.BEHAVIORAL):+ raise ValueError(f"Team {team_id} already has an active team backfill run (behavioral)")hashes: dict[int, str] = {}behavioral_hashes: dict[int, str] = {}@@ -269,10 +335,13 @@ def create_person_backfill_run_for_cohort() -> 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.+ Unlike ``create_person_team_backfill_run`` this refuses quietly where the team creator raises:+ it is the target of ``cohort_person_shape_changed_backfill``, where a refusal must 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. The one exception is a transient+ sizing failure (a ClickHouse timeout or transport error), which propagates so the task's retry+ machinery re-runs it; the scan's own deterministic read cap still refuses quietly, since+ retrying it would only repeat the capped scan."""if not is_realtime_cohort_team(team_id):return None@@ -291,59 +360,144 @@ def create_person_backfill_run_for_cohort()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()+ # Unlocked pre-pass for the sizing gate: the estimate is a ClickHouse round trip, so it must not+ # run while the create path below holds the cohort row FOR UPDATE. The locked pass re-derives+ # eligibility and the pin, and refuses if the definition moved in between.+ cohort = Cohort.objects.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+ if _has_active_cohort_run(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,)- 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+ 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+ person_scan_since = django_timezone.now() - timedelta(days=horizon_days)+ # With a precondition missing the run below records as `blocked`, which the seeder never claims,+ # so paying for the sizing scan would buy nothing.+ preconditions, missing = check_person_run_preconditions()+ estimate: PersonSeedEstimate | None = None+ if not missing:+ # A budget already consumed by in-flight runs refuses before the estimate on purpose: the+ # estimate is the team-wide sizing scan, and dispatch is debounced per cohort, so N edited+ # cohorts would otherwise each pay a scan only to be refused here one by one. Expensive+ # scans record large estimates, so the teams whose scans cost the most stop scanning first.+ active_topic_bytes = _active_person_seed_topic_bytes(team_id)+ if active_topic_bytes >= settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET:+ logger.warning(+ "cohort_person_backfill_over_budget",+ team_id=team_id,+ cohort_id=cohort_id,+ active_topic_bytes=active_topic_bytes,+ budget_bytes=settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET,+ )+ return Nonetry:- pinned = pin_person_conditions_for_cohorts(- [cohort],- max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ estimate = estimate_person_seed_topic_bytes(team_id, person_scan_since, len(pinned["conditions"]))+ except PersonSeedEstimateScanCapExceeded as error:+ logger.warning(+ "cohort_person_backfill_sizing_failed",+ team_id=team_id,+ cohort_id=cohort_id,+ error=str(error),)- except PersonPinningCapExceeded:+ return None+ if estimate.estimated_topic_bytes + active_topic_bytes > estimate.budget_bytes:logger.warning(- "cohort_person_backfill_pinning_cap_exceeded",+ "cohort_person_backfill_over_budget",team_id=team_id,cohort_id=cohort_id,- max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,+ estimated_topic_bytes=estimate.estimated_topic_bytes,+ active_topic_bytes=active_topic_bytes,+ budget_bytes=estimate.budget_bytes,)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(+ try:+ 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+ if _has_active_cohort_run(team_id, cohort_id, kind=CohortBackfillKind.PERSON_PROPERTY):+ return None++ try:+ locked_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+ if locked_pinned != pinned:+ # A racing edit changed the definition after sizing; its own save dispatched a fresh+ # debounced task, so that task owns the re-sized run.+ logger.warning(+ "cohort_person_backfill_definition_changed_during_sizing",+ team_id=team_id,+ cohort_id=cohort_id,+ )+ return None++ filters_shape_hash = ensure_filters_shape_hash(cohort)+ person_filters_shape_hash = cohort.person_filters_shape_hash or ""+ status, blocked_reason = _run_status(missing)+ 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, **(estimate.as_preconditions() if estimate else {})},+ 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+ except IntegrityError:+ # A writer this transaction could not see won the unique-constraint race after the conflict+ # checks passed. Refusing is this creator's contract, so return None rather than raise.+ logger.warning(+ "cohort_backfill_run_conflict_race",team_id=team_id,- cohort=cohort,+ cohort_id=cohort_id,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+ return Nonedef _person_cohorts_for_team(team_id: int, requested_ids: set[int] | None, *, lock: bool) -> list[Cohort]:@@ -361,7 +515,7 @@ def _person_cohorts_for_team(team_id: int, requested_ids: set[int] | None, *, loif 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]+ 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})@@ -385,7 +539,7 @@ def create_person_team_backfill_run(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)+ preconditions, missing = check_person_run_preconditions()if missing:raise ValueError(f"Missing operator attestations: {', '.join(missing)}")@@ -423,6 +577,8 @@ def create_person_team_backfill_run()if conflicting_ids:raise ValueError(f"Cohorts already have active person-property backfill runs: {sorted(conflicting_ids)}")+ if _has_active_team_run(team_id, kind=CohortBackfillKind.PERSON_PROPERTY):+ raise ValueError(f"Team {team_id} already has an active team backfill run (person_property)")hashes: dict[int, str] = {}person_hashes: dict[int, str] = {}@@ -460,6 +616,8 @@ def create_person_team_backfill_run(def supersede_active_runs(team_id: int, cohort_ids: Iterable[int], *, kind: CohortBackfillKind) -> int:+ """Returns the number of participations newly superseded, not everything written: superseding a+ run whose participation the seeder already terminalized returns 0."""cohort_id_set = set(cohort_ids)if not cohort_id_set:return 0@@ -479,10 +637,23 @@ def supersede_active_runs(team_id: int, cohort_ids: Iterable[int], *, kind: Coho).values_list("id", "run_id", "run__scope"))- if not targets:+ # Cohort-scoped runs are also targeted through the run's own cohort column: a seeder partial+ # outcome (`record_participation_partial`) supersedes the participation while the run stays+ # active, and an active run holds the per-cohort uniqueness slot whether or not its+ # participation is already terminal.+ cohort_run_ids = set(+ CohortBackfillRun.objects.for_team(team_id)+ .filter(+ cohort_id__in=cohort_id_set,+ backfill_kind=kind,+ status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ )+ .values_list("id", flat=True)+ )+ cohort_run_ids.update(run_id for _, run_id, scope in targets if scope == CohortBackfillScope.COHORT)+ if not targets and not cohort_run_ids:return 0- cohort_run_ids = [run_id for _, run_id, scope in targets if scope == CohortBackfillScope.COHORT]if cohort_run_ids:CohortBackfillRun.objects.for_team(team_id).filter(id__in=cohort_run_ids).update(status=CohortBackfillRunStatus.SUPERSEDED,diff --git a/products/cohorts/backend/backfill/sizing.py b/products/cohorts/backend/backfill/sizing.pyindex 33c4e51a1e60..23eb96d509f5 100644--- a/products/cohorts/backend/backfill/sizing.py+++ b/products/cohorts/backend/backfill/sizing.py@@ -5,6 +5,7 @@ from typing import Anyfrom django.conf import settingsfrom posthog.clickhouse.client import sync_execute+from posthog.errors import InternalCHQueryError# 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@@ -13,6 +14,16 @@ from posthog.clickhouse.client import sync_executePERSON_SEED_BASE_BYTES = 256PERSON_SEED_PER_HASH_BYTES = 38+# TOO_MANY_ROWS / TOO_MANY_BYTES: what `read_overflow_mode: throw` raises when the scan hits the+# caps below. Deterministic for a given team, unlike a timeout or transport failure.+_READ_CAP_ERROR_CODES = (158, 307)+++class PersonSeedEstimateScanCapExceeded(Exception):+ """The sizing scan hit its own read cap: the team's person history exceeds what the estimate may+ read, so the answer will not change on retry and the caller should refuse rather than repeat the+ capped scan."""+@dataclass(frozen=True)class PersonSeedEstimate:@@ -49,27 +60,34 @@ def estimate_person_seed_topic_bytes(# 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+ try:+ 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,)- """,- {"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,- )+ except InternalCHQueryError as error:+ if error.code in _READ_CAP_ERROR_CODES:+ raise PersonSeedEstimateScanCapExceeded(+ f"Person sizing scan for team {team_id} exceeded its read cap"+ ) from error+ raiseestimated_persons = int(rows[0][0])bytes_per_seed = PERSON_SEED_BASE_BYTES + PERSON_SEED_PER_HASH_BYTES * pinned_condition_countreturn PersonSeedEstimate(diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.pyindex 530405bd6979..74e1612fa551 100644--- a/products/cohorts/backend/backfill/test/test_readiness.py+++ b/products/cohorts/backend/backfill/test/test_readiness.py@@ -47,6 +47,8 @@ KINDS = [BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_SIZING_ATTESTED=True,+ BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,)class TestBackfillReadiness(BaseTest):def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:@@ -186,6 +188,27 @@ class TestBackfillReadiness(BaseTest):self.assertIsNone(cohort.last_backfill_events_at)self.assertIsNone(participation.stamped_at)+ def test_person_edit_revert_is_fenced_by_the_receiver(self) -> None:+ # A -> B -> A restores the pinned person hash, so the stamp's CAS passes again. Only the+ # `superseded_at` that `cohort_person_shape_changed_supersede` set on the first edit keeps+ # readiness off a backfill whose seeded state went stale during the B window.+ cohort, run = self._cohort_and_run(create_person_backfill_run_for_cohort)++ with self.captureOnCommitCallbacks(execute=True):+ cohort.filters = self._filters(7, person_hash="person-b")+ cohort.save(update_fields=["filters"])+ cohort.filters = self._filters(7, person_hash="person-a")+ cohort.save(update_fields=["filters"])++ cohort.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)+ self.assertEqual(cohort.person_filters_shape_hash, participation.person_filters_shape_hash)++ self.assertFalse(stamp_person_properties_readiness(run, cohort.id))++ cohort.refresh_from_db()+ self.assertIsNone(cohort.last_backfill_person_properties_at)+@parameterized.expand(KINDS)def test_supersession_racing_the_stamp_rolls_the_cohort_back(self, _name: str, make_run, stamp, _hash: str, stamp_column: str, *_editsdiff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.pyindex daaeaa8b7a5d..c67a46836936 100644--- a/products/cohorts/backend/backfill/test/test_runs.py+++ b/products/cohorts/backend/backfill/test/test_runs.py@@ -16,7 +16,7 @@ from products.cohorts.backend.backfill.runs import (create_team_backfill_run,supersede_active_runs,)-from products.cohorts.backend.backfill.sizing import PersonSeedEstimate+from products.cohorts.backend.backfill.sizing import PersonSeedEstimate, PersonSeedEstimateScanCapExceededfrom products.cohorts.backend.models.backfill import (CohortBackfillChunk,CohortBackfillKind,@@ -272,6 +272,7 @@ class TestPersonBackfillRuns(BaseTest):"person_horizon_days": expected_horizon_days,},)+ self.assertIn("person_seed_estimated_topic_bytes", run.preconditions)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)@@ -308,6 +309,72 @@ class TestPersonBackfillRuns(BaseTest):person_horizon_days=0,)+ @parameterized.expand([("over_budget",), ("scan_cap_hit",)])+ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_signal_path_refuses_unsized_person_seed(self, _name: str, estimate: mock.Mock) -> None:+ # A user save replays cost here, so the automated path has to honor the same topic-bytes+ # budget as the operator creator. The scan's own read cap refuses quietly too: it is+ # deterministic for the team, so retrying would only repeat the capped scan.+ if _name == "over_budget":+ estimate.return_value = self._estimate(estimated_topic_bytes=2_000_000)+ else:+ estimate.side_effect = PersonSeedEstimateScanCapExceeded("read cap exceeded")+ cohort = self._cohort()++ self.assertIsNone(create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created"))+ 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_transient_sizing_failure_reaches_the_retry_machinery(self, estimate: mock.Mock) -> None:+ # A timeout or transport blip is worth retrying; swallowing it would leave the cohort with+ # no run and nothing scheduled to try again until its next edit.+ estimate.side_effect = ConnectionError("clickhouse unavailable")+ cohort = self._cohort()++ with self.assertRaises(ConnectionError):+ create_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")++ 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_budget_bounds_the_teams_active_person_runs_in_aggregate(self, estimate: mock.Mock) -> None:+ # The seeder's person scan is team-wide per run and the uniqueness constraint is per cohort,+ # so runs that each fit the budget stack cost; the gate has to count what is already in+ # flight for the team.+ estimate.return_value = self._estimate(estimated_topic_bytes=600_000)+ first = self._cohort()+ second = Cohort.objects.create(+ team=self.team,+ name="second person cohort",+ cohort_type=CohortType.REALTIME,+ filters=self._filters(),+ )++ self.assertIsNotNone(create_person_backfill_run_for_cohort(self.team.id, first.id, "cohort_created"))+ self.assertIsNone(create_person_backfill_run_for_cohort(self.team.id, second.id, "cohort_created"))+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)++ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")+ def test_consumed_budget_refuses_before_the_sizing_scan(self, estimate: mock.Mock) -> None:+ # Dispatch is debounced per cohort, so once in-flight runs consume the whole budget, every+ # further edited cohort has to refuse before the team-wide sizing scan, not after paying+ # for one each.+ estimate.return_value = self._estimate(estimated_topic_bytes=1_000_000)+ first = self._cohort()+ self.assertIsNotNone(create_person_backfill_run_for_cohort(self.team.id, first.id, "cohort_created"))+ second = Cohort.objects.create(+ team=self.team,+ name="second person cohort",+ cohort_type=CohortType.REALTIME,+ filters=self._filters(),+ )++ estimate.reset_mock()+ self.assertIsNone(create_person_backfill_run_for_cohort(self.team.id, second.id, "cohort_created"))++ estimate.assert_not_called()+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)+@override_settings(BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS=0)def test_cohort_run_warns_and_refuses_pinning_cap(self) -> None:cohort = self._cohort()@@ -354,6 +421,62 @@ class TestPersonBackfillRuns(BaseTest):self.assertEqual(expected[superseded_kind].status, CohortBackfillRunStatus.SUPERSEDED)self.assertEqual(other[superseded_kind].status, CohortBackfillRunStatus.AWAITING_BOUNDARY)+ def test_editing_the_person_leaf_supersedes_only_the_person_run(self) -> None:+ # rust/cohort-seeder replays the person conditions a run pinned and the finalizer stamps+ # readiness from them, so a person-leaf edit has to supersede that run. The behavioral run+ # pins leaves this edit does not touch, so it has to survive.+ 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++ with self.captureOnCommitCallbacks(execute=True):+ cohort.filters = self._filters(person_hashes=("person0000000002",))+ cohort.save()++ behavioral.refresh_from_db()+ person.refresh_from_db()+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=person)+ self.assertEqual(person.status, CohortBackfillRunStatus.SUPERSEDED)+ self.assertIsNotNone(participation.superseded_at)+ self.assertEqual(behavioral.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)++ @parameterized.expand(+ [+ ("behavioral", create_backfill_run_for_cohort, CohortBackfillKind.BEHAVIORAL),+ ("person_property", create_person_backfill_run_for_cohort, CohortBackfillKind.PERSON_PROPERTY),+ ]+ )+ def test_seeder_partial_outcome_does_not_wedge_the_cohort(+ self, _name: str, creator, kind: CohortBackfillKind+ ) -> None:+ # The seeder's record_participation_partial supersedes the participation but leaves the run+ # active, so the run still holds the cohort_bfr_active_cohort_kind_uq slot. The creator has+ # to refuse on the run, not only the participation, or it raises IntegrityError; and+ # supersession has to target the run directly, or nothing ever frees the slot while the+ # finalizer's person gate is closed.+ cohort = self._cohort()+ run = creator(self.team.id, cohort.id, "cohort_created")+ assert run is not None+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(run=run).update(+ superseded_at=datetime.now(UTC), error="stage 2 hash mismatch"+ )+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(+ status=CohortBackfillRunStatus.RECONCILING+ )++ # The active-run refusal has to fire in the pre-pass, before the sizing scan: the sibling+ # IntegrityError catch also returns None, so without this the run-level guard is unpinned.+ with mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes") as estimate:+ self.assertIsNone(creator(self.team.id, cohort.id, "cohort_edited"))+ estimate.assert_not_called()++ supersede_active_runs(self.team.id, [cohort.id], kind=kind)+ run.refresh_from_db()+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)+ self.assertIsNotNone(creator(self.team.id, cohort.id, "cohort_edited"))+@parameterized.expand([("behavioral_only", {"filters": None}),diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.pyindex a0c0fcdb34cd..15d0e6ba4edc 100644--- a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py@@ -15,12 +15,13 @@ from products.cohorts.backend.backfill.pinning import (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,+ has_behavioral_filters,+ person_backfill_ineligibility_reason,)from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytesfrom products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRunCohort, CohortBackfillTrigger@@ -29,12 +30,6 @@ from products.cohorts.backend.models.leaf_shape import walk_filter_leavesfrom 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"))- )--def _parse_boundary_at(value: str | None) -> datetime | None:if value is None:return None@@ -111,7 +106,7 @@ class Command(BaseCommand):)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)]+ 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)@@ -145,7 +140,7 @@ class Command(BaseCommand):boundary_at: datetime | None,dry_run: bool,) -> None:- _, missing = check_person_run_preconditions(requires_sizing_attestation=True)+ _, missing = check_person_run_preconditions()if missing:raise CommandError(f"Missing operator attestations: {', '.join(missing)}")if person_horizon_days < 1:@@ -196,11 +191,11 @@ class Command(BaseCommand):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`.+ # 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")]+ 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:diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.pyindex d63c6d3f0daf..15a890e52768 100644--- a/products/cohorts/backend/models/cohort.py+++ b/products/cohorts/backend/models/cohort.py@@ -267,6 +267,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# deprecated in favor of filtersgroups = models.JSONField(default=list)+ # Transient save() state, not columns: _maintain_filter_shape_hashes sets these so the post_save+ # backfill receivers, which get this same instance, can tell which leaf shapes the save moved.+ _leaf_shape_changed: bool = False+ _person_shape_changed: bool = False+objects = CohortManager() # type: ignoreclass Meta:@@ -314,6 +319,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):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):@@ -379,6 +385,7 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):self._leaf_shape_changed = Trueif person_shape_changed:self.last_backfill_person_properties_at = None+ self._person_shape_changed = Trueif maintained_update_fields is None:return Nonediff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.pyindex d5b16525d47a..aaece96d75de 100644--- a/products/cohorts/backend/models/dependencies.py+++ b/products/cohorts/backend/models/dependencies.py@@ -13,12 +13,18 @@ from rest_framework.exceptions import ValidationErrorfrom structlog import get_loggerfrom posthog.models.team.team import Team+from posthog.redis import get_client as get_redis_client-from products.cohorts.backend.models.backfill import CohortBackfillKind-from products.cohorts.backend.models.cohort import Cohort, is_cohort_recalculation_only_save+from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillTrigger+from products.cohorts.backend.models.cohort import Cohort, CohortType, is_cohort_recalculation_only_save+from products.cohorts.backend.realtime_teams import is_cohort_backfill_trigger_team, is_realtime_cohort_teamlogger = get_logger(__name__)DEPENDENCY_CACHE_TIMEOUT = 7 * 24 * 60 * 60 # 1 week+COHORT_BACKFILL_DEBOUNCE_SECONDS = 300 # 5 minutes+# The lock expiring exactly as the task fires is what closes the lost-dispatch window: a TTL longer+# than the countdown would swallow a save that lands after the task already read its state.+COHORT_BACKFILL_REDIS_TTL_SECONDS = COHORT_BACKFILL_DEBOUNCE_SECONDS# Prometheus metrics for cache hit/miss trackingCOHORT_DEPENDENCY_CACHE_COUNTER = Counter(@@ -29,10 +35,19 @@ COHORT_DEPENDENCY_CACHE_COUNTER = Counter(COHORT_REALTIME_STATE_ORPHANED_COUNTER = Counter("posthog_cohort_realtime_state_orphaned_total",- "Realtime cohort edits that changed the Stage 1 LeafStateKey input set",+ "Realtime cohort edits that orphaned Stage 1 state keyed on the pre-edit definition",labelnames=["reason"],)+# `not_realtime_team` is the one outcome with no log line: it fires on every save of a+# trigger-allowlisted team the realtime allowlist misses, and logging that per save would be noise+# while the misconfiguration itself deserves a signal an operator can alert on.+COHORT_BACKFILL_TRIGGER_COUNTER = Counter(+ "posthog_cohort_backfill_trigger_total",+ "Dispatch outcomes of cohort saves that were candidates for a backfill run",+ labelnames=["backfill_kind", "outcome"],+)+def _cohort_dependencies_key(cohort_id: int) -> str:return f"cohort:dependencies:{cohort_id}"@@ -308,18 +323,103 @@ def _on_cohort_changed(cohort: Cohort, always_invalidate: bool = False):warm_team_cohort_dependency_cache(cohort.team_id)-def _supersede_cohort_events_backfills(cohort: Cohort) -> None:+def _has_backfillable_filters(cohort: Cohort, kind: CohortBackfillKind) -> bool:+ from products.cohorts.backend.backfill.runs import ( # noqa: PLC0415 — avoids a model-load cycle+ has_behavioral_filters,+ person_backfill_ineligibility_reason,+ )++ if kind == CohortBackfillKind.PERSON_PROPERTY:+ # The creator's own predicate, so this cannot judge backfillable a cohort the creator will+ # permanently refuse (for example one that also carries a person_metadata leaf).+ return person_backfill_ineligibility_reason(cohort) is None+ return has_behavioral_filters(cohort)+++def _trigger_cohort_backfill(cohort: Cohort, trigger_kind: str, kind: CohortBackfillKind) -> None:+ """Enqueue one debounced run-creation task, at most one per cohort and kind per window.++ The Redis TTL matching the countdown is what closes the window: the key expires exactly when the+ task fires, so a save arriving after that schedules the next task instead of being swallowed.+ """+ try:+ from posthog.tasks.calculate_cohort import (+ trigger_cohort_backfill_run_task, # noqa: PLC0415 — avoids a task import during model loading+ )++ redis_client = get_redis_client()+ lock_key = f"cohort_backfill_{kind}_pending:{cohort.pk}"+ if not redis_client.set(lock_key, 1, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="debounced").inc()+ logger.info(+ "cohort_backfill_already_pending",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ backfill_kind=kind,+ )+ return++ logger.info(+ "triggering_cohort_backfill",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ backfill_kind=kind,+ trigger_kind=trigger_kind,+ debounce_seconds=COHORT_BACKFILL_DEBOUNCE_SECONDS,+ )+ try:+ trigger_cohort_backfill_run_task.apply_async(+ args=[cohort.team_id, cohort.pk, trigger_kind, kind],+ countdown=COHORT_BACKFILL_DEBOUNCE_SECONDS,+ )+ except Exception:+ # Release the lock so the next save can retry scheduling.+ redis_client.delete(lock_key)+ raise+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="enqueued").inc()+ except Exception as error:+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="enqueue_failed").inc()+ logger.exception(+ "failed_to_trigger_cohort_backfill",+ cohort_id=cohort.pk,+ team_id=cohort.team_id,+ backfill_kind=kind,+ error=str(error),+ )+++def _backfill_trigger_kind(instance: Cohort, kwargs: dict, *, shape_changed: bool) -> str | None:+ """The trigger label for a save that should enqueue a run, or None when it should not.++ ``created`` has to be checked separately from ``shape_changed``, which compares against a stored+ hash and so is always False on an insert. Guarding on the flag alone would silently drop the+ create path.+ """+ if is_cohort_recalculation_only_save(kwargs):+ return None+ update_fields = kwargs.get("update_fields")+ if update_fields is not None and "filters" not in update_fields:+ return None+ if instance.cohort_type != CohortType.REALTIME or instance.is_static or instance.deleted:+ return None+ if kwargs.get("created", False):+ return CohortBackfillTrigger.COHORT_CREATED+ return CohortBackfillTrigger.COHORT_EDITED if shape_changed else None+++def _supersede_cohort_backfills(cohort: Cohort, kind: CohortBackfillKind) -> 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], kind=CohortBackfillKind.BEHAVIORAL)+ supersede_active_runs(cohort.team_id, [cohort.id], kind=kind)except Exception as error:logger.exception(- "failed_to_supersede_cohort_events_backfills",+ "failed_to_supersede_cohort_backfills",cohort_id=cohort.pk,team_id=cohort.team_id,+ backfill_kind=kind,error=str(error),)@@ -350,11 +450,99 @@ def cohort_behavioral_shape_changed_supersede(sender, instance, **kwargs):`_leaf_shape_changed` is only set for allowlisted realtime, non-static, non-deleted cohorts on areal `filters` change, so it is the whole guard."""- if not getattr(instance, "_leaf_shape_changed", False):+ if not instance._leaf_shape_changed:returnCOHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed").inc()- transaction.on_commit(lambda: _supersede_cohort_events_backfills(instance))+ transaction.on_commit(lambda: _supersede_cohort_backfills(instance, CohortBackfillKind.BEHAVIORAL))+++@receiver(post_save, sender=Cohort)+def cohort_person_shape_changed_supersede(sender, instance, **kwargs):+ """Invalidate in-flight person-property backfill runs when the cohort's person leaf shape changes.++ The person mirror of `cohort_behavioral_shape_changed_supersede`, and the edit-time fence the+ person readiness stamp relies on. After an A -> B -> A revert the participation's pinned person+ hash matches the cohort's current one again, so the hash CAS in `_stamp_readiness` would stamp+ readiness over a backfill whose seeded state went stale during the B window; only the+ `superseded_at` set here refuses that stamp.++ `_person_shape_changed` is only set for allowlisted realtime, non-static, non-deleted cohorts on+ a real `filters` change, so it is the whole guard.+ """+ if not instance._person_shape_changed:+ return++ COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="person_condition_hash_changed").inc()+ transaction.on_commit(lambda: _supersede_cohort_backfills(instance, CohortBackfillKind.PERSON_PROPERTY))+++@receiver(post_save, sender=Cohort)+def cohort_behavioral_shape_changed_backfill(sender, instance, **kwargs):+ """Enqueue a behavioral backfill run when an allowlisted team creates or edits a cohort.++ Separate from the supersede receiver above on purpose. Superseding an invalidated run is a+ correctness obligation to rust/cohort-seeder that has to hold for every realtime team, while+ creating a replacement run costs a ClickHouse history replay, so it stays behind the narrower+ `COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST`. Keeping them apart means the expensive half can be off+ for a team while the cheap half still runs.++ The trigger allowlist opts a team in on top of realtime membership, which the creators require:+ without the realtime check here, a team listed only in the trigger allowlist would debounce a+ task on every create that the creators are guaranteed to refuse, with nothing naming the cause.+ """+ try:+ if not is_cohort_backfill_trigger_team(instance.team_id):+ return+ if not is_realtime_cohort_team(instance.team_id):+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(+ backfill_kind=CohortBackfillKind.BEHAVIORAL, outcome="not_realtime_team"+ ).inc()+ return+ trigger_kind = _backfill_trigger_kind(instance, kwargs, shape_changed=instance._leaf_shape_changed)+ if trigger_kind is None or not _has_backfillable_filters(instance, CohortBackfillKind.BEHAVIORAL):+ return++ transaction.on_commit(lambda: _trigger_cohort_backfill(instance, trigger_kind, CohortBackfillKind.BEHAVIORAL))+ 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_save, sender=Cohort)+def cohort_person_shape_changed_backfill(sender, instance, **kwargs):+ """Enqueue a person-property backfill run when an allowlisted team creates or edits a cohort.++ The person mirror of `cohort_behavioral_shape_changed_backfill`, sharing its allowlist. A cohort+ carrying both leaf kinds gets one run of each, on separate debounce keys, because the two seed+ different stores and stamp different readiness columns.+ """+ try:+ if not is_cohort_backfill_trigger_team(instance.team_id):+ return+ if not is_realtime_cohort_team(instance.team_id):+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY, outcome="not_realtime_team"+ ).inc()+ return+ trigger_kind = _backfill_trigger_kind(instance, kwargs, shape_changed=instance._person_shape_changed)+ if trigger_kind is None or not _has_backfillable_filters(instance, CohortBackfillKind.PERSON_PROPERTY):+ return++ transaction.on_commit(+ lambda: _trigger_cohort_backfill(instance, trigger_kind, CohortBackfillKind.PERSON_PROPERTY)+ )+ except Exception as error:+ logger.exception(+ "failed_to_handle_cohort_person_shape_change",+ cohort_id=instance.pk,+ team_id=instance.team_id,+ error=str(error),+ )@receiver(post_delete, sender=Cohort)diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.pyindex d8da2bfa3209..861e0f25748a 100644--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py@@ -5,9 +5,19 @@ from django.test import override_settingsfrom django.utils import timezonefrom django.utils.deprecation import RemovedInDjango60Warning+from parameterized import parameterized++from products.cohorts.backend.models.backfill import CohortBackfillKindfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.dependencies import COHORT_REALTIME_STATE_ORPHANED_COUNTER+# (name, run kind, two successive edits as `_filters` args) — the edits move only this kind's leaf+# shape, so only this kind's receiver reacts to them even though both share one allowlist.+TRIGGER_KINDS = [+ ("behavioral", CohortBackfillKind.BEHAVIORAL, ((14, "person-a"), (30, "person-a"))),+ ("person_property", CohortBackfillKind.PERSON_PROPERTY, ((7, "person-b"), (7, "person-c"))),+]+@override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="all")class TestBehavioralBackfillDependencies(BaseTest):@@ -214,6 +224,156 @@ class TestBehavioralBackfillDependencies(BaseTest):self.assertEqual(cohort.last_backfill_events_at, ready_at)self.assertEqual(self._orphan_count(), before)+ def _redis(self, *set_results: bool) -> mock.Mock:+ redis = mock.Mock()+ if set_results:+ redis.set.side_effect = list(set_results)+ else:+ redis.set.return_value = True+ return redis++ def test_default_trigger_allowlist_enqueues_nothing(self) -> None:+ # The trigger allowlist defaults to no teams, so merging this cannot start seeding anywhere+ # until an operator opts a team in, even though the realtime allowlist is wide open here.+ redis = self._redis()+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ cohort = self._cohort(7, person_hash="person-a")+ cohort.filters = self._filters(30, person_hash="person-b")+ cohort.save()++ enqueue.assert_not_called()+ redis.set.assert_not_called()++ def _assert_one_debounced_task_per_kind(self, enqueue, redis, cohort: Cohort, trigger: str) -> None:+ self.assertEqual(+ {tuple(call.kwargs["args"][2:]) for call in enqueue.call_args_list},+ {(trigger, CohortBackfillKind.BEHAVIORAL), (trigger, CohortBackfillKind.PERSON_PROPERTY)},+ )+ self.assertEqual({call.kwargs["countdown"] for call in enqueue.call_args_list}, {300})+ self.assertEqual(+ {call.args[0] for call in redis.set.call_args_list},+ {+ f"cohort_backfill_behavioral_pending:{cohort.id}",+ f"cohort_backfill_person_property_pending:{cohort.id}",+ },+ )+ # Without nx every save enqueues a replay; without ex outliving the countdown, an expired+ # window swallows saves forever. Both are the debounce design's whole contract.+ for call in redis.set.call_args_list:+ self.assertEqual(call.kwargs, {"nx": True, "ex": 300})++ @override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all")+ def test_create_enqueues_one_debounced_task_per_leaf_kind(self) -> None:+ # A new cohort has no stored hash to differ from, so its shape-changed flag is False here.+ # Guarding the receivers on that flag alone would silently never seed a newly created cohort.+ redis = self._redis()+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ cohort = self._cohort(7, person_hash="person-a")++ self._assert_one_debounced_task_per_kind(enqueue, redis, cohort, "cohort_created")++ def test_edit_touching_both_leaf_kinds_enqueues_one_task_per_kind(self) -> None:+ # The kinds seed different stores, so one save that moves both shapes owes a task to each, on+ # keys that cannot debounce one another. The cohort is created before the trigger allowlist+ # opens, so the create dispatches nothing real behind the edit's mocks.+ cohort = self._cohort(7, person_hash="person-a")+ redis = self._redis()+ with (+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ cohort.filters = self._filters(30, person_hash="person-b")+ cohort.save()++ self._assert_one_debounced_task_per_kind(enqueue, redis, cohort, "cohort_edited")++ @parameterized.expand(TRIGGER_KINDS)+ def test_two_edits_share_one_debounce_key(self, _name: str, kind: CohortBackfillKind, edits) -> None:+ cohort = self._cohort(7, person_hash="person-a")+ redis = self._redis(True, False)+ with (+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ for window_days, person_hash in edits:+ cohort.filters = self._filters(window_days, person_hash=person_hash)+ cohort.save()++ enqueue.assert_called_once_with(+ args=[self.team.id, cohort.id, "cohort_edited", kind],+ countdown=300,+ )+ self.assertEqual(+ redis.set.call_args_list,+ [mock.call(f"cohort_backfill_{kind.value}_pending:{cohort.id}", 1, nx=True, ex=300)] * 2,+ )++ @parameterized.expand(+ [+ ("static", {"is_static": True}),+ ("non_realtime_type", {"cohort_type": None}),+ ]+ )+ @override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all")+ def test_ineligible_create_enqueues_nothing(self, _name: str, overrides: dict) -> None:+ # Creates skip the shape-changed flags and dispatch straight off kwargs["created"], so the+ # type guard in _backfill_trigger_kind is all that keeps every ordinary (static or+ # non-realtime) cohort create in an opted-in team from firing tasks the creators refuse.+ redis = self._redis()+ params: dict = {+ "team": self.team,+ "cohort_type": CohortType.REALTIME,+ "filters": self._filters(7, person_hash="person-a"),+ **overrides,+ }+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ Cohort.objects.create(**params)++ enqueue.assert_not_called()+ redis.set.assert_not_called()++ @override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="999999999", COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all")+ def test_trigger_allowlisted_but_non_realtime_team_enqueues_nothing(self) -> None:+ # The trigger allowlist opts a team in on top of realtime membership. Without the receivers'+ # realtime gate, this misconfiguration would debounce a task on every create that the+ # creators are guaranteed to refuse, forever, with nothing pointing at the cause.+ redis = self._redis()+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,+ ):+ self._cohort(7, person_hash="person-a")++ enqueue.assert_not_called()+ redis.set.assert_not_called()++ @override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all")+ def test_failed_enqueue_releases_the_debounce_lock(self) -> None:+ # If the broker rejects the publish after the lock is claimed, the lock has to be released,+ # or every save in the next window is swallowed with no task behind the key.+ redis = self._redis()+ with (+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),+ mock.patch(+ "posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async",+ side_effect=Exception("broker down"),+ ),+ ):+ cohort = self._cohort(7)++ redis.delete.assert_called_once_with(f"cohort_backfill_behavioral_pending:{cohort.id}")+def test_hashing_failure_in_maintain_shape_does_not_break_save(self) -> None:# _maintain_filter_shape_hashes swallows hashing errors so a hashing bug can't take down every# realtime cohort save. This exercises that guard directly by making the hash raise.diff --git a/products/cohorts/backend/realtime_teams.py b/products/cohorts/backend/realtime_teams.pyindex 19227bf642c5..248a04e3abde 100644--- a/products/cohorts/backend/realtime_teams.py+++ b/products/cohorts/backend/realtime_teams.py@@ -4,8 +4,8 @@ from django.conf import settings_MAX_RANGE_SPAN = 100_000-def is_realtime_cohort_team(team_id: int) -> bool:- """Whether the realtime-cohort pipeline is scoped to ``team_id``.+def _team_in_allowlist(raw_allowlist: str, team_id: int) -> bool:+ """Whether ``team_id`` matches a team-allowlist setting.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@@ -15,7 +15,7 @@ def is_realtime_cohort_team(team_id: int) -> bool: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()+ raw_allowlist = raw_allowlist.strip()if raw_allowlist == "" or raw_allowlist.lower() == "all" or raw_allowlist == "*":return Trueif raw_allowlist.lower() == "none":@@ -35,3 +35,17 @@ def is_realtime_cohort_team(team_id: int) -> bool:if start <= end <= start + _MAX_RANGE_SPAN - 1 and start <= team_id <= end:return Truereturn False+++def is_realtime_cohort_team(team_id: int) -> bool:+ """Whether the realtime-cohort pipeline is scoped to ``team_id``."""+ return _team_in_allowlist(settings.REALTIME_COHORT_TEAM_ALLOWLIST, team_id)+++def is_cohort_backfill_trigger_team(team_id: int) -> bool:+ """Whether saving a cohort in ``team_id`` should enqueue backfill runs for it."""+ if not settings.COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST.strip():+ # No Rust service parses this setting, so it can fail closed on empty where the realtime+ # allowlist cannot: a set-but-empty value means no teams, not every team.+ return False+ return _team_in_allowlist(settings.COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST, team_id)diff --git a/products/cohorts/backend/test/test_realtime_teams.py b/products/cohorts/backend/test/test_realtime_teams.pyindex 8fe90cc37abc..05a6601593c3 100644--- a/products/cohorts/backend/test/test_realtime_teams.py+++ b/products/cohorts/backend/test/test_realtime_teams.py@@ -9,7 +9,7 @@ from parameterized import parameterizedimport posthog.settings.cohorts as cohorts_settings-from products.cohorts.backend.realtime_teams import is_realtime_cohort_team+from products.cohorts.backend.realtime_teams import is_cohort_backfill_trigger_team, is_realtime_cohort_teamclass TestIsRealtimeCohortTeam(SimpleTestCase):@@ -44,6 +44,23 @@ class TestIsRealtimeCohortTeam(SimpleTestCase):self.assertEqual(is_realtime_cohort_team(team_id), expected)+class TestIsCohortBackfillTriggerTeam(SimpleTestCase):+ @parameterized.expand(+ [+ # Only Python parses this setting, so unlike the realtime allowlist it fails closed on a+ # set-but-empty value, the natural Helm rendering of "clear this".+ ("empty_fails_closed", "", 2, False),+ ("whitespace_fails_closed", " ", 2, False),+ ("all_keyword", "all", 2, True),+ ("single_match", "2", 2, True),+ ("single_miss", "2", 3, False),+ ]+ )+ def test_membership(self, _name: str, allowlist: str, team_id: int, expected: bool) -> None:+ with override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST=allowlist):+ self.assertEqual(is_cohort_backfill_trigger_team(team_id), expected)++class TestRealtimeCohortAllowlistSetting(SimpleTestCase):def _reload_allowlist(self) -> str:self.addCleanup(importlib.reload, cohorts_settings)diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rsindex 3b30dce701d0..62d1b42a6c8a 100644--- a/rust/cohort-seeder/src/config.rs+++ b/rust/cohort-seeder/src/config.rs@@ -196,13 +196,12 @@ pub struct Config {/// `UnknownKind` and skip-commits it without a marker, stranding the run as a shortfall./// 2. Flip `SEEDER_PERSON_SEEDS_ENABLED` and let person runs seed./// 3. Flip this once step 1 is confirmed everywhere.- /// 4. Flip Django's `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` once both preconditions in- /// its `posthog/settings/cohorts.py` docstring hold: the flags service no longer reads- /// `last_backfill_person_properties_at` as proof `cohort_membership` is populated, and a- /// person-leaf edit supersedes the cohort's active person runs. Until then the finalizer- /// skips person runs, so they stay `reconciling` after step 3 and- /// `seeder_runs_reconciling{kind="person_property"}` climbs. That is expected, not a- /// stalled dispatch.+ /// 4. Flip Django's `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` once the remaining+ /// precondition in its `posthog/settings/cohorts.py` docstring holds: the flags service no+ /// longer reads `last_backfill_person_properties_at` as proof `cohort_membership` is+ /// populated. Until then the finalizer skips person runs, so they stay `reconciling` after+ /// step 3 and `seeder_runs_reconciling{kind="person_property"}` climbs. That is expected,+ /// not a stalled dispatch.////// Flipping this back off does not undo a bad rollout: a run already in `reconciling` stops/// being discovered, so it never reaches `reconcile_observed_at` and never finalizes. Recovery