: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
chore(tasks): rms some unused tasks relying on persons (#61923)
Nick Bestd1835a24cf94
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.pyindex 7969738898d8..78860776c846 100644--- a/posthog/tasks/__init__.py+++ b/posthog/tasks/__init__.py@@ -23,7 +23,6 @@ from . import (tasks,team_access_cache_tasks,usage_report,- verify_persons_data_in_sync,warehouse,)@@ -50,6 +49,5 @@ __all__ = ["tasks","team_access_cache_tasks","usage_report",- "verify_persons_data_in_sync","warehouse",]diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 2e233e75ac94..239633e24fff 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -49,7 +49,6 @@ from posthog.tasks.tasks import (ingestion_lag,kill_stale_queued_task_runs,pg_plugin_server_query_timing,- pg_row_count,pg_table_cache_hit_rate,process_scheduled_changes,redis_celery_queue_depth,@@ -63,7 +62,6 @@ from posthog.tasks.tasks import (update_event_partitions,update_survey_adaptive_sampling,update_survey_iteration,- verify_persons_data_in_sync,)from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_policy_cache_entriesfrom posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entries@@ -368,11 +366,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="send matview failure digest",)- # PostHog Cloud cron jobs- # NOTE: We can't use is_cloud here as some Django elements aren't loaded yet. We check in the task execution instead- # Verify that persons data is in sync every day at 4 AM UTC- sender.add_periodic_task(crontab(hour="4", minute="0"), verify_persons_data_in_sync.s())-# Every 30 minutes, send decide request counts to the main posthog instancesender.add_periodic_task(crontab(minute="*/30"),@@ -434,12 +427,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="clickhouse instance errors count",)- add_periodic_task_with_expiry(- sender,- crontab(minute="*/2"),- pg_row_count.s(),- name="PG tables row counts",- )add_periodic_task_with_expiry(sender,crontab(minute="*/2"),diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 43197d3b7542..3269b6bf9566 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -334,31 +334,6 @@ def pg_plugin_server_query_timing() -> None:pass-POSTGRES_TABLES = ["posthog_personoverride", "posthog_personoverridemapping"]---@shared_task(ignore_result=True)-def pg_row_count() -> None:- with pushed_metrics_registry("celery_pg_row_count") as registry:- row_count_gauge = Gauge(- "posthog_celery_pg_table_row_count",- "Number of rows per Postgres table.",- labelnames=["table_name"],- registry=registry,- )- with connection.cursor() as cursor:- for table in POSTGRES_TABLES:- QUERY = "SELECT count(*) FROM {table};"- query = QUERY.format(table=table)-- try:- cursor.execute(query)- row = cursor.fetchone()- row_count_gauge.labels(table_name=table).set(row[0])- except:- pass--CLICKHOUSE_TABLES = ["sharded_events","person",@@ -906,16 +881,6 @@ def check_async_migration_health() -> None:check_async_migration_health()-@shared_task(ignore_result=True)-def verify_persons_data_in_sync() -> None:- from posthog.tasks.verify_persons_data_in_sync import verify_persons_data_in_sync as verify-- if not is_cloud():- return-- verify()--@shared_task(ignore_result=True)def stop_surveys_reached_target() -> None:from posthog.tasks.stop_surveys_reached_target import stop_surveys_reached_targetdiff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 926fcc0c14b8..d0bf93b03571 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -105,7 +105,6 @@'posthog.tasks.tasks.ingestion_lag','posthog.tasks.tasks.kill_stale_queued_task_runs','posthog.tasks.tasks.pg_plugin_server_query_timing',- 'posthog.tasks.tasks.pg_row_count','posthog.tasks.tasks.pg_table_cache_hit_rate','posthog.tasks.tasks.poll_query_performance','posthog.tasks.tasks.process_query_task',@@ -125,7 +124,6 @@'posthog.tasks.tasks.update_event_partitions','posthog.tasks.tasks.update_survey_adaptive_sampling','posthog.tasks.tasks.update_survey_iteration',- 'posthog.tasks.tasks.verify_persons_data_in_sync','posthog.tasks.team_access_cache_tasks.invalidate_token_cache_task','posthog.tasks.team_access_cache_tasks.invalidate_user_tokens_task','posthog.tasks.team_llm_gateway_policy.refresh_expiring_llm_gateway_policy_cache_entries',@@ -137,7 +135,6 @@'posthog.tasks.usage_report.capture_report','posthog.tasks.usage_report.send_all_org_usage_reports','posthog.tasks.usage_report.send_report_to_billing_service',- 'posthog.tasks.verify_persons_data_in_sync.verify_persons_data_in_sync','posthog.tasks.warehouse.validate_data_warehouse_table_columns',])# ---diff --git a/posthog/tasks/verify_persons_data_in_sync.py b/posthog/tasks/verify_persons_data_in_sync.pydeleted file mode 100644index d85ad44fe48a..000000000000--- a/posthog/tasks/verify_persons_data_in_sync.py+++ /dev/null@@ -1,188 +0,0 @@-import json-from collections import Counter, defaultdict-from datetime import timedelta-from typing import Any--from django.db.models.query import Prefetch-from django.utils.timezone import now--import structlog-from celery import shared_task--from posthog.clickhouse.client import sync_execute-from posthog.models.person import Person, PersonDistinctId-from posthog.scoping_audit import skip_team_scope_audit--logger = structlog.get_logger(__name__)--# We check up to LIMIT persons between PERIOD_START..PERIOD_END, in batches of BATCH_SIZE-# This helps keep the metric "moving" as we ship fixes or bugs.-LIMIT = 100000-BATCH_SIZE = 500-PERIOD_START = timedelta(hours=1)-PERIOD_END = timedelta(days=2)--GET_PERSON_CH_QUERY = """-SELECT id, version, properties FROM person JOIN (- SELECT id, max(version) as version, max(is_deleted) as is_deleted, team_id- FROM person- WHERE team_id IN %(team_ids)s AND id IN (%(person_ids)s)- GROUP BY team_id, id-) as person_max ON person.id = person_max.id AND person.version = person_max.version AND person.team_id = person_max.team_id-WHERE team_id IN %(team_ids)s- AND person_max.is_deleted = 0- AND id IN (%(person_ids)s)-"""--GET_DISTINCT_IDS_CH_QUERY = """-SELECT distinct_id, argMax(person_id, version) as person_id-FROM person_distinct_id2-WHERE team_id IN %(team_ids)s-GROUP BY team_id, distinct_id-HAVING argMax(is_deleted, version) = 0 AND person_id IN (%(person_ids)s)-"""---@shared_task(max_retries=1, ignore_result=True)-@skip_team_scope_audit-def verify_persons_data_in_sync(- period_start: timedelta = PERIOD_START,- period_end: timedelta = PERIOD_END,- limit: int = LIMIT,- emit_results: bool = True,-) -> Counter:- # :KLUDGE: Rather than filter on created_at directly which is unindexed, we look up the latest value in 'id' column- # and leverage that to narrow down filtering in an index-efficient way- max_pk = (- # nosemgrep: no-direct-persons-db-orm- Person.objects.filter(created_at__lte=now() - period_start)- .latest("id")- .id # nosemgrep: no-direct-persons-db-orm- ) # nosemgrep: no-direct-persons-db-orm- person_data = list(- Person.objects.filter( # nosemgrep: no-direct-persons-db-orm- pk__lte=max_pk,- pk__gte=max_pk - LIMIT * 5,- created_at__gte=now() - period_end,- ).values_list("id", "uuid", "team_id")[:limit]- )- person_data.sort(key=lambda row: row[2]) # keep persons from same team together-- results = Counter(- {- "total": 0,- "missing_in_clickhouse": 0,- "version_mismatch": 0,- "properties_mismatch": 0,- "distinct_ids_mismatch": 0,- "properties_mismatch_same_version": 0,- }- )- for i in range(0, len(person_data), BATCH_SIZE):- batch = person_data[i : i + BATCH_SIZE]- results += _team_integrity_statistics(batch)-- if emit_results:- _emit_metrics(results)-- return results---def _team_integrity_statistics(person_data: list[Any]) -> Counter:- person_ids = [id for id, _, _ in person_data]- person_uuids = [uuid for _, uuid, _ in person_data]- team_ids = list({team_id for _, _, team_id in person_data})-- # :TRICKY: To speed up processing, we fetch all models in batch at once and store results in dictionary indexed by person uuid- pg_persons = _index_by(- list(- Person.objects.filter( # nosemgrep: no-direct-persons-db-orm- id__in=person_ids, team_id__in=team_ids- ).prefetch_related( # nosemgrep: no-direct-persons-db-orm- Prefetch(- "persondistinctid_set",- # nosemgrep: no-direct-persons-db-orm- queryset=PersonDistinctId.objects.filter(- team_id__in=team_ids- ).order_by( # nosemgrep: no-direct-persons-db-orm- "id"- ), # nosemgrep: no-direct-persons-db-orm- to_attr="distinct_ids_cache",- )- )- ),- lambda p: p.uuid,- )-- ch_persons = _index_by(- sync_execute(GET_PERSON_CH_QUERY, {"person_ids": person_uuids, "team_ids": team_ids}),- lambda row: row[0],- )-- ch_distinct_ids_mapping = _index_by(- sync_execute(- GET_DISTINCT_IDS_CH_QUERY,- {"person_ids": person_uuids, "team_ids": team_ids},- ),- lambda row: row[1],- flat=False,- )-- result: Counter = Counter()- for _pk, uuid, team_id in person_data:- # Person was deleted in the middle of processing, can ignore- if uuid not in pg_persons:- continue- result["total"] += 1- pg_person = pg_persons[uuid]- if uuid not in ch_persons:- result["missing_in_clickhouse"] += 1- logger.info("Found person missing in clickhouse", team_id=team_id, uuid=uuid)- continue- _, ch_version, ch_properties = ch_persons[uuid]- ch_properties = json.loads(ch_properties)- if ch_version != pg_person.version:- result["version_mismatch"] += 1- logger.info(- "Found version mismatch",- team_id=team_id,- uuid=uuid,- properties=pg_person.properties,- ch_properties=ch_properties,- )- if pg_person.properties != ch_properties:- result["properties_mismatch"] += 1- logger.info(- "Found properties mismatch",- team_id=team_id,- uuid=uuid,- properties=pg_person.properties,- ch_properties=ch_properties,- )-- # :KLUDGE: Verify business logic. If versions are in sync so should properties be.- if ch_version != 0 and ch_version == pg_person.version and pg_person.properties != ch_properties:- result["properties_mismatch_same_version"] += 1-- pg_distinct_ids = sorted(map(str, pg_person.distinct_ids))- ch_distinct_id = sorted(str(distinct_id) for distinct_id, _ in ch_distinct_ids_mapping.get(uuid, []))- if pg_distinct_ids != ch_distinct_id:- result["distinct_ids_mismatch"] += 1- return result---def _emit_metrics(integrity_results: Counter) -> None:- from statshog.defaults.django import statsd-- for key, value in integrity_results.items():- statsd.gauge(f"posthog_person_integrity_{key}", value)---def _index_by(collection: list[Any], key_fn: Any, flat: bool = True) -> dict:- result: dict = {} if flat else defaultdict(list)- for item in collection:- if flat:- result[key_fn(item)] = item- else:- result[key_fn(item)].append(item)- return resultdiff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambrindex 99eace3b572f..9949fba14211 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr@@ -127,114 +127,6 @@use_hive_partitioning=0'''# ----# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed- '''- WITH exposures AS- (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,- if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,- min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,- max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,- argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,- argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id- FROM experiment_exposures_preaggregated AS t- WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))))- GROUP BY entity_id),- metric_events AS- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,- toTimeZone(events.timestamp, 'UTC') AS timestamp,- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value- FROM events- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(86400))), equals(events.event, 'purchase'))),- entity_metrics AS- (SELECT exposures.entity_id AS entity_id,- exposures.variant AS variant,- sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value- FROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), exposures.first_exposure_time), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(exposures.last_exposure_time, toIntervalSecond(86400)))))- GROUP BY exposures.entity_id,- exposures.variant)- SELECT entity_metrics.variant AS variant,- count(entity_metrics.entity_id) AS num_users,- sum(entity_metrics.value) AS total_sum,- sum(power(entity_metrics.value, 2)) AS total_sum_of_squares- FROM entity_metrics- GROUP BY entity_metrics.variant- LIMIT 50000 SETTINGS join_algorithm='grace_hash',- grace_hash_join_initial_buckets=2,- load_balancing='in_order',- readonly=2,- max_execution_time=600,- allow_experimental_object_type=1,- max_ast_elements=4000000,- max_expanded_ast_elements=4000000,- max_bytes_before_external_group_by=39728447488,- transform_null_in=1,- optimize_min_equality_disjunction_chain_length=4294967295,- allow_experimental_join_condition=1,- use_hive_partitioning=0- '''-# ----# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed- '''- WITH exposures AS- (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,- if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,- min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,- max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,- argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,- argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id- FROM experiment_exposures_preaggregated AS t- WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC'))))- GROUP BY entity_id),- metric_events AS- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,- toTimeZone(events.timestamp, 'UTC') AS timestamp,- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value- FROM events- LEFT OUTER JOIN- (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,- person_distinct_id_overrides.distinct_id AS distinct_id- FROM person_distinct_id_overrides- WHERE equals(person_distinct_id_overrides.team_id, 99999)- GROUP BY person_distinct_id_overrides.distinct_id- HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(86400))), equals(events.event, 'purchase'))),- entity_metrics AS- (SELECT exposures.entity_id AS entity_id,- exposures.variant AS variant,- sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value- FROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), exposures.first_exposure_time), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(exposures.last_exposure_time, toIntervalSecond(86400)))))- GROUP BY exposures.entity_id,- exposures.variant)- SELECT entity_metrics.variant AS variant,- count(entity_metrics.entity_id) AS num_users,- sum(entity_metrics.value) AS total_sum,- sum(power(entity_metrics.value, 2)) AS total_sum_of_squares- FROM entity_metrics- GROUP BY entity_metrics.variant- LIMIT 50000 SETTINGS join_algorithm='grace_hash',- grace_hash_join_initial_buckets=2,- load_balancing='in_order',- readonly=2,- max_execution_time=600,- allow_experimental_object_type=1,- max_ast_elements=4000000,- max_expanded_ast_elements=4000000,- max_bytes_before_external_group_by=39728447488,- transform_null_in=1,- optimize_min_equality_disjunction_chain_length=4294967295,- allow_experimental_join_condition=1,- use_hive_partitioning=0- '''-# ---# name: TestExperimentMeanMetric.test_count_distinct_property_values_via_hogql_0_direct'''WITH exposures AS