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.

chore(cohorts): stop scheduling cohort calculation and save-triggered backfills (#76684)

Gustavo H. Strassburgerfab23bdd246a
diff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.py
index e60cb12fa1ed..ddae99504f64 100644
--- a/posthog/settings/schedules.py
+++ b/posthog/settings/schedules.py
@@ -57,6 +57,10 @@ CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON = get_from_env(
"0 5 1 */3 *",
)
+# Cohort selection for the Python realtime cohort calculation coordinator, which no longer has a
+# schedule (rust/cohort-stream-processor replaced it). These survive only because the coordinator
+# still parses them, and go away with the Python implementation. Unrelated to
+# REALTIME_COHORT_TEAM_ALLOWLIST, which is the live setting Rust and Django both read.
# Teams that should process all their cohorts (comma-separated team IDs)
# Example: "2,42" means team 2 and team 42 process all cohorts
REALTIME_COHORT_CALCULATION_TEAMS: set[int] = {
@@ -72,147 +76,3 @@ REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE: float = get_from_env(
0.0,
type_cast=float,
)
-
-# Realtime cohort calculation schedule intervals (in minutes) based on duration percentiles
-# Faster cohorts run more frequently, slower cohorts run less frequently
-REALTIME_COHORT_CALCULATION_P0_P50_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P0_P50_INTERVAL_MINUTES",
- 7,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P50_P80_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P50_P80_INTERVAL_MINUTES",
- 10,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P80_P90_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P80_P90_INTERVAL_MINUTES",
- 15,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P90_P95_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P90_P95_INTERVAL_MINUTES",
- 20,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P95_P99_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P95_P99_INTERVAL_MINUTES",
- 25,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P99_P100_INTERVAL_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P99_P100_INTERVAL_MINUTES",
- 45,
- type_cast=int,
-)
-
-# How often precalculated_events is reconciled against person_distinct_id_overrides to
-# repair rows made stale by person merges. Runs at the realtime calculation cadence so a
-# merge is reconciled by the next calculation run. Each run re-diffs every override from the
-# last RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS (6 by default) — there is no
-# watermark, so a wider window just reprocesses more already-handled merges. The window must stay
-# well above this interval and well below the overrides squash cadence
-# (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default) — the squash deletes override rows
-# after folding them into events, and reconciliation needs to see them before then.
-RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES: int = get_from_env(
- "RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES",
- 15,
- type_cast=int,
-)
-
-# Batch delay settings for different percentile ranges
-REALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P50_P80_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P50_P80_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P80_P90_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P80_P90_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P90_P95_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P90_P95_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P95_P99_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P95_P99_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P99_P100_BATCH_DELAY_MINUTES: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P99_P100_BATCH_DELAY_MINUTES",
- 1,
- type_cast=int,
-)
-
-# Parallelism settings for different percentile ranges
-REALTIME_COHORT_CALCULATION_P0_P50_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P0_P50_PARALLELISM",
- 12,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P50_P80_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P50_P80_PARALLELISM",
- 8,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P80_P90_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P80_P90_PARALLELISM",
- 4,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P90_P95_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P90_P95_PARALLELISM",
- 2,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P95_P99_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P95_P99_PARALLELISM",
- 16,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P99_P100_PARALLELISM: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P99_P100_PARALLELISM",
- 16,
- type_cast=int,
-)
-
-
-# Workflows per batch settings for different percentile ranges
-REALTIME_COHORT_CALCULATION_P0_P50_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P0_P50_WORKFLOWS_PER_BATCH",
- 6,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P50_P80_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P50_P80_WORKFLOWS_PER_BATCH",
- 4,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P80_P90_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P80_P90_WORKFLOWS_PER_BATCH",
- 2,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P90_P95_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P90_P95_WORKFLOWS_PER_BATCH",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P95_P99_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P95_P99_WORKFLOWS_PER_BATCH",
- 1,
- type_cast=int,
-)
-REALTIME_COHORT_CALCULATION_P99_P100_WORKFLOWS_PER_BATCH: int = get_from_env(
- "REALTIME_COHORT_CALCULATION_P99_P100_WORKFLOWS_PER_BATCH",
- 1,
- type_cast=int,
-)
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index 717ae9a381e6..e9a53a627b9f 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -23,7 +23,6 @@ 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
from products.cohorts.backend.models.util import (
@@ -840,82 +839,6 @@ def collect_cohort_query_stats(
raise
-@shared_task(ignore_result=True, max_retries=3)
-def trigger_cohort_backfill_task(team_id: int, cohort_id: int) -> None:
- """
- Trigger backfill for a realtime cohort with person properties.
- Uses the existing temporal workflow for consistency.
-
- TODO: Extract the core logic from backfill_precalculated_person_properties
- into a standalone function (e.g. posthog.cohorts.backfill.run_backfill)
- so this task, the management command, and the admin view can all call it
- directly instead of going through call_command/argparse.
- """
- from django.core.management import call_command
-
- logger = structlog.get_logger(__name__)
-
- try:
- logger.info(
- "triggering_cohort_backfill_task",
- cohort_id=cohort_id,
- team_id=team_id,
- )
-
- # Use the existing management command to trigger backfill
- call_command(
- "backfill_precalculated_person_properties",
- "--team-id",
- str(team_id),
- "--cohort-id",
- str(cohort_id),
- "--batch-size",
- 10_000,
- "--concurrent-workflows",
- 100,
- )
-
- except Exception as e:
- logger.exception(
- "failed_to_trigger_cohort_backfill_task",
- cohort_id=cohort_id,
- team_id=team_id,
- error=str(e),
- )
- raise
-
-
-@shared_task(ignore_result=True, max_retries=3)
-def trigger_cohort_events_backfill_task(team_id: int, cohort_id: int, trigger_kind: str) -> None:
- try:
- run = create_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)
- if run is None:
- logger.info(
- "skipping_cohort_events_backfill_task",
- cohort_id=cohort_id,
- team_id=team_id,
- trigger_kind=trigger_kind,
- )
- return
- logger.info(
- "created_cohort_events_backfill_run",
- run_id=str(run.id),
- cohort_id=cohort_id,
- team_id=team_id,
- trigger_kind=trigger_kind,
- status=run.status,
- )
- except Exception as error:
- logger.exception(
- "failed_to_trigger_cohort_events_backfill_task",
- cohort_id=cohort_id,
- team_id=team_id,
- trigger_kind=trigger_kind,
- error=str(error),
- )
- 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
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 56d7b8323003..ca48628d1ca7 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -18,8 +18,6 @@
'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_task',
- 'posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task',
'posthog.tasks.demo_create_data.create_data_for_demo_team',
'posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature',
'posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change',
diff --git a/posthog/temporal/messaging/constants.py b/posthog/temporal/messaging/constants.py
index 1bccf0eefc00..cefc38d9c13c 100644
--- a/posthog/temporal/messaging/constants.py
+++ b/posthog/temporal/messaging/constants.py
@@ -5,23 +5,8 @@
# backfilled check and the backfill writer can't drift apart.
BACKFILL_EVENT_SOURCE_PREFIX = "cohort_event_backfill"
-# Workflow IDs and patterns
-REALTIME_COHORT_CALCULATION_SCHEDULE_ID = "realtime-cohort-calculation-schedule"
-REALTIME_COHORT_CALCULATION_COORDINATOR_WORKFLOW_NAME = "realtime-cohort-calculation-coordinator"
CHILD_WORKFLOW_ID_SUFFIX = "child"
-# Reconciliation of precalculated_events rows made stale by person merges
-RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID = "reconcile-precalculated-data-schedule"
-RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME = "reconcile-precalculated-data"
-
-# Duration percentile-based schedule IDs
-REALTIME_COHORT_CALCULATION_P0_P50_SCHEDULE_ID = "realtime-cohort-calculation-p0-p50"
-REALTIME_COHORT_CALCULATION_P50_P80_SCHEDULE_ID = "realtime-cohort-calculation-p50-p80"
-REALTIME_COHORT_CALCULATION_P80_P90_SCHEDULE_ID = "realtime-cohort-calculation-p80-p90"
-REALTIME_COHORT_CALCULATION_P90_P95_SCHEDULE_ID = "realtime-cohort-calculation-p90-p95"
-REALTIME_COHORT_CALCULATION_P95_P99_SCHEDULE_ID = "realtime-cohort-calculation-p95-p99"
-REALTIME_COHORT_CALCULATION_P99_P100_SCHEDULE_ID = "realtime-cohort-calculation-p99-p100"
-
def get_child_workflow_id(parent_workflow_id: str, child_index: int) -> str:
"""Generate a standardized child workflow ID."""
diff --git a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py
index 98dc00dbf0dc..9ee55cbf0b51 100644
--- a/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py
+++ b/posthog/temporal/messaging/reconcile_precalculated_data_workflow.py
@@ -56,11 +56,10 @@ def _positive_int_env(name: str, default: int, logger: structlog.BoundLogger) ->
# Default overrides lookback window, env-overridable via
-# RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS. 6h is a conservative interim value sized
-# for steady-state run duration, not a hard bound: nothing caps how long a run takes, so a run
-# longer than the window can still strand a merge until the next full_scan (the planned per-run
-# watermark is the real guarantee). Lower it once per-run duration is reliably small. See the
-# block comment below for how the window relates to the schedule and squash cadence.
+# RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS. 6h was a conservative interim value sized
+# for steady-state run duration, never a hard bound: nothing caps how long a run takes, so a run
+# longer than the window can strand a merge until the next full_scan. Moot now that this workflow is
+# unscheduled and superseded. See the block comment below.
DEFAULT_OVERRIDES_LOOKBACK_HOURS = 6
@@ -76,20 +75,22 @@ DEFAULT_OVERRIDES_LOOKBACK_HOURS = 6
# row replaces the stale one. cohort_membership then self-heals on the next calculation run,
# whose FULL OUTER JOIN diff emits 'left' for the old person and 'entered' for the new one.
#
-# The override row written at merge time is the invalidation signal: each scheduled run
-# picks up distinct_ids whose override landed within the lookback window
+# The override row written at merge time is the invalidation signal: a run picks up distinct_ids
+# whose override landed within the lookback window
# (RECONCILE_PRECALCULATED_DATA_OVERRIDES_LOOKBACK_HOURS, default DEFAULT_OVERRIDES_LOOKBACK_HOURS)
-# and repairs just their rows, so the schedule can run at the realtime calculation cadence and a
-# merge is reconciled by the next calculation run instead of hours later. A `full_scan` input
-# ignores the window — use it for first-deploy remediation or after the workflow was down longer
-# than the lookback.
+# and repairs just their rows. A `full_scan` input ignores the window.
#
-# Timing constraints: the lookback must comfortably exceed the schedule interval (so no
-# merge falls between runs), and both must stay well inside the person-overrides squash
-# cadence (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default) — the squash folds
-# overrides into the events table and then DELETES the override rows, and
-# precalculated_events is not part of that squash, so any override this workflow never saw
-# becomes unrepairable except by an event backfill re-run.
+# Superseded and unscheduled. rust/cohort-stream-processor owns reconciliation now, in its
+# workers/reconcile.rs and sweep/reconcile.rs, against RocksDB state rather than by re-querying
+# ClickHouse. This workflow is retained only until the Python implementation is deleted, so the
+# lookback no longer bounds anything: with no cadence behind it, any override older than the window
+# is simply missed unless a run passes `full_scan`.
+#
+# If a one-off run is ever needed before this goes, note that a repair still has to land inside the
+# person-overrides squash cadence (SQUASH_PERSON_OVERRIDES_SCHEDULE, weekly by default). That squash
+# folds overrides into the events table and then DELETES the override rows, and precalculated_events
+# is not part of it, so an override this workflow never saw is unrepairable except by an event
+# backfill re-run.
# Latest surviving mapping per overridden distinct_id; mirrors the HogQL
# person_distinct_id_overrides lazy table (argmax_select with deleted_field="is_deleted").
diff --git a/posthog/temporal/messaging/schedule.py b/posthog/temporal/messaging/schedule.py
deleted file mode 100644
index 055fe9cd0261..000000000000
--- a/posthog/temporal/messaging/schedule.py
+++ /dev/null
@@ -1,275 +0,0 @@
-"""Schedule configuration for realtime cohort calculation coordinator."""
-
-from dataclasses import asdict
-from datetime import timedelta
-
-from django.conf import settings
-
-from temporalio.client import (
- Client,
- Schedule,
- ScheduleActionStartWorkflow,
- ScheduleIntervalSpec,
- ScheduleOverlapPolicy,
- SchedulePolicy,
- ScheduleSpec,
-)
-
-from posthog.settings.schedules import (
- REALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P0_P50_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P0_P50_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P0_P50_WORKFLOWS_PER_BATCH,
- REALTIME_COHORT_CALCULATION_P50_P80_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P50_P80_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P50_P80_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P50_P80_WORKFLOWS_PER_BATCH,
- REALTIME_COHORT_CALCULATION_P80_P90_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P80_P90_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P80_P90_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P80_P90_WORKFLOWS_PER_BATCH,
- REALTIME_COHORT_CALCULATION_P90_P95_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P90_P95_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P90_P95_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P90_P95_WORKFLOWS_PER_BATCH,
- REALTIME_COHORT_CALCULATION_P95_P99_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P95_P99_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P95_P99_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P95_P99_WORKFLOWS_PER_BATCH,
- REALTIME_COHORT_CALCULATION_P99_P100_BATCH_DELAY_MINUTES,
- REALTIME_COHORT_CALCULATION_P99_P100_INTERVAL_MINUTES,
- REALTIME_COHORT_CALCULATION_P99_P100_PARALLELISM,
- REALTIME_COHORT_CALCULATION_P99_P100_WORKFLOWS_PER_BATCH,
-)
-from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
-from posthog.temporal.messaging.constants import (
- REALTIME_COHORT_CALCULATION_COORDINATOR_WORKFLOW_NAME,
- REALTIME_COHORT_CALCULATION_P0_P50_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P50_P80_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P80_P90_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P90_P95_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P95_P99_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P99_P100_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_SCHEDULE_ID,
- RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID,
- RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME,
-)
-from posthog.temporal.messaging.realtime_cohort_calculation_workflow_coordinator import (
- RealtimeCohortCalculationCoordinatorWorkflowInputs,
-)
-from posthog.temporal.messaging.reconcile_precalculated_data_workflow import ReconcilePrecalculatedDataWorkflowInputs
-
-# Default configuration for realtime cohort calculation coordinator
-DEFAULT_COORDINATOR_PARALLELISM = 6
-DEFAULT_WORKFLOWS_PER_BATCH = 2
-DEFAULT_BATCH_DELAY_MINUTES = 5
-
-# Configuration is controlled via:
-# - REALTIME_COHORT_CALCULATION_TEAMS: comma-separated team IDs that should process all cohorts
-# - REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE: percentage (0.0-1.0) for teams not in the teams list
-
-# No execution timeout for coordinator - let children have their own timeouts
-COORDINATOR_EXECUTION_TIMEOUT_SECONDS: int | None = None
-
-
-async def create_realtime_cohort_calculation_p0_p50_schedule(client: Client):
- """Create or update schedule for p0-p50 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P0_P50_SCHEDULE_ID,
- duration_percentile_min=0.0,
- duration_percentile_max=50.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P0_P50_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P0_P50_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P0_P50_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P0_P50_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_p50_p80_schedule(client: Client):
- """Create or update schedule for p50-p80 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P50_P80_SCHEDULE_ID,
- duration_percentile_min=50.0,
- duration_percentile_max=80.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P50_P80_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P50_P80_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P50_P80_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P50_P80_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_p80_p90_schedule(client: Client):
- """Create or update schedule for p80-p90 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P80_P90_SCHEDULE_ID,
- duration_percentile_min=80.0,
- duration_percentile_max=90.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P80_P90_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P80_P90_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P80_P90_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P80_P90_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_p90_p95_schedule(client: Client):
- """Create or update schedule for p90-p95 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P90_P95_SCHEDULE_ID,
- duration_percentile_min=90.0,
- duration_percentile_max=95.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P90_P95_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P90_P95_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P90_P95_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P90_P95_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_p95_p99_schedule(client: Client):
- """Create or update schedule for p95-p99 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P95_P99_SCHEDULE_ID,
- duration_percentile_min=95.0,
- duration_percentile_max=99.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P95_P99_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P95_P99_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P95_P99_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P95_P99_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_p99_p100_schedule(client: Client):
- """Create or update schedule for p99-p100 cohorts."""
- await create_realtime_cohort_calculation_schedule_with_id(
- client=client,
- schedule_id=REALTIME_COHORT_CALCULATION_P99_P100_SCHEDULE_ID,
- duration_percentile_min=99.0,
- duration_percentile_max=100.0,
- interval_minutes=REALTIME_COHORT_CALCULATION_P99_P100_INTERVAL_MINUTES,
- parallelism=REALTIME_COHORT_CALCULATION_P99_P100_PARALLELISM,
- workflows_per_batch=REALTIME_COHORT_CALCULATION_P99_P100_WORKFLOWS_PER_BATCH,
- batch_delay_minutes=REALTIME_COHORT_CALCULATION_P99_P100_BATCH_DELAY_MINUTES,
- )
-
-
-async def create_realtime_cohort_calculation_schedule_with_id(
- client: Client,
- schedule_id: str,
- duration_percentile_min: float | None = None,
- duration_percentile_max: float | None = None,
- interval_minutes: int = 60,
- parallelism: int = DEFAULT_COORDINATOR_PARALLELISM,
- workflows_per_batch: int = DEFAULT_WORKFLOWS_PER_BATCH,
- batch_delay_minutes: int = DEFAULT_BATCH_DELAY_MINUTES,
-):
- """Create or update a schedule with a specific ID for duration percentile filtering."""
- from posthog.settings.schedules import (
- REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE,
- REALTIME_COHORT_CALCULATION_TEAMS,
- )
-
- realtime_cohort_calculation_schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- REALTIME_COHORT_CALCULATION_COORDINATOR_WORKFLOW_NAME,
- asdict(
- RealtimeCohortCalculationCoordinatorWorkflowInputs(
- parallelism=parallelism,
- workflows_per_batch=workflows_per_batch,
- batch_delay_minutes=batch_delay_minutes,
- duration_percentile_min=duration_percentile_min,
- duration_percentile_max=duration_percentile_max,
- team_ids=REALTIME_COHORT_CALCULATION_TEAMS.copy(),
- global_percentage=REALTIME_COHORT_CALCULATION_GLOBAL_PERCENTAGE,
- )
- ),
- id=schedule_id,
- task_queue=settings.MESSAGING_TASK_QUEUE,
- execution_timeout=timedelta(seconds=COORDINATOR_EXECUTION_TIMEOUT_SECONDS)
- if COORDINATOR_EXECUTION_TIMEOUT_SECONDS
- else None,
- ),
- spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(minutes=interval_minutes))]),
- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
- )
-
- if await a_schedule_exists(client, schedule_id):
- await a_update_schedule(client, schedule_id, realtime_cohort_calculation_schedule)
- else:
- await a_create_schedule(
- client,
- schedule_id,
- realtime_cohort_calculation_schedule,
- trigger_immediately=False,
- )
-
-
-async def create_reconcile_precalculated_data_schedule(client: Client):
- """Create or update the schedule that repairs precalculated_events rows after person merges."""
- from posthog.settings.schedules import RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES
-
- schedule = Schedule(
- action=ScheduleActionStartWorkflow(
- RECONCILE_PRECALCULATED_DATA_WORKFLOW_NAME,
- asdict(ReconcilePrecalculatedDataWorkflowInputs()),
- id=RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID,
- task_queue=settings.MESSAGING_TASK_QUEUE,
- ),
- spec=ScheduleSpec(
- intervals=[ScheduleIntervalSpec(every=timedelta(minutes=RECONCILE_PRECALCULATED_DATA_INTERVAL_MINUTES))]
- ),
- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
- )
-
- if await a_schedule_exists(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID):
- await a_update_schedule(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID, schedule)
- else:
- await a_create_schedule(client, RECONCILE_PRECALCULATED_DATA_SCHEDULE_ID, schedule, trigger_immediately=False)
-
-
-async def create_all_realtime_cohort_calculation_schedules(client: Client):
- """Create or update the active percentile-based schedules for realtime cohort calculation.
-
- Only the p0-p80 tiers (p0-p50, p50-p80) are active. The p80-p100 tiers (p80-p90, p90-p95,
- p95-p99, p99-p100) are intentionally disabled for now — they cover the slowest, most expensive
- cohorts — so their schedules are deleted here if they exist. Re-enabling is a matter of
- re-adding the create calls below and dropping the corresponding deletes; the per-tier
- create_* helpers, settings, and schedule-ID constants are kept in place for that.
-
- Note: This migration is non-atomic. Between creating new schedules and deleting the old one,
- both schedules may fire simultaneously. The old schedule processes ALL cohorts while the new
- percentile-based schedules also process cohorts, resulting in duplicate processing during deployment.
- This is acceptable as cohort calculation is idempotent, but may cause transient increased load.
- """
- from posthog.temporal.common.schedule import a_delete_schedule, a_schedule_exists
-
- # First ensure the active p0-p80 percentile-based schedules are in place
- await create_realtime_cohort_calculation_p0_p50_schedule(client)
- await create_realtime_cohort_calculation_p50_p80_schedule(client)
-
- # Delete the disabled p80-p100 tiers so any previously registered schedules stop firing
- for disabled_schedule_id in (
- REALTIME_COHORT_CALCULATION_P80_P90_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P90_P95_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P95_P99_SCHEDULE_ID,
- REALTIME_COHORT_CALCULATION_P99_P100_SCHEDULE_ID,
- ):
- if await a_schedule_exists(client, disabled_schedule_id):
- await a_delete_schedule(client, disabled_schedule_id)
-
- # Then clean up the legacy schedules if they exist to prevent duplicate runs
- if await a_schedule_exists(client, REALTIME_COHORT_CALCULATION_SCHEDULE_ID):
- await a_delete_schedule(client, REALTIME_COHORT_CALCULATION_SCHEDULE_ID)
-
- # Also clean up the old p0-p90 schedule that we're replacing with p0-p50, p50-p80, p80-p90
- old_p0_p90_schedule_id = "realtime-cohort-calculation-p0-p90"
- if await a_schedule_exists(client, old_p0_p90_schedule_id):
- await a_delete_schedule(client, old_p0_p90_schedule_id)
-
- # Clean up the old p95-p100 schedule that we're replacing with p95-p99, p99-p100
- old_p95_p100_schedule_id = "realtime-cohort-calculation-p95-p100"
- if await a_schedule_exists(client, old_p95_p100_schedule_id):
- await a_delete_schedule(client, old_p95_p100_schedule_id)
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 40c15ccdaf61..f87ad30d59ca 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -56,10 +56,6 @@ from posthog.temporal.health_checks.schedule import create_health_check_schedule
from posthog.temporal.ingestion_acceptance_test.schedule import create_ingestion_acceptance_test_schedule
from posthog.temporal.logs_alerting.schedule import create_logs_alert_check_schedule
from posthog.temporal.mcp_analytics.intent_clustering.schedule import create_intent_clustering_coordinator_schedule
-from posthog.temporal.messaging.schedule import (
- create_all_realtime_cohort_calculation_schedules,
- create_reconcile_precalculated_data_schedule,
-)
from posthog.temporal.product_analytics.upgrade_queries_workflow import UpgradeQueriesWorkflowInputs
from posthog.temporal.quota_limiting.run_quota_limiting import RunQuotaLimitingInputs
from posthog.temporal.salesforce_enrichment.conversations_slack_workflow import ConversationsSlackEnrichmentInputs
@@ -641,6 +637,34 @@ async def cleanup_legacy_session_summarization_schedules(client: Client):
await a_delete_schedule(client, schedule_id)
+async def cleanup_cohort_calculation_schedules(client: Client):
+ """Delete the realtime cohort calculation and precalculated-data reconcile schedules.
+
+ This ClickHouse-query-based path did not scale and was putting load on ClickHouse it could not
+ carry. rust/cohort-stream-processor replaces it with incremental evaluation off the event stream,
+ and owns reconciliation too (its workers/reconcile.rs and sweep/reconcile.rs), so nothing here
+ needs to run on a cadence any more.
+
+ The workflows stay registered on the messaging worker only until the Python implementation is
+ deleted. In-flight executions finish on their own; deleting a schedule doesn't cancel them.
+ """
+ legacy_schedule_ids = [
+ "realtime-cohort-calculation-p0-p50",
+ "realtime-cohort-calculation-p50-p80",
+ "realtime-cohort-calculation-p80-p90",
+ "realtime-cohort-calculation-p90-p95",
+ "realtime-cohort-calculation-p95-p99",
+ "realtime-cohort-calculation-p99-p100",
+ "realtime-cohort-calculation-p0-p90",
+ "realtime-cohort-calculation-p95-p100",
+ "realtime-cohort-calculation-schedule",
+ "reconcile-precalculated-data-schedule",
+ ]
+ for schedule_id in legacy_schedule_ids:
+ if await a_schedule_exists(client, schedule_id):
+ await a_delete_schedule(client, schedule_id)
+
+
async def create_run_usage_reports_schedule(client: Client):
"""Intraday usage report run every 30 minutes.
@@ -830,8 +854,7 @@ schedules = [
create_experiment_regular_metrics_schedules,
create_experiment_saved_metrics_schedules,
create_experiment_precompute_canary_schedule,
- create_all_realtime_cohort_calculation_schedules,
- create_reconcile_precalculated_data_schedule,
+ cleanup_cohort_calculation_schedules,
create_ingestion_acceptance_test_schedule,
create_warehouse_sources_queue_partition_management_schedule,
create_health_check_schedules,
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 60d7e2ebddf8..f852436b3d80 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -157,9 +157,8 @@ post_save:products.cdp.backend.models.plugin.plugin_attachement_reload_needed
post_save:products.cdp.backend.models.plugin.plugin_config_reload_needed
post_save:products.cdp.backend.models.plugin.plugin_reload_needed
post_save:products.cdp.backend.models.plugin.preinstall_plugins_for_new_organization
-post_save:products.cohorts.backend.models.dependencies.cohort_behavioral_shape_changed_backfill
+post_save:products.cohorts.backend.models.dependencies.cohort_behavioral_shape_changed_supersede
post_save:products.cohorts.backend.models.dependencies.cohort_changed
-post_save:products.cohorts.backend.models.dependencies.cohort_conditions_changed_backfill
post_save:products.conversations.backend.signals.emit_ticket_created_event
post_save:products.conversations.backend.signals.post_github_reply_on_team_message
post_save:products.conversations.backend.signals.post_slack_reply_on_team_message
@@ -229,7 +228,6 @@ pre_save:posthog.storage.team_access_cache_signal_handlers.personal_api_key_pre_
pre_save:posthog.storage.team_access_cache_signal_handlers.project_secret_api_key_pre_save
pre_save:posthog.storage.team_access_cache_signal_handlers.team_pre_save_auth_cache
pre_save:posthog.storage.team_llm_gateway_policy_signal_handlers._capture_old_state_if_deferred
-pre_save:products.cohorts.backend.models.dependencies.cohort_pre_save
pre_save:products.conversations.backend.signals.handle_comment_soft_delete
pre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policy
pre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name
diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.py
index 672a65d625f6..1864a04e3ad0 100644
--- a/products/cohorts/backend/backfill/test/test_finalize.py
+++ b/products/cohorts/backend/backfill/test/test_finalize.py
@@ -45,11 +45,6 @@ class TestFinalizerKindCoverage(SimpleTestCase):
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()
diff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.py
index af191767e572..f1147268e307 100644
--- a/products/cohorts/backend/backfill/test/test_management_command.py
+++ b/products/cohorts/backend/backfill/test/test_management_command.py
@@ -29,14 +29,6 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,
)
class TestCreateCohortBackfillRunCommand(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- feature_patch = mock.patch(
- "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False
- )
- feature_patch.start()
- self.addCleanup(feature_patch.stop)
-
def _cohort(self, event: str) -> Cohort:
return Cohort.objects.create(
team=self.team,
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index 1f9672a5d394..530405bd6979 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -1,5 +1,4 @@
from posthog.test.base import BaseTest
-from unittest import mock
from django.db import connection
from django.test import override_settings
@@ -50,14 +49,6 @@ KINDS = [
BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED=True,
)
class TestBackfillReadiness(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- feature_patch = mock.patch(
- "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False
- )
- feature_patch.start()
- self.addCleanup(feature_patch.stop)
-
def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:
values: list[dict] = [
{
diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.py
index 9e57e56a8c43..daaeaa8b7a5d 100644
--- a/products/cohorts/backend/backfill/test/test_runs.py
+++ b/products/cohorts/backend/backfill/test/test_runs.py
@@ -8,8 +8,6 @@ from django.test import override_settings
from parameterized import parameterized
-from posthog.tasks.calculate_cohort import trigger_cohort_events_backfill_task
-
from products.cohorts.backend.backfill.pinning import PersonPinningCapExceeded
from products.cohorts.backend.backfill.runs import (
create_backfill_run_for_cohort,
@@ -36,14 +34,6 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,
)
class TestBackfillRuns(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- feature_patch = mock.patch(
- "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False
- )
- feature_patch.start()
- self.addCleanup(feature_patch.stop)
-
def _filters(self, event: str = "$pageview", window_days: int = 7) -> dict:
return {
"properties": {
@@ -158,12 +148,20 @@ class TestBackfillRuns(BaseTest):
with self.assertRaisesMessage(ValueError, "Cohorts already have active backfill runs"):
create_team_backfill_run(self.team.id, "team_enablement")
- def test_celery_task_uses_explicit_team_scope(self) -> None:
+ def test_editing_the_cohort_supersedes_its_active_run(self) -> None:
+ # rust/cohort-seeder claims run rows and replays history from the filters the run pinned, so
+ # if the post_save receiver stops superseding, an edit leaves the seeder on a stale definition.
cohort = self._cohort()
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
- trigger_cohort_events_backfill_task.run(self.team.id, cohort.id, "cohort_created")
+ with self.captureOnCommitCallbacks(execute=True):
+ cohort.filters = self._filters("signup")
+ cohort.save()
- self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).filter(cohort=cohort).count(), 1)
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
+ self.assertIsNotNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
@override_settings(
@@ -175,15 +173,6 @@ class TestBackfillRuns(BaseTest):
BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET=1_000_000,
)
class TestPersonBackfillRuns(BaseTest):
- def setUp(self) -> None:
- super().setUp()
- feature_patch = mock.patch(
- "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled",
- return_value=False,
- )
- feature_patch.start()
- self.addCleanup(feature_patch.stop)
-
def _filters(
self,
*,
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 6600263ecd56..d63c6d3f0daf 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -314,7 +314,6 @@ 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 = False
maintained_update_fields = set(update_fields) if update_fields is not None else None
try:
if not self.team_id or not is_realtime_cohort_team(self.team_id):
@@ -380,10 +379,6 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
self._leaf_shape_changed = True
if person_shape_changed:
self.last_backfill_person_properties_at = None
- # Nothing reads this yet: the receiver that supersedes active person-property runs
- # on a person-leaf edit — the counterpart to `_leaf_shape_changed` in
- # dependencies.py — lands with the person-run trigger (B7.3b).
- self._person_shape_changed = True
if maintained_update_fields is None:
return None
diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.py
index f07907977f9f..d5b16525d47a 100644
--- a/products/cohorts/backend/models/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -5,27 +5,20 @@ from django.core.cache import cache
from django.db import transaction
from django.db.models import Q, TextField
from django.db.models.functions import Cast
-from django.db.models.signals import post_delete, post_save, pre_save
+from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
-import posthoganalytics
from prometheus_client import Counter
from rest_framework.exceptions import ValidationError
from structlog import get_logger
from 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, CohortType, is_cohort_recalculation_only_save
-from products.cohorts.backend.models.leaf_shape import walk_filter_leaves
-from products.cohorts.backend.realtime_teams import is_realtime_cohort_team
+from products.cohorts.backend.models.cohort import Cohort, is_cohort_recalculation_only_save
logger = get_logger(__name__)
DEPENDENCY_CACHE_TIMEOUT = 7 * 24 * 60 * 60 # 1 week
-COHORT_BACKFILL_DEBOUNCE_SECONDS = 300 # 5 minutes
-COHORT_BACKFILL_REDIS_TTL_SECONDS = 300 # matches countdown; task reads fresh state at execution time
-
# Prometheus metrics for cache hit/miss tracking
COHORT_DEPENDENCY_CACHE_COUNTER = Counter(
@@ -315,191 +308,6 @@ def _on_cohort_changed(cohort: Cohort, always_invalidate: bool = False):
warm_team_cohort_dependency_cache(cohort.team_id)
-def _has_person_property_filters(cohort: Cohort) -> bool:
- """
- Check if a cohort has person property filters in its filters.
- Used to determine if backfill should be triggered.
- """
- return bool(_extract_person_property_filters(cohort))
-
-
-def _has_behavioral_filters(cohort: Cohort) -> bool:
- properties = (cohort.filters or {}).get("properties")
- return any(leaf.get("type") == "behavioral" for leaf in walk_filter_leaves(properties))
-
-
-def _person_property_filters_changed(cohort: Cohort) -> bool:
- """
- Check if person property filters have changed by comparing current filters
- with the previous version stored in pre_save.
- """
- try:
- # For new cohorts, always trigger if they have person property filters
- if not cohort.pk:
- return True
-
- # Check if we have the previous state stored from pre_save
- previous_filters = getattr(cohort, "_previous_person_property_filters", None)
- if previous_filters is None:
- # No previous state available, assume changed to be safe
- return True
-
- # Extract current person property filters
- current_filters = _extract_person_property_filters(cohort)
-
- # Compare the filters - they changed if they're not equal
- return current_filters != previous_filters
-
- except Exception as e:
- logger.warning(
- "error_checking_person_property_filter_changes",
- cohort_id=cohort.pk,
- error=str(e),
- )
- # If we can't determine if they changed, assume they did to be safe
- return True
-
-
-def _extract_person_property_filters(cohort: Cohort) -> str:
- """
- Extract a normalized representation of person property filters from a cohort.
- Returns a hash string that can be used for comparison to detect changes.
- This captures both the individual conditions AND their logical structure.
- """
- import json
- import hashlib
-
- if not cohort.filters:
- return ""
-
- def normalize_filter_tree(node) -> dict | None:
- """Recursively traverse and normalize the filter tree structure."""
- if not isinstance(node, dict):
- return None
-
- node_type = node.get("type")
-
- # Check if this is a group node (AND/OR)
- if node_type in ("AND", "OR"):
- # Recursively process children and filter out None values
- children = []
- for child in node.get("values", []):
- normalized_child = normalize_filter_tree(child)
- if normalized_child is not None:
- children.append(normalized_child)
-
- if children:
- # Sort children by their JSON representation to make order-independent
- # For AND/OR operations, the order shouldn't matter logically
- children.sort(key=lambda x: json.dumps(x, sort_keys=True))
- return {"type": node_type, "children": children}
- return None
-
- # This is a leaf node - check if it's a person property filter
- if node_type == "person" and node.get("conditionHash") is not None:
- # Use conditionHash to represent the condition, preserving structure
- return {"type": "person", "conditionHash": node.get("conditionHash")}
-
- return None
-
- properties = cohort.filters.get("properties")
- if not properties:
- return ""
-
- normalized_tree = normalize_filter_tree(properties)
- if not normalized_tree:
- return ""
-
- # Convert to a stable JSON representation and hash it
- normalized_json = json.dumps(normalized_tree, sort_keys=True, separators=(",", ":"))
- return hashlib.sha256(normalized_json.encode()).hexdigest()
-
-
-def _trigger_cohort_backfill(cohort: Cohort) -> None:
- """
- Trigger backfill for a realtime cohort with person properties.
- Debounces with a 5-minute delay so rapid re-saves only trigger one backfill.
- """
- try:
- from posthog.tasks.calculate_cohort import trigger_cohort_backfill_task
-
- redis_client = get_redis_client()
- lock_key = f"cohort_backfill_pending:{cohort.pk}"
-
- # Atomic set-if-not-exists with TTL. Returns True only for the first
- # caller within the window; subsequent saves are debounced.
- if redis_client.set(lock_key, 1, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):
- logger.info(
- "triggering_cohort_backfill_on_conditions_change",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- cohort_type=cohort.cohort_type,
- debounce_seconds=COHORT_BACKFILL_DEBOUNCE_SECONDS,
- )
- try:
- trigger_cohort_backfill_task.apply_async(
- args=[cohort.team_id, cohort.pk],
- countdown=COHORT_BACKFILL_DEBOUNCE_SECONDS,
- )
- except Exception:
- # Release the lock so the next save can retry scheduling
- redis_client.delete(lock_key)
- raise
- else:
- logger.info(
- "cohort_backfill_already_pending",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- )
-
- except Exception as e:
- logger.exception(
- "failed_to_trigger_cohort_backfill",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- error=str(e),
- )
-
-
-def _trigger_cohort_events_backfill(cohort: Cohort, trigger_kind: str) -> None:
- try:
- from posthog.tasks.calculate_cohort import (
- trigger_cohort_events_backfill_task, # noqa: PLC0415 — avoids task import during model loading
- )
-
- redis_client = get_redis_client()
- lock_key = f"cohort_backfill_events_pending:{cohort.pk}"
- if redis_client.set(lock_key, 1, nx=True, ex=COHORT_BACKFILL_REDIS_TTL_SECONDS):
- logger.info(
- "triggering_cohort_events_backfill",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- trigger_kind=trigger_kind,
- debounce_seconds=COHORT_BACKFILL_DEBOUNCE_SECONDS,
- )
- try:
- trigger_cohort_events_backfill_task.apply_async(
- args=[cohort.team_id, cohort.pk, trigger_kind],
- countdown=COHORT_BACKFILL_DEBOUNCE_SECONDS,
- )
- except Exception:
- redis_client.delete(lock_key)
- raise
- else:
- logger.info(
- "cohort_events_backfill_already_pending",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- )
- except Exception as error:
- logger.exception(
- "failed_to_trigger_cohort_events_backfill",
- cohort_id=cohort.pk,
- team_id=cohort.team_id,
- error=str(error),
- )
-
-
def _supersede_cohort_events_backfills(cohort: Cohort) -> None:
try:
from products.cohorts.backend.backfill.runs import (
@@ -516,41 +324,6 @@ def _supersede_cohort_events_backfills(cohort: Cohort) -> None:
)
-@receiver(pre_save, sender=Cohort)
-def cohort_pre_save(sender, instance, **kwargs):
- """
- Capture the previous state of person property filters before save.
- This is needed to compare with the new state in post_save.
- """
- try:
- # Skip non-realtime cohorts to avoid extra DB queries
- if not instance.pk or instance.cohort_type != CohortType.REALTIME:
- instance._previous_person_property_filters = ""
- return
-
- # Check if filters field is being updated - if not, skip the expensive DB read
- update_fields = kwargs.get("update_fields")
- if update_fields is not None and "filters" not in update_fields:
- instance._previous_person_property_filters = ""
- return
-
- # Get the previous version from database
- previous_cohort = Cohort.objects.get(pk=instance.pk)
- # Store the previous person property filters hash on the instance
- instance._previous_person_property_filters = _extract_person_property_filters(previous_cohort)
- except Cohort.DoesNotExist:
- # Cohort doesn't exist yet (should not happen), treat as new
- instance._previous_person_property_filters = ""
- except Exception as e:
- logger.warning(
- "error_capturing_previous_person_property_filters",
- cohort_id=instance.pk,
- error=str(e),
- )
- # If we can't capture previous state, mark as None to be safe
- instance._previous_person_property_filters = None
-
-
@receiver(post_save, sender=Cohort)
def cohort_changed(sender, instance, **kwargs):
"""
@@ -564,101 +337,24 @@ def cohort_changed(sender, instance, **kwargs):
@receiver(post_save, sender=Cohort)
-def cohort_conditions_changed_backfill(sender, instance, **kwargs):
+def cohort_behavioral_shape_changed_supersede(sender, instance, **kwargs):
+ """Invalidate in-flight behavioral backfill runs when the cohort's behavioral leaf shape changes.
+
+ Part of the Django-to-Rust contract, not a leftover of the removed Python backfill trigger: a run
+ row pins the cohort's filters and shape hashes (see backfill/runs.py), and rust/cohort-seeder
+ claims those rows to replay history. An edit mid-run leaves the seeder working from a definition
+ that no longer exists, so the run has to be marked superseded. `is_realtime_cohort_team` explains
+ why the allowlist bounds this: Django's edit-time invalidation must cover exactly the teams Rust
+ maintains realtime membership for.
+
+ `_leaf_shape_changed` is only set for allowlisted realtime, non-static, non-deleted cohorts on a
+ real `filters` change, so it is the whole guard.
"""
- Trigger backfill when realtime cohort person property conditions change.
- This ensures that person property filters are properly backfilled
- when cohort filters are modified.
- """
- # Skip if this is only a recalculation update
- if is_cohort_recalculation_only_save(kwargs):
+ if not getattr(instance, "_leaf_shape_changed", False):
return
- # Skip if filters field is not being updated - matches pre_save logic
- update_fields = kwargs.get("update_fields")
- if update_fields is not None and "filters" not in update_fields:
- return
-
- # Skip if cohort is not realtime
- if instance.cohort_type != CohortType.REALTIME:
- return
-
- # Skip if cohort is static
- if instance.is_static:
- return
-
- # Skip if cohort is deleted
- if instance.deleted:
- return
-
- # Check if this is a new cohort (created=True) or an update
- is_new = kwargs.get("created", False)
-
- if is_new:
- # For new cohorts, only trigger if they have person property filters
- if not _has_person_property_filters(instance):
- return
- else:
- # For updates, only trigger if person property filters actually changed
- if not _person_property_filters_changed(instance):
- return
-
- # Check feature flag before triggering backfill
- if not posthoganalytics.feature_enabled(
- "cohort-backfill-on-change",
- str(instance.team_id),
- groups={"team": str(instance.team_id)},
- send_feature_flag_events=False,
- ):
- return
-
- # Use transaction.on_commit to ensure backfill runs after the current transaction
- transaction.on_commit(lambda: _trigger_cohort_backfill(instance))
-
-
-@receiver(post_save, sender=Cohort)
-def cohort_behavioral_shape_changed_backfill(sender, instance, **kwargs):
- try:
- if is_cohort_recalculation_only_save(kwargs):
- return
-
- update_fields = kwargs.get("update_fields")
- if update_fields is not None and "filters" not in update_fields:
- return
- if not is_realtime_cohort_team(instance.team_id):
- return
- if instance.cohort_type != CohortType.REALTIME or instance.is_static or instance.deleted:
- return
- if not _has_behavioral_filters(instance):
- return
-
- created = kwargs.get("created", False)
- if not created and not getattr(instance, "_leaf_shape_changed", False):
- return
-
- if created:
- trigger_kind = "cohort_created"
- else:
- trigger_kind = "cohort_edited"
- COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed").inc()
- transaction.on_commit(lambda: _supersede_cohort_events_backfills(instance))
-
- if not posthoganalytics.feature_enabled(
- "behavioral-cohort-backfill-runs",
- str(instance.team_id),
- groups={"team": str(instance.team_id)},
- send_feature_flag_events=False,
- ):
- return
-
- transaction.on_commit(lambda: _trigger_cohort_events_backfill(instance, trigger_kind))
- except Exception as error:
- logger.exception(
- "failed_to_handle_cohort_behavioral_shape_change",
- cohort_id=instance.pk,
- team_id=instance.team_id,
- error=str(error),
- )
+ COHORT_REALTIME_STATE_ORPHANED_COUNTER.labels(reason="leaf_state_key_changed").inc()
+ transaction.on_commit(lambda: _supersede_cohort_events_backfills(instance))
@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.py
index 81a0b0ebfdd1..d8da2bfa3209 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -17,12 +17,6 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.on_commit = on_commit_patch.start()
self.addCleanup(on_commit_patch.stop)
- feature_patch = mock.patch(
- "products.cohorts.backend.models.dependencies.posthoganalytics.feature_enabled", return_value=False
- )
- self.feature_enabled = feature_patch.start()
- self.addCleanup(feature_patch.stop)
-
def _filters(self, window_days: int, *, person_hash: str | None = None) -> dict:
values = [
{
@@ -127,17 +121,16 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertEqual(cohort.filters_shape_hash, old_hash)
self.assertEqual(cohort.last_backfill_events_at, ready_at)
- def test_flag_off_still_nulls_readiness_without_enqueue(self) -> None:
+ def test_behavioral_edit_nulls_events_readiness(self) -> None:
cohort = self._cohort(7)
Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())
cohort.refresh_from_db()
- with mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue:
- cohort.filters = self._filters(30)
- cohort.save()
+
+ cohort.filters = self._filters(30)
+ cohort.save()
cohort.refresh_from_db()
self.assertIsNone(cohort.last_backfill_events_at)
- enqueue.assert_not_called()
def test_person_only_edit_preserves_events_readiness(self) -> None:
cohort = self._cohort(7, person_hash="person-a")
@@ -151,19 +144,9 @@ class TestBehavioralBackfillDependencies(BaseTest):
)
cohort.refresh_from_db()
before = self._orphan_count()
- self.feature_enabled.return_value = True
- redis = mock.Mock()
- redis.set.return_value = True
-
- with (
- mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
- mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task.apply_async") as person_enqueue,
- mock.patch(
- "posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async"
- ) as event_enqueue,
- ):
- cohort.filters = self._filters(7, person_hash="person-b")
- cohort.save(update_fields=["filters"])
+
+ cohort.filters = self._filters(7, person_hash="person-b")
+ cohort.save(update_fields=["filters"])
cohort.refresh_from_db()
self.assertNotEqual(cohort.filters_shape_hash, old_hash)
@@ -172,8 +155,6 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertEqual(cohort.last_backfill_events_at, ready_at)
self.assertIsNone(cohort.last_backfill_person_properties_at)
self.assertEqual(self._orphan_count(), before)
- person_enqueue.assert_called_once()
- event_enqueue.assert_not_called()
def test_first_legacy_save_initializes_hashes_without_invalidating_readiness(self) -> None:
cohort = self._cohort(7)
@@ -186,11 +167,9 @@ class TestBehavioralBackfillDependencies(BaseTest):
)
cohort.refresh_from_db()
before = self._orphan_count()
- self.feature_enabled.return_value = True
- with mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue:
- cohort.name = "renamed"
- cohort.save()
+ cohort.name = "renamed"
+ cohort.save()
cohort.refresh_from_db()
self.assertIsNotNone(cohort.filters_shape_hash)
@@ -198,7 +177,6 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertIsNotNone(cohort.person_filters_shape_hash)
self.assertEqual(cohort.last_backfill_events_at, ready_at)
self.assertEqual(self._orphan_count(), before)
- enqueue.assert_not_called()
def test_first_legacy_behavioral_edit_invalidates_readiness(self) -> None:
cohort = self._cohort(7)
@@ -236,79 +214,9 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertEqual(cohort.last_backfill_events_at, ready_at)
self.assertEqual(self._orphan_count(), before)
- def test_two_edits_share_the_events_debounce_key(self) -> None:
- cohort = self._cohort(7)
- self.feature_enabled.return_value = True
- redis = mock.Mock()
- redis.set.side_effect = [True, False]
- with (
- mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
- mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue,
- ):
- cohort.filters = self._filters(14)
- cohort.save()
- cohort.filters = self._filters(30)
- cohort.save()
-
- enqueue.assert_called_once_with(
- args=[self.team.id, cohort.id, "cohort_edited"],
- countdown=300,
- )
-
- def test_person_and_behavioral_changes_enqueue_separate_tasks(self) -> None:
- cohort = self._cohort(7, person_hash="person-a")
- self.feature_enabled.return_value = True
- redis = mock.Mock()
- redis.set.return_value = True
- with (
- mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
- mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task.apply_async") as person_enqueue,
- mock.patch(
- "posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async"
- ) as event_enqueue,
- ):
- cohort.filters = self._filters(30, person_hash="person-b")
- cohort.save()
-
- person_enqueue.assert_called_once()
- event_enqueue.assert_called_once()
- self.assertEqual(
- {call.args[0] for call in redis.set.call_args_list},
- {f"cohort_backfill_pending:{cohort.id}", f"cohort_backfill_events_pending:{cohort.id}"},
- )
-
- def test_create_path_enqueues_behavioral_backfill(self) -> None:
- self.feature_enabled.return_value = True
- redis = mock.Mock()
- redis.set.return_value = True
- with (
- mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
- mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_events_backfill_task.apply_async") as enqueue,
- ):
- cohort = self._cohort(7)
-
- enqueue.assert_called_once_with(
- args=[self.team.id, cohort.id, "cohort_created"],
- countdown=300,
- )
-
- def test_receiver_failure_does_not_break_save(self) -> None:
- cohort = self._cohort(7)
-
- with mock.patch(
- "products.cohorts.backend.models.dependencies._has_behavioral_filters",
- side_effect=RuntimeError("broken detector"),
- ):
- cohort.filters = self._filters(30)
- cohort.save()
-
- cohort.refresh_from_db()
- self.assertIsNone(cohort.last_backfill_events_at)
-
def test_hashing_failure_in_maintain_shape_does_not_break_save(self) -> None:
# _maintain_filter_shape_hashes swallows hashing errors so a hashing bug can't take down every
- # realtime cohort save. The receiver-guard test above patches a different try/except in the
- # signal path; this one exercises the save-path guard directly by making the hash raise.
+ # realtime cohort save. This exercises that guard directly by making the hash raise.
cohort = self._cohort(7)
ready_at = timezone.now()
Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=ready_at)
diff --git a/products/cohorts/backend/models/test/test_dependencies.py b/products/cohorts/backend/models/test/test_dependencies.py
index b317c02c94e3..72bc880e26f0 100644
--- a/products/cohorts/backend/models/test/test_dependencies.py
+++ b/products/cohorts/backend/models/test/test_dependencies.py
@@ -9,14 +9,9 @@ from rest_framework.exceptions import ValidationError
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.dependencies import (
- COHORT_BACKFILL_DEBOUNCE_SECONDS,
COHORT_DEPENDENCY_CACHE_COUNTER,
DEPENDENCY_CACHE_TIMEOUT,
_behavioral_cohort_ids_key,
- _extract_person_property_filters,
- _has_person_property_filters,
- _person_property_filters_changed,
- _trigger_cohort_backfill,
extract_cohort_dependencies,
get_cohort_dependencies,
get_cohort_dependents,
@@ -438,814 +433,6 @@ class TestCohortDependencies(BaseTest):
self.assertEqual(final_invalid, initial_invalid + 1)
-class TestCohortBackfillOnConditionsChanged(BaseTest):
- def _create_cohort(self, name: str, **kwargs):
- return Cohort.objects.create(name=name, team=self.team, **kwargs)
-
- @fixture(autouse=True)
- def mock_transaction(self):
- with mock.patch("django.db.transaction.on_commit", side_effect=lambda func: func()):
- yield
-
- def test_has_person_property_filters_with_person_properties(self):
- """Test that _has_person_property_filters correctly detects person property filters"""
- cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- self.assertTrue(_has_person_property_filters(cohort))
-
- def test_has_person_property_filters_without_required_fields(self):
- """Test that _has_person_property_filters returns False when required fields are missing"""
- cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- # Missing conditionHash and bytecode
- }
- ],
- }
- ],
- }
- },
- )
-
- self.assertFalse(_has_person_property_filters(cohort))
-
- def test_has_person_property_filters_with_behavioral_only(self):
- """Test that _has_person_property_filters returns False for behavioral filters only"""
- cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "pageview",
- "type": "behavioral",
- "value": "performed_event",
- "event_type": "events",
- }
- ],
- }
- ],
- }
- },
- )
-
- self.assertFalse(_has_person_property_filters(cohort))
-
- def test_has_person_property_filters_no_filters(self):
- """Test that _has_person_property_filters returns False for cohorts without filters"""
- cohort = self._create_cohort(name="Test Cohort")
- self.assertFalse(_has_person_property_filters(cohort))
-
- @parameterized.expand(
- [
- ("schedules_task_when_key_absent", True, True),
- ("debounces_when_key_present", False, False),
- ]
- )
- @mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")
- @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")
- def test_trigger_cohort_backfill_redis_set(
- self, _name, redis_set_result, should_schedule, mock_get_redis, mock_task
- ):
- mock_redis = mock.MagicMock()
- mock_redis.set.return_value = redis_set_result
- mock_get_redis.return_value = mock_redis
- cohort = self._create_cohort(name="Test Cohort", cohort_type=CohortType.REALTIME)
-
- _trigger_cohort_backfill(cohort)
-
- if should_schedule:
- mock_task.apply_async.assert_called_once_with(
- args=[cohort.team_id, cohort.pk], countdown=COHORT_BACKFILL_DEBOUNCE_SECONDS
- )
- else:
- mock_task.apply_async.assert_not_called()
-
- @mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")
- @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")
- def test_trigger_cohort_backfill_handles_task_exception(self, mock_get_redis, mock_task):
- mock_redis = mock.MagicMock()
- mock_redis.set.return_value = True
- mock_get_redis.return_value = mock_redis
- mock_task.apply_async.side_effect = Exception("Task failed")
- cohort = self._create_cohort(name="Test Cohort", cohort_type=CohortType.REALTIME)
-
- # Should not raise
- _trigger_cohort_backfill(cohort)
-
- # Redis key should be cleaned up so the next save can retry
- mock_redis.delete.assert_called_once_with(f"cohort_backfill_pending:{cohort.pk}")
-
- @mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_task")
- @mock.patch("products.cohorts.backend.models.dependencies.get_redis_client")
- def test_trigger_cohort_backfill_handles_redis_failure(self, mock_get_redis, mock_task):
- mock_get_redis.side_effect = Exception("Redis unavailable")
- cohort = self._create_cohort(name="Test Cohort", cohort_type=CohortType.REALTIME)
-
- # Should not raise
- _trigger_cohort_backfill(cohort)
- mock_task.apply_async.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch("posthoganalytics.feature_enabled", return_value=True)
- def test_backfill_signal_triggered_for_realtime_cohorts(self, mock_feature_enabled, mock_trigger_backfill):
- """Test that backfill is triggered when a realtime cohort with person properties is saved"""
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Reset mock after creation (since creation also triggers the signal)
- mock_trigger_backfill.reset_mock()
-
- # Update the cohort filters to trigger the signal again
- cohort.filters = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "name",
- "type": "person",
- "value": ["test user"],
- "operator": "exact",
- "conditionHash": "xyz789",
- "bytecode": [4, 5, 6],
- }
- ],
- }
- ],
- }
- }
- cohort.save()
-
- mock_trigger_backfill.assert_called_once_with(cohort)
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch("posthoganalytics.feature_enabled", return_value=True) # Flag enabled, but cohort type prevents trigger
- def test_backfill_signal_not_triggered_for_non_realtime_cohorts(self, mock_feature_enabled, mock_trigger_backfill):
- """Test that backfill is not triggered for non-realtime cohorts"""
- cohort = self._create_cohort(
- name="Test Cohort",
- # cohort_type is None (not realtime)
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Update the cohort to trigger the signal
- cohort.name = "Updated Test Cohort"
- cohort.save()
-
- mock_trigger_backfill.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch(
- "posthoganalytics.feature_enabled", return_value=True
- ) # Flag enabled, but static cohort prevents trigger
- def test_backfill_signal_not_triggered_for_static_cohorts(self, mock_feature_enabled, mock_trigger_backfill):
- """Test that backfill is not triggered for static cohorts"""
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- is_static=True,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Update the cohort to trigger the signal
- cohort.name = "Updated Test Cohort"
- cohort.save()
-
- mock_trigger_backfill.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch(
- "posthoganalytics.feature_enabled", return_value=True
- ) # Flag enabled, but no person properties prevents trigger
- def test_backfill_signal_not_triggered_without_person_properties(self, mock_feature_enabled, mock_trigger_backfill):
- """Test that backfill is not triggered for cohorts without person properties"""
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "pageview",
- "type": "behavioral",
- "value": "performed_event",
- "event_type": "events",
- }
- ],
- }
- ],
- }
- },
- )
-
- # Update the cohort to trigger the signal
- cohort.name = "Updated Test Cohort"
- cohort.save()
-
- mock_trigger_backfill.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch(
- "posthoganalytics.feature_enabled", return_value=True
- ) # Flag enabled, but recalculation save prevents trigger
- def test_backfill_signal_not_triggered_for_recalculation_saves(self, mock_feature_enabled, mock_trigger_backfill):
- """Test that backfill is not triggered for recalculation-only saves"""
- # Create cohort first (this will trigger the signal once)
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Reset mock after creation
- mock_trigger_backfill.reset_mock()
-
- # Save only recalculation fields to simulate recalculation-only update
- cohort.save(update_fields=["is_calculating", "last_calculation", "count"])
-
- mock_trigger_backfill.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch("posthoganalytics.feature_enabled", return_value=False)
- def test_backfill_signal_not_triggered_when_feature_flag_disabled(
- self, mock_feature_enabled, mock_trigger_backfill
- ):
- """Test that backfill is not triggered when the feature flag is disabled"""
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Reset mock after creation (since creation also triggers the signal)
- mock_trigger_backfill.reset_mock()
- mock_feature_enabled.reset_mock()
-
- # Update the cohort filters to trigger the signal again
- cohort.filters = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "name",
- "type": "person",
- "value": ["test user"],
- "operator": "exact",
- "conditionHash": "xyz789",
- "bytecode": [4, 5, 6],
- }
- ],
- }
- ],
- }
- }
- cohort.save()
-
- # Verify the feature flag was checked
- mock_feature_enabled.assert_called_once_with(
- "cohort-backfill-on-change",
- str(cohort.team_id),
- groups={"team": str(cohort.team_id)},
- send_feature_flag_events=False,
- )
- # Verify backfill was not triggered due to disabled feature flag
- mock_trigger_backfill.assert_not_called()
-
- @mock.patch("products.cohorts.backend.models.dependencies._trigger_cohort_backfill")
- @mock.patch("posthoganalytics.feature_enabled", return_value=True)
- def test_backfill_signal_not_triggered_when_person_properties_unchanged(
- self, mock_feature_enabled, mock_trigger_backfill
- ):
- """Test that backfill is not triggered when person property filters haven't changed"""
- cohort = self._create_cohort(
- name="Test Cohort",
- cohort_type=CohortType.REALTIME,
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- ],
- }
- },
- )
-
- # Reset mock after creation (since creation also triggers the signal)
- mock_trigger_backfill.reset_mock()
- mock_feature_enabled.reset_mock()
-
- # Update the cohort name but not the filters - should not trigger backfill
- cohort.name = "Updated Test Cohort"
- cohort.save()
-
- # Feature flag should not be checked since person properties didn't change
- mock_feature_enabled.assert_not_called()
- # Verify backfill was not triggered
- mock_trigger_backfill.assert_not_called()
-
- def test_extract_person_property_filters(self):
- """Test that _extract_person_property_filters correctly extracts and normalizes filters"""
- cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- },
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gt",
- "conditionHash": "def456",
- "bytecode": [4, 5, 6],
- },
- ],
- }
- ],
- }
- },
- )
-
- filters_hash = _extract_person_property_filters(cohort)
-
- # Should return a non-empty hash string for filters with person properties
- self.assertIsInstance(filters_hash, str)
- self.assertTrue(len(filters_hash) > 0)
-
- def test_extract_person_property_filters_empty(self):
- """Test that _extract_person_property_filters returns empty string for no filters"""
- cohort = self._create_cohort(name="Test Cohort", filters={})
- filters_hash = _extract_person_property_filters(cohort)
- self.assertEqual(filters_hash, "")
-
- def test_extract_person_property_filters_behavioral_only(self):
- """Test that _extract_person_property_filters ignores behavioral filters"""
- cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "OR",
- "values": [
- {
- "key": "$pageview",
- "type": "event",
- "value": ["performed_event"],
- "operator": "exact",
- }
- ],
- }
- },
- )
-
- filters_hash = _extract_person_property_filters(cohort)
- self.assertEqual(filters_hash, "")
-
- def test_extract_person_property_filters_order_independence(self):
- """Test that _extract_person_property_filters produces same hash regardless of child order"""
- # Create two cohorts with same conditions but different order
- cohort_order_1 = self._create_cohort(
- name="Test Cohort Order 1",
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "condition_1",
- "bytecode": [1, 2, 3],
- },
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gte",
- "conditionHash": "condition_2",
- "bytecode": [4, 5, 6],
- },
- ],
- }
- },
- )
-
- cohort_order_2 = self._create_cohort(
- name="Test Cohort Order 2",
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gte",
- "conditionHash": "condition_2",
- "bytecode": [4, 5, 6],
- },
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "condition_1",
- "bytecode": [1, 2, 3],
- },
- ],
- }
- },
- )
-
- hash_1 = _extract_person_property_filters(cohort_order_1)
- hash_2 = _extract_person_property_filters(cohort_order_2)
-
- # Both hashes should be identical despite different child order
- self.assertEqual(hash_1, hash_2)
- # And both should be non-empty since they have person property filters
- self.assertTrue(len(hash_1) > 0)
-
- def test_person_property_filters_changed_new_cohort(self):
- """Test that _person_property_filters_changed returns True for new cohorts"""
- cohort = self._create_cohort(name="Test Cohort")
- cohort.pk = None # Simulate new cohort
-
- result = _person_property_filters_changed(cohort)
- self.assertTrue(result)
-
- def test_person_property_filters_changed_filters_changed(self):
- """Test that _person_property_filters_changed detects changes"""
- # Create original cohort with one filter
- original_cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- },
- )
-
- # Create modified cohort with different filters
- modified_cohort = self._create_cohort(
- name="Test Cohort",
- filters={
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gt",
- "conditionHash": "def456",
- "bytecode": [4, 5, 6],
- }
- ],
- }
- },
- )
-
- # Simulate pre_save capturing the original state hash
- original_hash = _extract_person_property_filters(original_cohort)
- modified_cohort._previous_person_property_filters = original_hash
-
- result = _person_property_filters_changed(modified_cohort)
- self.assertTrue(result)
-
- def test_person_property_filters_changed_no_change(self):
- """Test that _person_property_filters_changed returns False when filters haven't changed"""
- # Create cohorts with identical filters
- filters = {
- "properties": {
- "type": "AND",
- "values": [
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "abc123",
- "bytecode": [1, 2, 3],
- }
- ],
- }
- }
-
- cohort = self._create_cohort(name="Test Cohort", filters=filters)
-
- # Simulate pre_save capturing the same state hash
- current_hash = _extract_person_property_filters(cohort)
- cohort._previous_person_property_filters = current_hash
-
- result = _person_property_filters_changed(cohort)
- self.assertFalse(result)
-
- def test_person_property_filters_changed_structural_change(self):
- """Test that _person_property_filters_changed detects structural changes even with same conditions"""
- # Original: (A AND B) OR C
- original_filters = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "type": "AND",
- "values": [
- {
- "key": "name",
- "type": "person",
- "value": ["Alice"],
- "operator": "exact",
- "conditionHash": "hashA",
- "bytecode": [1, 2, 3],
- },
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gt",
- "conditionHash": "hashB",
- "bytecode": [4, 5, 6],
- },
- ],
- },
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "hashC",
- "bytecode": [7, 8, 9],
- },
- ],
- }
- }
-
- # Modified: A OR B OR C (same conditions, different structure)
- modified_filters = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "key": "name",
- "type": "person",
- "value": ["Alice"],
- "operator": "exact",
- "conditionHash": "hashA",
- "bytecode": [1, 2, 3],
- },
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gt",
- "conditionHash": "hashB",
- "bytecode": [4, 5, 6],
- },
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "hashC",
- "bytecode": [7, 8, 9],
- },
- ],
- }
- }
-
- original_cohort = self._create_cohort(name="Test Cohort", filters=original_filters)
- modified_cohort = self._create_cohort(name="Test Cohort", filters=modified_filters)
-
- # Simulate pre_save capturing the original structure hash
- original_hash = _extract_person_property_filters(original_cohort)
- modified_cohort._previous_person_property_filters = original_hash
-
- result = _person_property_filters_changed(modified_cohort)
- self.assertTrue(result)
-
- def test_person_property_filters_changed_identical_structure(self):
- """Test that _person_property_filters_changed returns False for identical structure"""
- # Both: A OR B OR C (identical structure and conditions)
- filters = {
- "properties": {
- "type": "OR",
- "values": [
- {
- "key": "name",
- "type": "person",
- "value": ["Alice"],
- "operator": "exact",
- "conditionHash": "hashA",
- "bytecode": [1, 2, 3],
- },
- {
- "key": "age",
- "type": "person",
- "value": [25],
- "operator": "gt",
- "conditionHash": "hashB",
- "bytecode": [4, 5, 6],
- },
- {
- "key": "email",
- "type": "person",
- "value": ["[email protected]"],
- "operator": "exact",
- "conditionHash": "hashC",
- "bytecode": [7, 8, 9],
- },
- ],
- }
- }
-
- cohort = self._create_cohort(name="Test Cohort", filters=filters)
-
- # Simulate pre_save capturing the same structure hash
- current_hash = _extract_person_property_filters(cohort)
- cohort._previous_person_property_filters = current_hash
-
- result = _person_property_filters_changed(cohort)
- self.assertFalse(result)
-
-
class TestFlagExcludedBehavioralCohortIds(BaseTest):
BEHAVIORAL_FILTERS = {
"properties": {