Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cohorts): backfill completion protocol django foundation (#73737)

Matheus Batista57692ae47e70
diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.py
index 116506d5db58..2ad06fbe14c0 100644
--- a/posthog/settings/cohorts.py
+++ b/posthog/settings/cohorts.py
@@ -11,3 +11,11 @@ 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_FINALIZER_ENABLED: bool = get_from_env(
+ "BEHAVIORAL_BACKFILL_FINALIZER_ENABLED", False, type_cast=str_to_bool
+)
+# Bounds one finalizer pass: held runs come back every pass, so an unbounded scan would grow with a
+# stalled seeder instead of staying proportional to what a pass can actually resolve.
+BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS: int = get_from_env(
+ "BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS", 500, type_cast=int
+)
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index 4862879ccaf2..717ae9a381e6 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -22,6 +22,7 @@ from posthog.models.user import User
from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
+from products.cohorts.backend.backfill.finalize import finalize_backfill_runs
from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohort
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
@@ -913,3 +914,11 @@ def trigger_cohort_events_backfill_task(team_id: int, cohort_id: int, trigger_ki
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 by
+ ``BEHAVIORAL_BACKFILL_FINALIZER_ENABLED`` (checked inside ``finalize_backfill_runs``, which
+ returns before touching the DB when disabled)."""
+ finalize_backfill_runs()
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 3ce70ff46039..a77cb77fc9dd 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -11,6 +11,7 @@ from posthog.caching.warming import schedule_warming_for_teams_task
from posthog.clickhouse.client.execute_async import QueryStatusManager
from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports
from posthog.tasks.auth_token_cache_verification import verify_and_fix_auth_token_cache_task
+from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs
from posthog.tasks.email import (
EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC,
send_error_tracking_weekly_digest,
@@ -624,6 +625,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
args=(settings.CALCULATE_X_PARALLEL_COHORTS_DURING_NIGHT,),
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/2"),
+ finalize_cohort_backfill_runs.s(),
+ name="finalize cohort backfill runs",
+ )
+
add_periodic_task_with_expiry(
sender,
crontab(minute="*/2"),
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index a51391c9f043..5558261420c7 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -15,6 +15,7 @@
'posthog.tasks.calculate_cohort.calculate_cohort_ch',
'posthog.tasks.calculate_cohort.calculate_cohort_from_list',
'posthog.tasks.calculate_cohort.collect_cohort_query_stats',
+ 'posthog.tasks.calculate_cohort.finalize_cohort_backfill_runs',
'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',
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.py
new file mode 100644
index 000000000000..5803b1beaa35
--- /dev/null
+++ b/products/cohorts/backend/backfill/finalize.py
@@ -0,0 +1,246 @@
+"""Terminalizes behavioral backfill runs the Rust seeder has fully observed.
+
+B5 stamps only ``last_backfill_events_at``; mixed person+behavioral cohorts stay flag-incompatible
+until B7 stamps the person-properties column (intended fail-closed).
+
+The seeder writes a definitive per-participation outcome (``reconcile_completed_at`` /
+``superseded_at`` / retryable ``error``) before it sets ``run.reconcile_observed_at`` as its last
+write (INV-1). This finalizer trusts those columns — never Kafka — and CASes the run out of
+``reconciling`` once every participation has a terminal outcome (INV-5).
+"""
+
+from dataclasses import dataclass
+from uuid import UUID
+
+from django.conf import settings
+from django.db import transaction
+from django.db.models.functions import Now
+
+import structlog
+from celery import current_app
+from prometheus_client import Counter, Gauge
+
+from posthog.tasks.utils import CeleryQueue
+
+from products.cohorts.backend.backfill.readiness import stamp_events_readiness
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+)
+from products.cohorts.backend.models.dependencies import invalidate_team_behavioral_cohort_cache
+
+logger = structlog.get_logger(__name__)
+
+# products.feature_flags already depends on products.cohorts, so a static import of its task here
+# would close a forbidden product-dependency cycle; dispatch by registered task name instead. The
+# task pins the same string via ``name=`` so moving its module can't silently rename it out from
+# under us; test_finalize.py asserts the two still agree.
+FLAGS_CACHE_TASK = "products.feature_flags.backend.tasks.update_team_service_flags_cache"
+
+READINESS_STAMPS_COUNTER = Counter(
+ "posthog_cohort_backfill_readiness_stamps_total",
+ "Backfill participations resolved by the finalizer, by outcome",
+ ["result"], # labels: "stamped", "superseded"
+)
+
+RUNS_FINALIZED_COUNTER = Counter(
+ "posthog_cohort_backfill_runs_finalized_total",
+ "Backfill runs terminalized by the finalizer, by terminal status",
+ ["status"], # labels: "completed", "superseded"
+)
+
+# Split by reason: a shortfall is routine backpressure, an error is a crashed pass. Summing them
+# would leave an alert unable to tell which one is happening.
+HELD_RUNS_GAUGE = Gauge(
+ "posthog_cohort_backfill_finalizer_held_runs",
+ "Observed backfill runs the finalizer left in reconciling, by reason",
+ ["reason"], # labels: "shortfall" (an outcome was missing), "error" (the pass raised)
+ multiprocess_mode="max",
+)
+
+
+@dataclass
+class FinalizerPass:
+ runs_scanned: int = 0
+ completed: int = 0
+ superseded: int = 0
+ held: int = 0
+ errored: int = 0
+ stamped_participations: int = 0
+ invalidated_teams: int = 0
+
+
+def _dispatch_flags_cache_update(team_id: int) -> None:
+ # send_task bypasses the task decorator's options, so the queue must be routed explicitly.
+ current_app.send_task(FLAGS_CACHE_TASK, args=(team_id,), queue=CeleryQueue.FEATURE_FLAGS.value)
+
+
+def finalize_backfill_runs() -> FinalizerPass:
+ """One finalizer pass. Returns a summary so callers/tests can assert without scraping logs."""
+ result = FinalizerPass()
+ if not settings.BEHAVIORAL_BACKFILL_FINALIZER_ENABLED:
+ # Reset rather than leave the gauge frozen at its last value: multiprocess_mode="max" keeps
+ # a stale reading alive fleet-wide until the process recycles.
+ _publish_held_runs(result)
+ return result
+
+ # Deliberate, documented cross-team scan: the finalizer serves all teams. Each row is re-locked
+ # per team inside the loop, so the unscoped read is discovery only. Oldest-observed first, which
+ # the partial index already orders by, so a capped pass drains the backlog in arrival order.
+ observed = list(
+ CohortBackfillRun.objects.unscoped()
+ .filter(
+ # B5 stamps only the events column, so never terminalize a person-properties run (B7).
+ backfill_kind=CohortBackfillKind.BEHAVIORAL,
+ status=CohortBackfillRunStatus.RECONCILING,
+ reconcile_observed_at__isnull=False,
+ )
+ .order_by("reconcile_observed_at")
+ .values_list("id", "team_id")[: settings.BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS]
+ )
+
+ teams_to_invalidate: set[int] = set()
+ for run_id, team_id in observed:
+ try:
+ invalidate_team = _finalize_one_run(run_id, team_id, result)
+ except Exception:
+ # The transaction rolled back, so the run is still reconciling — count it so the pager
+ # gauge reflects a stuck run rather than reading clean.
+ logger.exception("cohort_backfill_finalizer_run_error", run_id=str(run_id), team_id=team_id)
+ result.errored += 1
+ continue
+ if invalidate_team:
+ teams_to_invalidate.add(team_id)
+
+ # Invalidation bypasses the cohort save signals, so it must run explicitly once per team, and only
+ # after the per-run transactions have committed.
+ for team_id in teams_to_invalidate:
+ try:
+ invalidate_team_behavioral_cohort_cache(team_id)
+ _dispatch_flags_cache_update(team_id)
+ except Exception:
+ logger.exception("cohort_backfill_finalizer_cache_invalidation_failed", team_id=team_id)
+ continue
+ result.invalidated_teams += 1
+
+ _publish_held_runs(result)
+ return result
+
+
+def _publish_held_runs(result: FinalizerPass) -> None:
+ HELD_RUNS_GAUGE.labels(reason="shortfall").set(result.held)
+ HELD_RUNS_GAUGE.labels(reason="error").set(result.errored)
+
+
+def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool:
+ """Terminalize one observed run. Returns whether the team's caches need invalidating."""
+ stamped = 0
+ superseded = 0
+ held = 0
+ invalidate_team = False
+ with transaction.atomic():
+ run = (
+ CohortBackfillRun.objects.for_team(team_id)
+ .select_for_update(skip_locked=True, of=("self",))
+ .filter(
+ id=run_id,
+ status=CohortBackfillRunStatus.RECONCILING,
+ reconcile_observed_at__isnull=False,
+ )
+ .first()
+ )
+ if run is None:
+ # Locked by another worker, or no longer eligible; a later pass retries.
+ return False
+
+ result.runs_scanned += 1
+
+ participations = list(CohortBackfillRunCohort.objects.for_team(team_id).filter(run_id=run.id))
+ if run.scope == CohortBackfillScope.COHORT and len(participations) != 1:
+ # create_backfill_run_for_cohort gives a cohort-scoped run exactly one participation, but
+ # no DB constraint holds that. The terminal CAS below reads the invariant, so surface a
+ # violation loudly instead of silently miscounting the run.
+ logger.error(
+ "cohort_backfill_finalizer_cohort_scoped_run_participation_count",
+ run_id=str(run.id),
+ team_id=team_id,
+ participations=len(participations),
+ )
+ for participation in participations:
+ # INV-2: supersede trumps completion, so check it first.
+ if participation.superseded_at is not None:
+ superseded += 1
+ continue
+ if participation.stamped_at is not None:
+ stamped += 1
+ continue
+ if participation.reconcile_completed_at is not None:
+ if stamp_events_readiness(run, participation.cohort_id):
+ stamped += 1
+ invalidate_team = True
+ result.stamped_participations += 1
+ READINESS_STAMPS_COUNTER.labels(result="stamped").inc()
+ else:
+ # stamp_events_readiness superseded the participation (and, for a cohort-scoped
+ # run, possibly the run row itself) inside this transaction.
+ superseded += 1
+ READINESS_STAMPS_COUNTER.labels(result="superseded").inc()
+ continue
+
+ # No outcome despite reconcile_observed_at being set. An empty error means the seeder
+ # violated INV-1 (observed without an outcome); a non-empty error is a legitimate
+ # retryable shortfall that simply holds until re-dispatch.
+ held += 1
+ if participation.error == "":
+ logger.error(
+ "cohort_backfill_finalizer_participation_missing_outcome",
+ run_id=str(run.id),
+ cohort_id=participation.cohort_id,
+ team_id=team_id,
+ )
+
+ if held > 0:
+ logger.info(
+ "cohort_backfill_finalizer_run_held",
+ run_id=str(run.id),
+ team_id=team_id,
+ stamped=stamped,
+ superseded=superseded,
+ held=held,
+ )
+ result.held += 1
+ return invalidate_team
+
+ terminal_status = CohortBackfillRunStatus.COMPLETED if stamped >= 1 else CohortBackfillRunStatus.SUPERSEDED
+ transitioned = (
+ CohortBackfillRun.objects.for_team(team_id)
+ .filter(id=run.id, status=CohortBackfillRunStatus.RECONCILING)
+ .update(status=terminal_status, finished_at=Now())
+ )
+ if transitioned:
+ if terminal_status == CohortBackfillRunStatus.COMPLETED:
+ result.completed += 1
+ RUNS_FINALIZED_COUNTER.labels(status="completed").inc()
+ else:
+ result.superseded += 1
+ RUNS_FINALIZED_COUNTER.labels(status="superseded").inc()
+ else:
+ # We hold the run row's FOR UPDATE lock, so a missed CAS can only mean our own
+ # stamp_events_readiness call superseded a cohort-scoped run inside this transaction —
+ # the run is terminal (superseded + finished_at) and counted as such. That reads the
+ # one-participation invariant checked above: with more, a run that also stamped a cohort
+ # would land here and be counted purely superseded.
+ result.superseded += 1
+ RUNS_FINALIZED_COUNTER.labels(status="superseded").inc()
+
+ # Re-fire invalidation when completing a run whose stamps landed in an earlier pass, covering
+ # a crash between that pass's commit and its post-commit invalidation. (A crash after this
+ # terminal transition commits leaves any staleness bounded by the flags-cache verifier task
+ # and the behavioral-ids cache TTL, in the fail-closed direction.)
+ if terminal_status == CohortBackfillRunStatus.COMPLETED and stamped >= 1:
+ invalidate_team = True
+
+ return invalidate_team
diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.py
index d13c632e4222..124aa2fe1b22 100644
--- a/products/cohorts/backend/backfill/readiness.py
+++ b/products/cohorts/backend/backfill/readiness.py
@@ -51,8 +51,17 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
This update intentionally bypasses signals. B5 must explicitly invalidate feature-flag and
behavioral-cohort caches after a successful stamp.
+
+ Call inside a transaction: the cohort stamp and the participation CAS that ratifies it must
+ commit or roll back together.
"""
participation = CohortBackfillRunCohort.objects.for_team(run.team_id).get(run_id=run.id, cohort_id=cohort_id)
+ if participation.superseded_at is not None:
+ # A superseded participation is terminal. Refuse even when its pinned behavioral hash matches
+ # the cohort's current one again (A->B->A edit-revert): the events backfill it covered is gone.
+ logger.info("cohort_backfill_readiness_stamp_refused_superseded", run_id=str(run.id), cohort_id=cohort_id)
+ return False
+
updated = Cohort.objects.filter(
id=cohort_id,
team_id=run.team_id,
@@ -60,10 +69,23 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
last_backfill_events_at__isnull=True,
).update(last_backfill_events_at=Now())
if updated:
- CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(
- stamped_at=Now(), error=""
+ # ``superseded_at__isnull`` guards a supersession racing in after the up-front check; a
+ # 0-row stamp then means the participation lost the race, so refuse (finalizer treats it
+ # as superseded) rather than claim success.
+ stamped = (
+ CohortBackfillRunCohort.objects.for_team(run.team_id)
+ .filter(id=participation.id, superseded_at__isnull=True)
+ .update(stamped_at=Now(), error="")
)
- return True
+ if not stamped:
+ # The cohort stamp above is this transaction's own uncommitted write, so take it back:
+ # leaving it would open ``is_flag_compatible`` on a backfill that just lost the race.
+ Cohort.objects.filter(
+ id=cohort_id,
+ team_id=run.team_id,
+ behavioral_filters_shape_hash=participation.behavioral_filters_shape_hash,
+ ).update(last_backfill_events_at=None)
+ return bool(stamped)
current_readiness = (
Cohort.objects.filter(id=cohort_id, team_id=run.team_id)
@@ -75,15 +97,20 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
and current_readiness[0] == participation.behavioral_filters_shape_hash
and current_readiness[1] is not None
):
- CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(
- stamped_at=Now(), error=""
+ stamped = (
+ CohortBackfillRunCohort.objects.for_team(run.team_id)
+ .filter(id=participation.id, superseded_at__isnull=True)
+ .update(stamped_at=Now(), error="")
)
- return True
+ return bool(stamped)
error = "Cohort definition changed before readiness was stamped"
- CohortBackfillRunCohort.objects.for_team(run.team_id).filter(id=participation.id).update(
- superseded_at=Now(), error=error
- )
+ # ``superseded_at__isnull`` keeps an earlier supersession's timestamp and message rather than
+ # clobbering them with this later, less specific diagnosis (the Rust side COALESCEs for the
+ # same reason). Either way the participation ends up terminal, which is what INV-2 needs.
+ CohortBackfillRunCohort.objects.for_team(run.team_id).filter(
+ id=participation.id, superseded_at__isnull=True
+ ).update(superseded_at=Now(), error=error)
if run.scope == CohortBackfillScope.COHORT:
CohortBackfillRun.objects.for_team(run.team_id).filter(
id=run.id,
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.py
index 2cd704502e78..7d60df39ad8c 100644
--- a/products/cohorts/backend/backfill/runs.py
+++ b/products/cohorts/backend/backfill/runs.py
@@ -202,22 +202,32 @@ def supersede_active_runs(team_id: int, cohort_ids: Iterable[int]) -> int:
if not cohort_id_set:
return 0
+ error = "Cohort definition changed during backfill"
with transaction.atomic():
- participations = CohortBackfillRunCohort.objects.for_team(team_id).filter(
- cohort_id__in=cohort_id_set,
- superseded_at__isnull=True,
- run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
- )
- cohort_run_ids = list(
- participations.filter(run__scope=CohortBackfillScope.COHORT).values_list("run_id", flat=True)
- )
- participation_count = participations.update(
- superseded_at=Now(), error="Cohort definition changed during backfill"
+ # Resolve the targets first, then write run rows before participation rows. The finalizer
+ # locks in that order (run FOR UPDATE, then participations via stamp_events_readiness), so
+ # the opposite order here would deadlock the two on a cohort-scoped run.
+ targets = list(
+ CohortBackfillRunCohort.objects.for_team(team_id)
+ .filter(
+ cohort_id__in=cohort_id_set,
+ superseded_at__isnull=True,
+ run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ )
+ .values_list("id", "run_id", "run__scope")
)
+ if not targets:
+ 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,
finished_at=Now(),
- error="Cohort definition changed during backfill",
+ error=error,
)
- return participation_count
+ return (
+ CohortBackfillRunCohort.objects.for_team(team_id)
+ .filter(id__in=[participation_id for participation_id, _, _ in targets], superseded_at__isnull=True)
+ .update(superseded_at=Now(), error=error)
+ )
diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.py
new file mode 100644
index 000000000000..e0c5a25ee074
--- /dev/null
+++ b/products/cohorts/backend/backfill/test/test_finalize.py
@@ -0,0 +1,258 @@
+import importlib
+
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from django.core.cache import cache
+from django.db import connection
+from django.test import override_settings
+from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs
+
+from products.cohorts.backend.backfill.finalize import FLAGS_CACHE_TASK, finalize_backfill_runs
+from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.dependencies import _behavioral_cohort_ids_key
+
+
+@override_settings(
+ REALTIME_COHORT_TEAM_ALLOWLIST="all",
+ BEHAVIORAL_BACKFILL_FINALIZER_ENABLED=True,
+)
+class TestBackfillFinalizer(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)
+
+ celery_patch = mock.patch("products.cohorts.backend.backfill.finalize.current_app")
+ self.mock_celery_app = celery_patch.start()
+ self.addCleanup(celery_patch.stop)
+
+ def _behavioral_filters(self) -> dict:
+ return {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event_multiple",
+ "conditionHash": "same-condition-hash",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ }
+ }
+
+ def _make_participation(self, run: CohortBackfillRun, outcome: str) -> tuple[Cohort, CohortBackfillRunCohort]:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ cohort_type=CohortType.REALTIME,
+ filters=self._behavioral_filters(),
+ )
+ ensure_filters_shape_hash(cohort)
+ cohort.refresh_from_db()
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ cohort=cohort,
+ filters_shape_hash=cohort.filters_shape_hash or "",
+ behavioral_filters_shape_hash=cohort.behavioral_filters_shape_hash or "",
+ pinned_filters=cohort.filters,
+ )
+ # Simulate the Rust seeder's per-participation outcome writes (the columns are the interface).
+ now = timezone.now()
+ rows = CohortBackfillRunCohort.objects.for_team(self.team.id).filter(id=participation.id)
+ if outcome == "completed":
+ rows.update(reconcile_completed_at=now)
+ elif outcome == "superseded":
+ rows.update(superseded_at=now, error="missing partitions [3, 9]")
+ elif outcome == "superseded_and_completed":
+ rows.update(superseded_at=now, reconcile_completed_at=now, error="missing partitions [3, 9]")
+ elif outcome == "completed_then_diverged":
+ # Reconcile completed, then the cohort's behavioral definition changed: the stamp CAS
+ # must refuse and supersede instead of opening readiness on a stale backfill.
+ rows.update(reconcile_completed_at=now)
+ Cohort.objects.filter(id=cohort.id).update(behavioral_filters_shape_hash="diverged-after-reconcile")
+ elif outcome == "shortfall":
+ rows.update(error="markers short, retryable")
+ elif outcome == "missing_outcome":
+ pass # nothing written despite reconcile_observed_at — INV-1 violation
+ else:
+ raise ValueError(outcome)
+ return cohort, participation
+
+ def _make_run(
+ self, outcomes: list[str], *, observed: bool = True, scope: str = CohortBackfillScope.TEAM
+ ) -> tuple[CohortBackfillRun, list[Cohort]]:
+ cohort_scoped = scope == CohortBackfillScope.COHORT
+ run = CohortBackfillRun.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ backfill_kind=CohortBackfillKind.BEHAVIORAL,
+ trigger_kind=(
+ CohortBackfillTrigger.COHORT_CREATED if cohort_scoped else CohortBackfillTrigger.TEAM_ENABLEMENT
+ ),
+ scope=scope,
+ status=CohortBackfillRunStatus.RECONCILING,
+ reconcile_observed_at=timezone.now() if observed else None,
+ timezone="UTC",
+ )
+ cohorts = [self._make_participation(run, outcome)[0] for outcome in outcomes]
+ if cohort_scoped:
+ run.cohort = cohorts[0]
+ run.save(update_fields=["cohort"])
+ return run, cohorts
+
+ @parameterized.expand(
+ [
+ ("all_completed", ["completed", "completed"], CohortBackfillRunStatus.COMPLETED, [0, 1]),
+ ("completed_and_superseded", ["completed", "superseded"], CohortBackfillRunStatus.COMPLETED, [0]),
+ ("all_superseded", ["superseded", "superseded"], CohortBackfillRunStatus.SUPERSEDED, []),
+ ("superseded_trumps_completed", ["superseded_and_completed"], CohortBackfillRunStatus.SUPERSEDED, []),
+ ("shortfall_holds", ["shortfall"], CohortBackfillRunStatus.RECONCILING, []),
+ # No outcome at all despite reconcile_observed_at: an INV-1 violation must hold the run
+ # rather than terminalize it on incomplete information.
+ ("missing_outcome_holds", ["missing_outcome"], CohortBackfillRunStatus.RECONCILING, []),
+ ("mixed_held_still_stamps", ["completed", "shortfall"], CohortBackfillRunStatus.RECONCILING, [0]),
+ ]
+ )
+ def test_outcome_matrix(
+ self, _name: str, outcomes: list[str], expected_status: str, stamped_indices: list[int]
+ ) -> None:
+ run, cohorts = self._make_run(outcomes)
+
+ finalize_backfill_runs()
+
+ run.refresh_from_db()
+ self.assertEqual(run.status, expected_status)
+ for index, cohort in enumerate(cohorts):
+ cohort.refresh_from_db()
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run, cohort=cohort)
+ if index in stamped_indices:
+ self.assertIsNotNone(cohort.last_backfill_events_at)
+ self.assertIsNotNone(participation.stamped_at)
+ else:
+ self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(participation.stamped_at)
+
+ def test_unobserved_run_is_untouched(self) -> None:
+ run, cohorts = self._make_run(["completed"], observed=False)
+
+ result = finalize_backfill_runs()
+
+ run.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ self.assertEqual(result.runs_scanned, 0)
+ self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)
+ self.assertIsNone(cohorts[0].last_backfill_events_at)
+
+ def test_second_fire_is_a_noop(self) -> None:
+ run, _cohorts = self._make_run(["completed", "completed"])
+
+ first = finalize_backfill_runs()
+ second = finalize_backfill_runs()
+
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(first.completed, 1)
+ self.assertEqual(second.runs_scanned, 0)
+ self.assertEqual(second.completed, 0)
+ self.assertEqual(self.mock_celery_app.send_task.call_count, 1)
+
+ @override_settings(BEHAVIORAL_BACKFILL_FINALIZER_ENABLED=False)
+ def test_disabled_setting_does_not_touch_the_db(self) -> None:
+ run, cohorts = self._make_run(["completed"])
+
+ with CaptureQueriesContext(connection) as queries:
+ finalize_cohort_backfill_runs()
+
+ self.assertEqual(len(queries), 0)
+ run.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)
+ self.assertIsNone(cohorts[0].last_backfill_events_at)
+
+ def test_stamping_pass_invalidates_team_caches(self) -> None:
+ cache.set(_behavioral_cohort_ids_key(self.team.id, True), [1, 2, 3], 300)
+ cache.set(_behavioral_cohort_ids_key(self.team.id, False), [1, 2, 3], 300)
+ self._make_run(["completed"])
+
+ finalize_backfill_runs()
+
+ self.assertIsNone(cache.get(_behavioral_cohort_ids_key(self.team.id, True)))
+ self.assertIsNone(cache.get(_behavioral_cohort_ids_key(self.team.id, False)))
+ self.mock_celery_app.send_task.assert_called_once_with(
+ FLAGS_CACHE_TASK, args=(self.team.id,), queue="feature_flags"
+ )
+
+ def test_flags_cache_task_name_matches_the_registered_task(self) -> None:
+ # The dispatch is by name (a static import would create a product-dependency cycle), so pin
+ # the string against the task's registered name to catch a rename or move.
+ module_path, task_name = FLAGS_CACHE_TASK.rsplit(".", 1)
+ task = getattr(importlib.import_module(module_path), task_name)
+ self.assertEqual(task.name, FLAGS_CACHE_TASK)
+
+ def test_cohort_scoped_run_superseded_by_stamp_divergence(self) -> None:
+ # The cohort's definition diverged after reconcile completed: the stamp CAS must refuse,
+ # supersede the participation and (cohort scope) the run itself, and the finalizer must
+ # count the run superseded despite its own terminal CAS missing.
+ run, cohorts = self._make_run(["completed_then_diverged"], scope=CohortBackfillScope.COHORT)
+
+ result = finalize_backfill_runs()
+
+ run.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
+ self.assertIsNotNone(run.finished_at)
+ self.assertIsNotNone(participation.superseded_at)
+ self.assertIsNone(participation.stamped_at)
+ self.assertIsNone(cohorts[0].last_backfill_events_at)
+ self.assertEqual(result.superseded, 1)
+ self.assertEqual(result.completed, 0)
+ self.mock_celery_app.send_task.assert_not_called()
+
+ def test_cohort_scoped_run_with_a_second_participation_keeps_the_stamp(self) -> None:
+ # Only creation-time code gives a cohort-scoped run exactly one participation, and the
+ # terminal CAS reads that invariant. With two, the diverged one supersedes the run row
+ # mid-transaction so the CAS misses — the stamp that already landed must survive with its
+ # cache invalidation, and the violation must be logged rather than silently miscounted.
+ with mock.patch("products.cohorts.backend.backfill.finalize.logger") as mock_logger:
+ run, cohorts = self._make_run(["completed", "completed_then_diverged"], scope=CohortBackfillScope.COHORT)
+
+ result = finalize_backfill_runs()
+
+ run.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ cohorts[1].refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
+ self.assertIsNotNone(cohorts[0].last_backfill_events_at)
+ self.assertIsNone(cohorts[1].last_backfill_events_at)
+ self.assertEqual(result.superseded, 1)
+ self.assertEqual(result.stamped_participations, 1)
+ self.mock_celery_app.send_task.assert_called_once_with(
+ FLAGS_CACHE_TASK, args=(self.team.id,), queue="feature_flags"
+ )
+ self.assertEqual(
+ mock_logger.error.call_args[0][0], "cohort_backfill_finalizer_cohort_scoped_run_participation_count"
+ )
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index 7b09b9c0936c..e9f7c425d4bc 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -132,6 +132,57 @@ class TestBackfillReadiness(BaseTest):
self.assertIsNotNone(participation.stamped_at)
self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)
+ def test_superseded_participation_is_never_resurrected(self) -> None:
+ cohort, run = self._cohort_and_run()
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(id=participation.id).update(
+ superseded_at=timezone.now()
+ )
+
+ # A -> B -> A: edit the behavioral window away and back so the cohort's current hash matches
+ # the pinned one again. The up-front guard must still refuse the terminal participation.
+ cohort.filters = self._filters(30)
+ cohort.save(update_fields=["filters"])
+ cohort.filters = self._filters(7)
+ cohort.save(update_fields=["filters"])
+ cohort.refresh_from_db()
+ participation.refresh_from_db()
+ self.assertEqual(cohort.behavioral_filters_shape_hash, participation.behavioral_filters_shape_hash)
+
+ self.assertFalse(stamp_events_readiness(run, cohort.id))
+
+ cohort.refresh_from_db()
+ participation.refresh_from_db()
+ self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(participation.stamped_at)
+
+ def test_supersession_racing_the_stamp_rolls_the_cohort_back(self) -> None:
+ cohort, run = self._cohort_and_run()
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
+ superseded: list[bool] = []
+
+ def supersede_after_the_cohort_stamp(execute, sql, params, many, context):
+ result = execute(sql, params, many, context)
+ if not superseded and sql.startswith('UPDATE "posthog_cohort" '):
+ superseded.append(True)
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(id=participation.id).update(
+ superseded_at=timezone.now()
+ )
+ return result
+
+ # A supersession commits after the cohort stamp but before the participation CAS ratifies
+ # it. The stamp is this transaction's own write, so it has to be taken back.
+ with connection.execute_wrapper(supersede_after_the_cohort_stamp):
+ self.assertFalse(stamp_events_readiness(run, cohort.id))
+
+ cohort.refresh_from_db()
+ participation.refresh_from_db()
+ self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(participation.stamped_at)
+ # The rollback must leave the participation terminal — the finalizer reads superseded_at to
+ # decide the run's outcome, so clearing it here would make the run reconcile forever.
+ self.assertIsNotNone(participation.superseded_at)
+
def test_ensure_shape_hash_only_fills_null_column(self) -> None:
cohort, _ = self._cohort_and_run()
Cohort.objects.filter(id=cohort.id).update(
diff --git a/products/cohorts/backend/migrations/0006_cohort_backfill_completion.py b/products/cohorts/backend/migrations/0006_cohort_backfill_completion.py
new file mode 100644
index 000000000000..f855b9a055d3
--- /dev/null
+++ b/products/cohorts/backend/migrations/0006_cohort_backfill_completion.py
@@ -0,0 +1,50 @@
+# Generated by Django 5.2.14 on 2026-07-25 05:25
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("cohorts", "0005_cohort_condition_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="cohortbackfillrun",
+ name="chunks_planned_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillrun",
+ name="marker_watch",
+ field=models.JSONField(
+ blank=True,
+ help_text='Opaque watcher resume state written by the Rust seeder, shape {"schema":1,"positions":{...},"ends":{...}|null}. Django never interprets it.',
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillrun",
+ name="reconcile_dispatched_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillrun",
+ name="reconcile_observed_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillruncohort",
+ name="reconcile_completed_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="cohortbackfillruncohort",
+ name="reconcile_marker_bits",
+ field=models.BigIntegerField(
+ db_default=0,
+ default=0,
+ help_text="Bitmap of seed partitions whose reconcile_complete marker was observed, maintained as an i64 by the Rust seeder (bits |= 1 << partition; all 64 partitions full is -1). Django never interprets the bits.",
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/0007_cohortbackfillrun_cohort_bfr_reconciling_idx.py b/products/cohorts/backend/migrations/0007_cohortbackfillrun_cohort_bfr_reconciling_idx.py
new file mode 100644
index 000000000000..a3fe85ec0ab9
--- /dev/null
+++ b/products/cohorts/backend/migrations/0007_cohortbackfillrun_cohort_bfr_reconciling_idx.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY so the build takes no ACCESS EXCLUSIVE lock on cohort_backfill_runs.
+ # Concurrent builds can't run in a transaction, so this migration is non-atomic.
+ atomic = False
+
+ dependencies = [
+ ("cohorts", "0006_cohort_backfill_completion"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="cohortbackfillrun",
+ index=models.Index(
+ condition=models.Q(("status", "reconciling")),
+ fields=["backfill_kind", "reconcile_observed_at"],
+ name="cohort_bfr_reconciling_idx",
+ ),
+ ),
+ ]
diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txt
index e603134fd06f..88d30e14d573 100644
--- a/products/cohorts/backend/migrations/max_migration.txt
+++ b/products/cohorts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0005_cohort_condition_type
+0007_cohortbackfillrun_cohort_bfr_reconciling_idx
diff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.py
index 72fa79cc9804..c0c0560e7c43 100644
--- a/products/cohorts/backend/models/backfill.py
+++ b/products/cohorts/backend/models/backfill.py
@@ -70,6 +70,17 @@ class CohortBackfillRun(TeamScopedRootMixin, UUIDTModel):
pinned = models.JSONField(default=dict)
preconditions = models.JSONField(default=dict)
reconcile_hwms = models.JSONField(null=True, blank=True)
+ chunks_planned_at = models.DateTimeField(null=True, blank=True)
+ reconcile_dispatched_at = models.DateTimeField(null=True, blank=True)
+ reconcile_observed_at = models.DateTimeField(null=True, blank=True)
+ marker_watch = models.JSONField(
+ null=True,
+ blank=True,
+ help_text=(
+ "Opaque watcher resume state written by the Rust seeder, shape "
+ '{"schema":1,"positions":{...},"ends":{...}|null}. Django never interprets it.'
+ ),
+ )
blocked_reason = models.TextField(blank=True, default="")
error = models.TextField(blank=True, default="")
superseded_by = models.ForeignKey(
@@ -84,6 +95,14 @@ class CohortBackfillRun(TeamScopedRootMixin, UUIDTModel):
indexes = [
models.Index(fields=["team", "status"], name="cohort_bfr_team_status_idx"),
models.Index(fields=["team", "-created_at"], name="cohort_bfr_team_created_idx"),
+ # The finalizer discovers observed runs across all teams, so it can't use the
+ # team-prefixed indexes above. Partial on status keeps that scan proportional to the
+ # live run set instead of to the table's ever-growing terminal history.
+ models.Index(
+ fields=["backfill_kind", "reconcile_observed_at"],
+ condition=Q(status=CohortBackfillRunStatus.RECONCILING),
+ name="cohort_bfr_reconciling_idx",
+ ),
]
constraints = [
models.UniqueConstraint(
@@ -108,6 +127,16 @@ class CohortBackfillRunCohort(TeamScopedRootMixin, UUIDModel):
pinned_filters = models.JSONField()
stamped_at = models.DateTimeField(null=True, blank=True)
superseded_at = models.DateTimeField(null=True, blank=True)
+ reconcile_completed_at = models.DateTimeField(null=True, blank=True)
+ reconcile_marker_bits = models.BigIntegerField(
+ default=0,
+ db_default=0,
+ help_text=(
+ "Bitmap of seed partitions whose reconcile_complete marker was observed, maintained "
+ "as an i64 by the Rust seeder (bits |= 1 << partition; all 64 partitions full is -1). "
+ "Django never interprets the bits."
+ ),
+ )
error = models.TextField(blank=True, default="")
class Meta:
diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.py
index b8773e3a5aa1..43c373d93d05 100644
--- a/products/cohorts/backend/models/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -190,6 +190,11 @@ def _invalidate_team_behavioral_cohort_cache(team_id: int) -> None:
)
+# Public alias for callers outside the signal path (e.g. the backfill finalizer) that must
+# explicitly invalidate the behavioral-cohort cache after bypassing signals.
+invalidate_team_behavioral_cohort_cache = _invalidate_team_behavioral_cohort_cache
+
+
def extract_cohort_dependencies(cohort: Cohort) -> set[int]:
"""
Extract cohort dependencies from the given cohort.
diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.py
index 3d95fdbb4270..75a5f1fdcfbd 100644
--- a/products/feature_flags/backend/tasks.py
+++ b/products/feature_flags/backend/tasks.py
@@ -76,7 +76,13 @@ def sync_cross_region_flags_task() -> None:
sync_cross_region_flags()
-@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)
+# Pinned: products.cohorts dispatches this by name (a static import would close a product-dependency
+# cycle), so a module move must not silently rename the registration out from under that caller.
+@shared_task(
+ name="products.feature_flags.backend.tasks.update_team_service_flags_cache",
+ ignore_result=True,
+ queue=CeleryQueue.FEATURE_FLAGS.value,
+)
@skip_team_scope_audit
def update_team_service_flags_cache(team_id: int) -> None:
"""