:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(clickhouse): restrict the Celery cleanup sweeps to self-hosted (#80015)
Eli Reismanc7a7afb5cf02
diff --git a/posthog/models/async_deletion/celery_fallback.py b/posthog/models/async_deletion/celery_fallback.pynew file mode 100644index 000000000000..5bca9c842148--- /dev/null+++ b/posthog/models/async_deletion/celery_fallback.py@@ -0,0 +1,48 @@+"""Gating for the Celery cleanup sweeps, which exist only for deployments without Dagster.++PostHog Cloud runs `clickhouse_deletion_sweep_job` instead. Two sweeps mutating `person` and+`person_distinct_id2` at once is the thing this prevents.+"""++import structlog++from posthog.clickhouse.client import sync_execute+from posthog.cloud_utils import is_hobby++logger = structlog.get_logger(__name__)++# The Dagster sweep runs weekly, so a month of silence means it does not run here.+DAGSTER_ACTIVITY_WINDOW_DAYS = 30++# The Celery sweep is unattended and uncapped by its caller, so it carries the Dagster default.+CELERY_SWEEP_MAX_COHORTS = 2_000+++def celery_sweeps_enabled() -> bool:+ """Whether this deployment should run the Celery cleanup sweeps."""+ return is_hobby() and not dagster_sweep_is_active()+++def dagster_sweep_is_active() -> bool:+ """Whether the Dagster sweep has run here in the last `DAGSTER_ACTIVITY_WINDOW_DAYS`.++ `derive_run_mode` resolves an unrecognized `CLOUD_DEPLOYMENT` to HOBBY, so `is_hobby()` reads+ true on a cloud deployment whose region is misspelled. This is the independent check on that.++ The counter is append-only, unlike `person_pg_cleanup_queue`, whose rows the Postgres drain+ deletes as it resolves them. An unreadable table means no Dagster sweep here.+ """+ try:+ [[runs]] = sync_execute(+ """+ SELECT count()+ FROM custom_metrics_counter_events+ WHERE name = 'clickhouse_cleanup_delete_pass_total'+ AND timestamp > now() - INTERVAL %(days)s DAY+ """,+ {"days": DAGSTER_ACTIVITY_WINDOW_DAYS},+ )+ return runs > 0+ except Exception:+ logger.info("clickhouse_cleanup counters unreadable, treating the Dagster sweep as absent")+ return Falsediff --git a/posthog/models/async_deletion/test_celery_fallback.py b/posthog/models/async_deletion/test_celery_fallback.pynew file mode 100644index 000000000000..2b390a6b0451--- /dev/null+++ b/posthog/models/async_deletion/test_celery_fallback.py@@ -0,0 +1,72 @@+from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from posthog.models.async_deletion.celery_fallback import celery_sweeps_enabled, dagster_sweep_is_active++GATE = "posthog.models.async_deletion.celery_fallback"+++class TestCelerySweepGating(SimpleTestCase):+ @parameterized.expand(+ [+ ("cloud_us", "US", False, False),+ ("cloud_eu", "EU", False, False),+ ("cloud_staging", "DEV", False, False),+ ("e2e", "E2E", False, False),+ ("local_dev_explicit", "LOCAL", False, False),+ ("local_dev_via_debug", None, True, False),+ ("self_hosted", None, False, True),+ ]+ )+ def test_only_self_hosted_runs_the_celery_sweeps(self, _name, cloud_deployment, debug, expected):+ with (+ override_settings(CLOUD_DEPLOYMENT=cloud_deployment, DEBUG=debug),+ patch(f"{GATE}.dagster_sweep_is_active", return_value=False),+ ):+ assert celery_sweeps_enabled() is expected++ def test_a_misspelled_cloud_deployment_is_caught_only_by_the_dagster_check(self):+ # derive_run_mode maps an unrecognized value to HOBBY, so is_hobby() reads true here.+ with override_settings(CLOUD_DEPLOYMENT="us-east-1", DEBUG=False):+ with patch(f"{GATE}.dagster_sweep_is_active", return_value=True):+ assert celery_sweeps_enabled() is False+ with patch(f"{GATE}.dagster_sweep_is_active", return_value=False):+ assert celery_sweeps_enabled() is True++ @parameterized.expand([("ran", [[3]], True), ("never_ran", [[0]], False)])+ def test_the_dagster_check_reads_the_sweep_counter(self, _name, rows, expected):+ with patch(f"{GATE}.sync_execute", return_value=rows):+ assert dagster_sweep_is_active() is expected++ def test_unreadable_counters_mean_no_dagster_sweep(self):+ # A self-hosted install may not have the table, which must not block the sweep.+ with patch(f"{GATE}.sync_execute", side_effect=Exception("no such table")):+ assert dagster_sweep_is_active() is False+++class TestCelerySweepTaskGuards(SimpleTestCase):+ @parameterized.expand(+ [+ ("cohorts", "posthog.tasks.tasks.clickhouse_clear_removed_data", "delete_cohorts.sweep_cohort_deletions"),+ (+ "persons",+ "posthog.tasks.tasks.clear_clickhouse_deleted_person",+ "delete_person.remove_deleted_person_data",+ ),+ ]+ )+ def test_the_task_does_nothing_when_gating_says_no(self, _name, task_path, swept_path):+ # The second layer: a beat schedule that survived a deploy must not sweep.+ from importlib import import_module++ module, _, name = task_path.rpartition(".")+ task = getattr(import_module(module), name)+ with (+ patch(f"{GATE}.celery_sweeps_enabled", return_value=False),+ patch(f"posthog.models.async_deletion.{swept_path}") as swept,+ ):+ task()+ swept.assert_not_called()diff --git a/posthog/settings/schedules.py b/posthog/settings/schedules.pyindex 1309974cbbbc..035bbcc42d7c 100644--- a/posthog/settings/schedules.py+++ b/posthog/settings/schedules.py@@ -58,7 +58,7 @@ CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON = get_from_env(# Schedule to delete redundant ClickHouse data on. Follows crontab syntax.# Use empty string to prevent thisCLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON = get_from_env(- "CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON",+ "CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON",# Every third month 5AM UTC on 1st of the month"0 5 1 */3 *",)diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 835b7236304f..41c248fbbd08 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -9,6 +9,7 @@ from celery.schedules import crontabfrom posthog.caching.warming import schedule_warming_for_teams_taskfrom posthog.clickhouse.client.execute_async import QueryStatusManager+from posthog.models.async_deletion.celery_fallback import celery_sweeps_enabledfrom posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reportsfrom posthog.tasks.auth_token_cache_verification import verify_and_fix_auth_token_cache_taskfrom posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs, publish_cohort_backfill_run_gauges@@ -820,19 +821,23 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="mark stale pulse briefs failed",)- if clear_clickhouse_crontab := get_crontab(settings.CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON):- sender.add_periodic_task(- clear_clickhouse_crontab,- clickhouse_clear_removed_data.s(),- name="clickhouse clear removed data",- )+ # Self-hosted only; cloud runs clickhouse_deletion_sweep_job instead.+ if celery_sweeps_enabled():+ if clear_clickhouse_crontab := get_crontab(settings.CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON):+ sender.add_periodic_task(+ clear_clickhouse_crontab,+ clickhouse_clear_removed_data.s(),+ name="clickhouse clear removed data",+ )- if clear_clickhouse_deleted_person_crontab := get_crontab(settings.CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON):- sender.add_periodic_task(- clear_clickhouse_deleted_person_crontab,- clear_clickhouse_deleted_person.s(),- name="clickhouse clear deleted person data",- )+ if clear_clickhouse_deleted_person_crontab := get_crontab(+ settings.CLEAR_CLICKHOUSE_DELETED_PERSON_SCHEDULE_CRON+ ):+ sender.add_periodic_task(+ clear_clickhouse_deleted_person_crontab,+ clear_clickhouse_deleted_person.s(),+ name="clickhouse clear deleted person data",+ )sender.add_periodic_task(crontab(hour="*", minute="0"),diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 2175379d4556..03c0be5a4a81 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -750,15 +750,22 @@ def clickhouse_mutation_count() -> None:@shared_task(ignore_result=True)def clickhouse_clear_removed_data() -> None:+ from posthog.models.async_deletion.celery_fallback import CELERY_SWEEP_MAX_COHORTS, celery_sweeps_enabledfrom posthog.models.async_deletion.delete_cohorts import sweep_cohort_deletions- sweep_cohort_deletions()+ # Also guarded at registration; this covers a stale beat schedule or a hand-run task.+ if not celery_sweeps_enabled():+ return+ sweep_cohort_deletions(max_cohorts=CELERY_SWEEP_MAX_COHORTS)@shared_task(ignore_result=True)def clear_clickhouse_deleted_person() -> None:+ from posthog.models.async_deletion.celery_fallback import celery_sweeps_enabledfrom posthog.models.async_deletion.delete_person import remove_deleted_person_data+ if not celery_sweeps_enabled():+ returnremove_deleted_person_data()