: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(personhog): migrate cohortpeople writes to personhog (#56234)
Nick Best5357ae3b6958
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex d64377676900..ad5d16483f29 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -1268,7 +1268,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):except (ValueError, AttributeError):raise ValidationError("One or more UUIDs are invalid.")- persons = get_persons_by_uuids(self.team, uuids)+ persons = get_persons_by_uuids(self.team_id, uuids)results: dict[str, Any] = {}for person in persons:diff --git a/posthog/api/test/__snapshots__/test_feature_flag.ambr b/posthog/api/test/__snapshots__/test_feature_flag.ambrindex 85b451eed666..2c13e8eded51 100644--- a/posthog/api/test/__snapshots__/test_feature_flag.ambr+++ b/posthog/api/test/__snapshots__/test_feature_flag.ambr@@ -540,6 +540,22 @@'''# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.3+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.4'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -643,7 +659,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.4+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.5'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -665,7 +681,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.5+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.6'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -685,7 +701,23 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.6+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.7+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.8'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -707,7 +739,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.7+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_iterator.9'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -832,6 +864,22 @@'''# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.4+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.5'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -935,7 +983,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.5+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.6'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -957,7 +1005,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.6+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too.7'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1019,6 +1067,126 @@'''# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.10+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.11+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."uuid",+ "posthog_team"."organization_id",+ "posthog_team"."parent_team_id",+ "posthog_team"."project_id",+ "posthog_team"."api_token",+ "posthog_team"."app_urls",+ "posthog_team"."name",+ "posthog_team"."slack_incoming_webhook",+ "posthog_team"."created_at",+ "posthog_team"."updated_at",+ "posthog_team"."anonymize_ips",+ "posthog_team"."completed_snippet_onboarding",+ "posthog_team"."has_completed_onboarding_for",+ "posthog_team"."onboarding_tasks",+ "posthog_team"."ingested_event",+ "posthog_team"."person_processing_opt_out",+ "posthog_team"."secret_api_token",+ "posthog_team"."secret_api_token_backup",+ "posthog_team"."session_recording_opt_in",+ "posthog_team"."session_recording_sample_rate",+ "posthog_team"."session_recording_minimum_duration_milliseconds",+ "posthog_team"."session_recording_linked_flag",+ "posthog_team"."session_recording_network_payload_capture_config",+ "posthog_team"."session_recording_masking_config",+ "posthog_team"."session_recording_url_trigger_config",+ "posthog_team"."session_recording_url_blocklist_config",+ "posthog_team"."session_recording_event_trigger_config",+ "posthog_team"."session_recording_trigger_match_type_config",+ "posthog_team"."session_recording_trigger_groups",+ "posthog_team"."session_replay_config",+ "posthog_team"."session_recording_retention_period",+ "posthog_team"."conversations_enabled",+ "posthog_team"."conversations_settings",+ "posthog_team"."proactive_tasks_enabled",+ "posthog_team"."survey_config",+ "posthog_team"."surveys_opt_in",+ "posthog_team"."product_tours_opt_in",+ "posthog_team"."capture_console_log_opt_in",+ "posthog_team"."capture_performance_opt_in",+ "posthog_team"."capture_dead_clicks",+ "posthog_team"."autocapture_opt_out",+ "posthog_team"."autocapture_web_vitals_opt_in",+ "posthog_team"."autocapture_web_vitals_allowed_metrics",+ "posthog_team"."autocapture_exceptions_opt_in",+ "posthog_team"."autocapture_exceptions_errors_to_ignore",+ "posthog_team"."logs_settings",+ "posthog_team"."heatmaps_opt_in",+ "posthog_team"."receive_org_level_activity_logs",+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",+ "posthog_team"."web_analytics_pre_aggregated_tables_version",+ "posthog_team"."flags_persistence_default",+ "posthog_team"."feature_flag_confirmation_enabled",+ "posthog_team"."feature_flag_confirmation_message",+ "posthog_team"."default_evaluation_environments_enabled",+ "posthog_team"."require_evaluation_environment_tags",+ "posthog_team"."default_evaluation_contexts_enabled",+ "posthog_team"."require_evaluation_contexts",+ "posthog_team"."session_recording_version",+ "posthog_team"."signup_token",+ "posthog_team"."is_demo",+ "posthog_team"."access_control",+ "posthog_team"."week_start_day",+ "posthog_team"."inject_web_apps",+ "posthog_team"."test_account_filters",+ "posthog_team"."test_account_filters_default_checked",+ "posthog_team"."path_cleaning_filters",+ "posthog_team"."timezone",+ "posthog_team"."data_attributes",+ "posthog_team"."person_display_name_properties",+ "posthog_team"."live_events_columns",+ "posthog_team"."recording_domains",+ "posthog_team"."human_friendly_comparison_periods",+ "posthog_team"."cookieless_server_hash_mode",+ "posthog_team"."primary_dashboard_id",+ "posthog_team"."default_data_theme",+ "posthog_team"."extra_settings",+ "posthog_team"."modifiers",+ "posthog_team"."correlation_config",+ "posthog_team"."session_recording_retention_period_days",+ "posthog_team"."plugins_opt_in",+ "posthog_team"."opt_out_capture",+ "posthog_team"."event_names",+ "posthog_team"."event_names_with_usage",+ "posthog_team"."event_properties",+ "posthog_team"."event_properties_with_usage",+ "posthog_team"."event_properties_numerical",+ "posthog_team"."external_data_workspace_id",+ "posthog_team"."external_data_workspace_last_synced_at",+ "posthog_team"."api_query_rate_limit",+ "posthog_team"."revenue_tracking_config",+ "posthog_team"."drop_events_older_than",+ "posthog_team"."base_currency",+ "posthog_team"."experiment_recalculation_time",+ "posthog_team"."default_experiment_confidence_level",+ "posthog_team"."default_experiment_stats_method",+ "posthog_team"."business_model"+ FROM "posthog_team"+ WHERE "posthog_team"."id" = 99999+ LIMIT 21+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.12'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1040,7 +1208,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.11+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.13'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1093,6 +1261,22 @@'''# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.3+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.4'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1196,7 +1380,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.4+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.5'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1218,7 +1402,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.5+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.6'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1238,7 +1422,7 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.6+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.7'''SELECT "posthog_team"."id","posthog_team"."project_id"@@ -1247,7 +1431,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.7+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.8'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -1279,7 +1463,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.8+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.9'''SELECT "posthog_cohort"."id","posthog_cohort"."name",@@ -1311,110 +1495,6 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_default_person_properties_adjustment.9- '''- SELECT "posthog_team"."id",- "posthog_team"."uuid",- "posthog_team"."organization_id",- "posthog_team"."parent_team_id",- "posthog_team"."project_id",- "posthog_team"."api_token",- "posthog_team"."app_urls",- "posthog_team"."name",- "posthog_team"."slack_incoming_webhook",- "posthog_team"."created_at",- "posthog_team"."updated_at",- "posthog_team"."anonymize_ips",- "posthog_team"."completed_snippet_onboarding",- "posthog_team"."has_completed_onboarding_for",- "posthog_team"."onboarding_tasks",- "posthog_team"."ingested_event",- "posthog_team"."person_processing_opt_out",- "posthog_team"."secret_api_token",- "posthog_team"."secret_api_token_backup",- "posthog_team"."session_recording_opt_in",- "posthog_team"."session_recording_sample_rate",- "posthog_team"."session_recording_minimum_duration_milliseconds",- "posthog_team"."session_recording_linked_flag",- "posthog_team"."session_recording_network_payload_capture_config",- "posthog_team"."session_recording_masking_config",- "posthog_team"."session_recording_url_trigger_config",- "posthog_team"."session_recording_url_blocklist_config",- "posthog_team"."session_recording_event_trigger_config",- "posthog_team"."session_recording_trigger_match_type_config",- "posthog_team"."session_recording_trigger_groups",- "posthog_team"."session_replay_config",- "posthog_team"."session_recording_retention_period",- "posthog_team"."conversations_enabled",- "posthog_team"."conversations_settings",- "posthog_team"."proactive_tasks_enabled",- "posthog_team"."survey_config",- "posthog_team"."surveys_opt_in",- "posthog_team"."product_tours_opt_in",- "posthog_team"."capture_console_log_opt_in",- "posthog_team"."capture_performance_opt_in",- "posthog_team"."capture_dead_clicks",- "posthog_team"."autocapture_opt_out",- "posthog_team"."autocapture_web_vitals_opt_in",- "posthog_team"."autocapture_web_vitals_allowed_metrics",- "posthog_team"."autocapture_exceptions_opt_in",- "posthog_team"."autocapture_exceptions_errors_to_ignore",- "posthog_team"."logs_settings",- "posthog_team"."heatmaps_opt_in",- "posthog_team"."receive_org_level_activity_logs",- "posthog_team"."web_analytics_pre_aggregated_tables_enabled",- "posthog_team"."web_analytics_pre_aggregated_tables_version",- "posthog_team"."flags_persistence_default",- "posthog_team"."feature_flag_confirmation_enabled",- "posthog_team"."feature_flag_confirmation_message",- "posthog_team"."default_evaluation_environments_enabled",- "posthog_team"."require_evaluation_environment_tags",- "posthog_team"."default_evaluation_contexts_enabled",- "posthog_team"."require_evaluation_contexts",- "posthog_team"."session_recording_version",- "posthog_team"."signup_token",- "posthog_team"."is_demo",- "posthog_team"."access_control",- "posthog_team"."week_start_day",- "posthog_team"."inject_web_apps",- "posthog_team"."test_account_filters",- "posthog_team"."test_account_filters_default_checked",- "posthog_team"."path_cleaning_filters",- "posthog_team"."timezone",- "posthog_team"."data_attributes",- "posthog_team"."person_display_name_properties",- "posthog_team"."live_events_columns",- "posthog_team"."recording_domains",- "posthog_team"."human_friendly_comparison_periods",- "posthog_team"."cookieless_server_hash_mode",- "posthog_team"."primary_dashboard_id",- "posthog_team"."default_data_theme",- "posthog_team"."extra_settings",- "posthog_team"."modifiers",- "posthog_team"."correlation_config",- "posthog_team"."session_recording_retention_period_days",- "posthog_team"."plugins_opt_in",- "posthog_team"."opt_out_capture",- "posthog_team"."event_names",- "posthog_team"."event_names_with_usage",- "posthog_team"."event_properties",- "posthog_team"."event_properties_with_usage",- "posthog_team"."event_properties_numerical",- "posthog_team"."external_data_workspace_id",- "posthog_team"."external_data_workspace_last_synced_at",- "posthog_team"."api_query_rate_limit",- "posthog_team"."revenue_tracking_config",- "posthog_team"."drop_events_older_than",- "posthog_team"."base_currency",- "posthog_team"."experiment_recalculation_time",- "posthog_team"."default_experiment_confidence_level",- "posthog_team"."default_experiment_stats_method",- "posthog_team"."business_model"- FROM "posthog_team"- WHERE "posthog_team"."id" = 99999- LIMIT 21- '''-# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag'''SELECT "posthog_team"."id",@@ -1489,6 +1569,22 @@'''# ---# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.3+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.4'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -1592,7 +1688,7 @@LIMIT 21'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.4+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.5'''SELECT "posthog_filesystem"."team_id","posthog_filesystem"."id",@@ -1614,7 +1710,7 @@AND "posthog_filesystem"."shortcut" IS NOT NULL))'''# ----# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.5+# name: TestCohortGenerationForFeatureFlag.test_creating_static_cohort_with_experience_continuity_flag.6'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -1981,6 +2077,22 @@'''# ---# name: TestFeatureFlag.test_creating_static_cohort.18+ '''+ SELECT 1 AS "a"+ FROM "posthog_cohort"+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")+ WHERE (("posthog_cohort"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_cohort"."team_id" = 99999))+ AND "posthog_cohort"."id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestFeatureFlag.test_creating_static_cohort.19'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -2084,28 +2196,6 @@LIMIT 21'''# ----# name: TestFeatureFlag.test_creating_static_cohort.19- '''- SELECT "posthog_filesystem"."team_id",- "posthog_filesystem"."id",- "posthog_filesystem"."path",- "posthog_filesystem"."depth",- "posthog_filesystem"."type",- "posthog_filesystem"."ref",- "posthog_filesystem"."href",- "posthog_filesystem"."shortcut",- "posthog_filesystem"."meta",- "posthog_filesystem"."created_at",- "posthog_filesystem"."created_by_id",- "posthog_filesystem"."project_id"- FROM "posthog_filesystem"- WHERE ("posthog_filesystem"."ref" = '0001'- AND "posthog_filesystem"."team_id" = 99999- AND "posthog_filesystem"."type" = 'cohort'- AND NOT ("posthog_filesystem"."shortcut"- AND "posthog_filesystem"."shortcut" IS NOT NULL))- '''-# ---# name: TestFeatureFlag.test_creating_static_cohort.2'''SELECT "posthog_team"."id",@@ -2236,6 +2326,28 @@'''# ---# name: TestFeatureFlag.test_creating_static_cohort.20+ '''+ SELECT "posthog_filesystem"."team_id",+ "posthog_filesystem"."id",+ "posthog_filesystem"."path",+ "posthog_filesystem"."depth",+ "posthog_filesystem"."type",+ "posthog_filesystem"."ref",+ "posthog_filesystem"."href",+ "posthog_filesystem"."shortcut",+ "posthog_filesystem"."meta",+ "posthog_filesystem"."created_at",+ "posthog_filesystem"."created_by_id",+ "posthog_filesystem"."project_id"+ FROM "posthog_filesystem"+ WHERE ("posthog_filesystem"."ref" = '0001'+ AND "posthog_filesystem"."team_id" = 99999+ AND "posthog_filesystem"."type" = 'cohort'+ AND NOT ("posthog_filesystem"."shortcut"+ AND "posthog_filesystem"."shortcut" IS NOT NULL))+ '''+# ---+# name: TestFeatureFlag.test_creating_static_cohort.21'''SELECT "posthog_filesystemshortcut"."id","posthog_filesystemshortcut"."team_id",@@ -2255,7 +2367,7 @@AND "posthog_filesystemshortcut"."href" IS NOT NULL))'''# ----# name: TestFeatureFlag.test_creating_static_cohort.21+# name: TestFeatureFlag.test_creating_static_cohort.22'''SELECT "posthog_cohort"."id","posthog_cohort"."name",@@ -2285,7 +2397,7 @@LIMIT 21'''# ----# name: TestFeatureFlag.test_creating_static_cohort.22+# name: TestFeatureFlag.test_creating_static_cohort.23'''SELECT "posthog_team"."id","posthog_team"."uuid",@@ -2389,7 +2501,7 @@LIMIT 21'''# ----# name: TestFeatureFlag.test_creating_static_cohort.23+# name: TestFeatureFlag.test_creating_static_cohort.24'''SELECT "posthog_user"."id","posthog_user"."password",@@ -2433,7 +2545,7 @@LIMIT 21'''# ----# name: TestFeatureFlag.test_creating_static_cohort.24+# name: TestFeatureFlag.test_creating_static_cohort.25'''SELECT "posthog_cohortcalculationhistory"."id","posthog_cohortcalculationhistory"."team_id",@@ -2454,7 +2566,7 @@LIMIT 1'''# ----# name: TestFeatureFlag.test_creating_static_cohort.25+# name: TestFeatureFlag.test_creating_static_cohort.26'''SELECT "posthog_experiment"."id","posthog_experiment"."name",@@ -2490,7 +2602,7 @@WHERE "posthog_experiment"."exposure_cohort_id" = 99999'''# ----# name: TestFeatureFlag.test_creating_static_cohort.26+# name: TestFeatureFlag.test_creating_static_cohort.27'''/* user_id:0 request:_snapshot_ */SELECT iddiff --git a/posthog/api/test/test_feature_flag.py b/posthog/api/test/test_feature_flag.pyindex de9907e20a62..1df3cec14829 100644--- a/posthog/api/test/test_feature_flag.py+++ b/posthog/api/test/test_feature_flag.py@@ -8470,7 +8470,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):)# TODO: Ensure server-side cursors are disabled, since in production we use this with pgbouncer- with snapshot_postgres_queries_context(self), self.assertNumQueries(17):+ with snapshot_postgres_queries_context(self), self.assertNumQueries(18):get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)cohort.refresh_from_db()@@ -8528,7 +8528,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):)# Extra queries because each batch adds its own queries- with snapshot_postgres_queries_context(self), self.assertNumQueries(23):+ with snapshot_postgres_queries_context(self), self.assertNumQueries(25):get_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk, batchsize=2)cohort.refresh_from_db()@@ -8618,7 +8618,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):name="some cohort",)- with snapshot_postgres_queries_context(self), self.assertNumQueries(14):+ with snapshot_postgres_queries_context(self), self.assertNumQueries(15):# no queries to evaluate flags, because all evaluated using override propertiesget_cohort_actors_for_feature_flag(cohort.pk, "some-feature2", self.team.pk)@@ -8747,7 +8747,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):name="some cohort",)- with snapshot_postgres_queries_context(self), self.assertNumQueries(31):+ with snapshot_postgres_queries_context(self), self.assertNumQueries(32):# forced to evaluate flags by going to db, because cohorts need db query to evaluateget_cohort_actors_for_feature_flag(cohort.pk, "some-feature-new", self.team.pk)diff --git a/posthog/models/cohort/cohort.py b/posthog/models/cohort/cohort.pyindex 596a39bbfa71..00f33ee23505 100644--- a/posthog/models/cohort/cohort.py+++ b/posthog/models/cohort/cohort.py@@ -27,10 +27,9 @@ from posthog.models.file_system.file_system_representation import FileSystemReprfrom posthog.models.filters.filter import Filterfrom posthog.models.person import Person, PersonDistinctIdfrom posthog.models.person.person import READ_DB_FOR_PERSONS-from posthog.models.person.util import get_person_by_uuid, get_persons_by_distinct_ids, is_person_in_cohort+from posthog.models.person.util import get_person_by_uuid, get_persons_by_distinct_idsfrom posthog.models.property import Property, PropertyGroupfrom posthog.models.utils import RootTeamManager, RootTeamMixin, sane_repr-from posthog.person_db_router import PERSONS_DB_FOR_WRITEfrom posthog.settings.base_variables import TESTif TYPE_CHECKING:@@ -696,75 +695,79 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Args:batch_iterator: BatchIterator of user UUIDs to be inserted into the cohort.insert_in_clickhouse: Whether the data should also be inserted into ClickHouse.- batchsize: Number of UUIDs to process in each batch.team_id: The ID of the team to which the cohort belongs.Returns:Number of batches processed."""- from posthog.models.cohort.util import get_static_cohort_size, insert_static_cohort+ from posthog.models.cohort.util import count_cohort_members, insert_static_cohort+ from posthog.personhog_client.gate import use_personhogcurrent_batch_index = -1processing_error = None+ personhog = use_personhog()try:from django.db import connections, router- db_write = router.db_for_write(Person) or "default"- db_read = router.db_for_read(Person) or "default"- persons_connection = connections[db_write]- cursor = persons_connection.cursor()- cohort_people_table = CohortPeople._meta.db_table- for batch_index, batch in batch_iterator:- current_batch_index = batch_index-- persons_query = (- # nosemgrep: no-direct-persons-db-orm- Person.objects.db_manager(db_read)- .filter(team_id=team_id)- .filter(uuid__in=batch) # nosemgrep: no-direct-persons-db-orm- ) # nosemgrep: no-direct-persons-db-orm- if insert_in_clickhouse:- # Both querysets must use db_write so Django can merge the- # .exclude() into a single NOT IN subquery. Using db_read- # for Person + db_write for CohortPeople causes a- # "Subqueries aren't allowed across different databases"- # ValueError when the aliases differ (production config).- insert_uuids_query = (- Person.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm- .filter(team_id=team_id, uuid__in=batch)- .exclude(- id__in=CohortPeople.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm- .filter(cohort_id=self.id)- .values_list("person_id", flat=True)- )- )- insert_static_cohort(- list(insert_uuids_query.values_list("uuid", flat=True)),- self.pk,- team_id=team_id,+ if personhog:+ for batch_index, batch in batch_iterator:+ current_batch_index = batch_index+ self._insert_batch_via_personhog(batch, insert_in_clickhouse, team_id=team_id)+ else:+ db_write = router.db_for_write(Person) or "default"+ db_read = router.db_for_read(Person) or "default"+ persons_connection = connections[db_write]+ cursor = persons_connection.cursor()+ cohort_people_table = CohortPeople._meta.db_table+ for batch_index, batch in batch_iterator:+ current_batch_index = batch_index++ persons_query = (+ Person.objects.db_manager(db_read) # nosemgrep: no-direct-persons-db-orm+ .filter(team_id=team_id)+ .filter(uuid__in=batch) # nosemgrep: no-direct-persons-db-orm)+ if insert_in_clickhouse:+ # Both querysets must use db_write so Django can merge the+ # .exclude() into a single NOT IN subquery. Using db_read+ # for Person + db_write for CohortPeople causes a+ # "Subqueries aren't allowed across different databases"+ # ValueError when the aliases differ (production config).+ insert_uuids_query = (+ Person.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm+ .filter(team_id=team_id, uuid__in=batch)+ .exclude(+ id__in=CohortPeople.objects.using(db_write) # nosemgrep: no-direct-persons-db-orm+ .filter(cohort_id=self.id)+ .values_list("person_id", flat=True)+ )+ )+ insert_static_cohort(+ list(insert_uuids_query.values_list("uuid", flat=True)),+ self.pk,+ team_id=team_id,+ )- # Dedup via LEFT JOIN so the exclusion stays entirely in SQL,- # avoiding the O(cohort_size) memory cost of loading all- # existing member IDs into Python. Both tables live on the- # persons DB so the join works on the db_write cursor.- sql, params = persons_query.distinct("pk").only("pk").query.sql_with_params()- query = f"""- INSERT INTO "{cohort_people_table}" ("person_id", "cohort_id", "version")- SELECT p."id", {self.pk}, {self.version or "NULL"}- FROM ({sql}) AS p- LEFT JOIN "{cohort_people_table}" AS cp- ON cp."person_id" = p."id" AND cp."cohort_id" = {self.pk}- WHERE cp."person_id" IS NULL- ON CONFLICT DO NOTHING- """- cursor.execute(query, params)+ # Dedup via LEFT JOIN so the exclusion stays entirely in SQL,+ # avoiding the O(cohort_size) memory cost of loading all+ # existing member IDs into Python. Both tables live on the+ # persons DB so the join works on the db_write cursor.+ sql, params = persons_query.distinct("pk").only("pk").query.sql_with_params()+ query = f"""+ INSERT INTO "{cohort_people_table}" ("person_id", "cohort_id", "version")+ SELECT p."id", {self.pk}, {self.version or "NULL"}+ FROM ({sql}) AS p+ LEFT JOIN "{cohort_people_table}" AS cp+ ON cp."person_id" = p."id" AND cp."cohort_id" = {self.pk}+ WHERE cp."person_id" IS NULL+ ON CONFLICT DO NOTHING+ """+ cursor.execute(query, params)except Exception as err:processing_error = errif settings.DEBUG:raise- # Add batch index context to the exceptioncapture_exception(err,additional_properties={@@ -776,11 +779,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):finally:# Always update the count and cohort state, even if processing failedtry:- # Use the write database to avoid replication lag from under-representing the count after inserting- count = get_static_cohort_size(cohort_id=self.id, team_id=self.team_id, using_database=db_write)+ count = count_cohort_members(cohort_id=self.id, team_id=self.team_id, consistency="strong")self.count = countexcept Exception as count_err:- # If count calculation fails, log the error but don't override the processing error+ # If count calculation fails, log the error but don't override the processing error.+ # Leave existing count unchanged - it's better than None.logger.exception("Failed to calculate static cohort size",cohort_id=self.id,@@ -790,12 +793,68 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):count_err,additional_properties={"cohort_id": self.id, "team_id": team_id},)- # Leave existing count unchanged - it's better than Noneself._safe_save_cohort_state(team_id=team_id, processing_error=processing_error)return current_batch_index + 1+ def _insert_batch_via_personhog(+ self,+ batch: list[str],+ insert_in_clickhouse: bool,+ *,+ team_id: int,+ ) -> None:+ """Personhog path for inserting a single batch of cohort members.++ Resolves UUIDs → person IDs via personhog, then calls the+ InsertCohortMembers RPC. ClickHouse inserts (if requested)+ exclude persons already in the cohort because the+ person_static_cohort table's ORDER BY includes a per-row UUID,+ preventing ReplacingMergeTree from deduplicating repeated inserts.+ """+ from posthog.models.cohort.util import insert_static_cohort+ from posthog.models.person.sql import PERSON_STATIC_COHORT_TABLE+ from posthog.models.person.util import get_persons_by_uuids++ persons = get_persons_by_uuids(team_id, batch)+ if not persons:+ return++ person_ids = [p.id for p in persons]+ person_uuids = [p.uuid for p in persons]++ if insert_in_clickhouse:+ uuid_strs = [str(u) for u in person_uuids]+ existing_uuids = self._get_existing_ch_member_uuids(uuid_strs, team_id, PERSON_STATIC_COHORT_TABLE)+ new_uuids = [u for u in person_uuids if str(u) not in existing_uuids]+ if new_uuids:+ insert_static_cohort(new_uuids, self.pk, team_id=team_id)++ from posthog.models.cohort.util import insert_cohort_members++ insert_cohort_members(team_id, self.pk, person_ids, self.version, _skip_ownership_check=True)++ def _get_existing_ch_member_uuids(+ self,+ person_uuids: list[str],+ team_id: int,+ table: str,+ ) -> set[str]:+ """Return the subset of person_uuids that already exist in the CH static cohort table."""+ if not person_uuids:+ return set()+ # nosemgrep: clickhouse-fstring-param-audit - table name from constant, values parameterized+ rows = sync_execute(+ f"SELECT person_id FROM {table} WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s AND person_id IN %(person_uuids)s GROUP BY person_id",+ {+ "team_id": team_id,+ "cohort_id": self.pk,+ "person_uuids": person_uuids,+ },+ )+ return {str(row[0]) for row in rows}+def remove_user_by_uuid(self, user_uuid: str, *, team_id: int) -> bool:"""Remove a user from the cohort by their UUID.@@ -811,7 +870,12 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):Raises:Exception: If removal fails due to database errors."""- from posthog.models.cohort.util import get_static_cohort_size, remove_person_from_static_cohort+ from posthog.models.cohort.util import (+ delete_cohort_member,+ get_static_cohort_size,+ is_person_in_cohort,+ remove_person_from_static_cohort,+ )try:# Get person by UUID@@ -825,12 +889,8 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# Delete from PostgreSQL first (source of truth), then ClickHouse.# This order ensures if PG delete fails, we don't create inverse inconsistency.- # The delete itself still goes through the ORM — no personhog RPC exists yet- # for removing a cohort member.if is_member:- CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm- cohort_id=self.id, person_id=person.id- ).delete() # nosemgrep: no-direct-persons-db-orm+ delete_cohort_member(team_id=team_id, cohort_id=self.id, person_id=person.id)else:# Person not in PG - this is expected when handling CH/PG sync issueslogger.info(@@ -844,12 +904,11 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):# data exists in CH but not PG due to past sync issuesremove_person_from_static_cohort(person.uuid, self.pk, team_id=team_id)- # Update count - use write database to avoid replication lag after deletetry:count = get_static_cohort_size(cohort_id=self.id,team_id=team_id,- using_database=PERSONS_DB_FOR_WRITE,+ consistency="strong",)self.count = countself.save(update_fields=["count"])@@ -1058,11 +1117,10 @@ def cohort_people_changed(sender, instance: "CohortPeople", **kwargs):person_uuid = instance.person_idcohort = Cohort.objects.get(id=cohort_id)- # Use write database to avoid replication lag after deletecohort.count = get_static_cohort_size(cohort_id=cohort.id,team_id=cohort.team_id,- using_database=PERSONS_DB_FOR_WRITE,+ consistency="strong",)# Clear cohort_type if count exceeds the realtime thresholddiff --git a/posthog/models/cohort/test/test_cohort_personhog.py b/posthog/models/cohort/test/test_cohort_personhog.pyindex af48f8462756..091a42c7d944 100644--- a/posthog/models/cohort/test/test_cohort_personhog.py+++ b/posthog/models/cohort/test/test_cohort_personhog.py@@ -108,7 +108,11 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)assert result is True- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ if self.personhog:+ assert self._fake_client is not None+ assert (cohort.id, person.id) not in self._fake_client._cohort_members+ else:+ assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()mock_remove_ch.assert_called_once()call_args = mock_remove_ch.call_argsassert call_args[0][0] == person.uuid@@ -190,7 +194,11 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)assert result is True- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ if self.personhog:+ assert self._fake_client is not None+ assert (cohort.id, person.id) not in self._fake_client._cohort_members+ else:+ assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()mock_remove_ch.assert_called_once()@patch("posthog.models.cohort.util.remove_person_from_static_cohort")@@ -207,7 +215,7 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@parameterized_class(("personhog",), [(False,), (True,)])class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):def test_returns_true_for_member(self):- from posthog.models.person.util import check_cohort_membership, is_person_in_cohort+ from posthog.models.cohort.util import check_cohort_membership, is_person_in_cohortperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -219,7 +227,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):self._assert_personhog_called("check_cohort_membership")def test_returns_false_for_non_member(self):- from posthog.models.person.util import is_person_in_cohort+ from posthog.models.cohort.util import is_person_in_cohortperson = self._seed_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -227,7 +235,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):assert is_person_in_cohort(team_id=self.team.id, person_id=person.id, cohort_id=cohort.id) is Falsedef test_returns_empty_dict_for_empty_cohort_ids(self):- from posthog.models.person.util import check_cohort_membership+ from posthog.models.cohort.util import check_cohort_membershipperson = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -235,7 +243,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):self._assert_personhog_not_called("check_cohort_membership")def test_mixed_membership(self):- from posthog.models.person.util import check_cohort_membership+ from posthog.models.cohort.util import check_cohort_membershipperson = self._seed_person(team=self.team, distinct_ids=["d1"])c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -255,7 +263,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):of which path (personhog vs ORM) runs. Tenant scoping happens in thepublic wrapper before dispatch, so the RPC is never called forout-of-team cohort_ids."""- from posthog.models.person.util import check_cohort_membership+ from posthog.models.cohort.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -275,7 +283,7 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):"""When a mix of in-team and out-of-team cohort_ids is passed, only thein-team ones reach downstream; the caller still gets a dict keyed byevery requested id with out-of-team ones reported as non-member."""- from posthog.models.person.util import check_cohort_membership+ from posthog.models.cohort.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=self.team, distinct_ids=["d1"])@@ -295,7 +303,7 @@ class TestCheckCohortMembershipFallback(BaseTest):"""Routing test: verifies ORM fallback when the personhog gate is disabled."""def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.person.util import is_person_in_cohort+ from posthog.models.cohort.util import is_person_in_cohortperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -393,7 +401,7 @@ class TestPropertyToQStaticCohortShortCircuit(PersonhogTestMixin, BaseTest):@parameterized_class(("personhog",), [(False,), (True,)])class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):def test_returns_member_ids(self):- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idsp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -409,7 +417,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):self._assert_personhog_called("list_cohort_member_ids")def test_returns_empty_for_empty_cohort(self):- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idscohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -418,7 +426,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):assert result == []def test_excludes_non_members(self):- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idsp1 = self._seed_person(team=self.team, distinct_ids=["d1"])p2 = self._seed_person(team=self.team, distinct_ids=["d2"])@@ -434,7 +442,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):assert result == [p1.id]def test_isolates_cross_team_cohort(self):- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idsother_team = Team.objects.create(organization=self.organization)person = self._seed_person(team=other_team, distinct_ids=["d1"])@@ -450,7 +458,7 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):class TestListCohortMemberIdsFallback(BaseTest):def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idsperson = Person.objects.create(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")@@ -526,3 +534,318 @@ class TestPropertyToQStaticCohortMemberList(PersonhogTestMixin, BaseTest):matched = set(Person.objects.filter(team_id=self.team.id).filter(q).values_list("id", flat=True))assert member.id in matchedassert non_member.id not in matched+++@parameterized_class(("personhog",), [(False,), (True,)])+class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _create_static_cohort(self) -> Cohort:+ return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")++ def test_inserts_members(self):+ from posthog.models.cohort.util import insert_cohort_members++ p1 = self._seed_person(team=self.team, distinct_ids=["d1"])+ p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ cohort = self._create_static_cohort()++ inserted = insert_cohort_members(self.team.id, cohort.id, [p1.id, p2.id], version=1)++ assert inserted > 0+ if self.personhog:+ assert self._fake_client is not None+ assert (cohort.id, p1.id) in self._fake_client._cohort_members+ assert (cohort.id, p2.id) in self._fake_client._cohort_members+ else:+ assert CohortPeople.objects.filter(cohort=cohort).count() == 2+ self._assert_personhog_called("insert_cohort_members")++ def test_deduplicates_existing_members(self):+ from posthog.models.cohort.util import insert_cohort_members++ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ cohort = self._create_static_cohort()+ CohortPeople.objects.create(cohort=cohort, person=person)+ self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)++ inserted = insert_cohort_members(self.team.id, cohort.id, [person.id], version=1)++ if self.personhog:+ assert inserted == 0+ else:+ assert CohortPeople.objects.filter(cohort=cohort).count() == 1++ def test_returns_zero_for_empty_list(self):+ from posthog.models.cohort.util import insert_cohort_members++ cohort = self._create_static_cohort()++ assert insert_cohort_members(self.team.id, cohort.id, [], version=1) == 0+ self._assert_personhog_not_called("insert_cohort_members")++ def test_rejects_cross_team_cohort(self):+ from posthog.models.cohort.util import insert_cohort_members++ other_team = Team.objects.create(organization=self.organization)+ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")++ inserted = insert_cohort_members(self.team.id, other_cohort.id, [person.id], version=1)++ assert inserted == 0+ assert not CohortPeople.objects.filter(cohort=other_cohort).exists()+ self._assert_personhog_not_called("insert_cohort_members")++ def test_skip_ownership_check_bypasses_team_validation(self):+ from posthog.models.cohort.util import insert_cohort_members++ other_team = Team.objects.create(organization=self.organization)+ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")+ self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=False)++ inserted = insert_cohort_members(self.team.id, cohort.id, [person.id], version=1, _skip_ownership_check=True)++ assert inserted > 0+ self._assert_personhog_called("insert_cohort_members")+++class TestInsertCohortMembersFallback(BaseTest):+ def test_falls_back_to_orm_when_personhog_disabled(self):+ from posthog.models.cohort.util import insert_cohort_members++ person = Person.objects.create(team=self.team, distinct_ids=["d1"])+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")++ with fake_personhog_client(gate_enabled=False) as fake:+ insert_cohort_members(self.team.id, cohort.id, [person.id], version=1)++ assert CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ fake.assert_not_called("insert_cohort_members")+++@parameterized_class(("personhog",), [(False,), (True,)])+class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _create_static_cohort(self) -> Cohort:+ return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")++ def test_deletes_existing_member(self):+ from posthog.models.cohort.util import delete_cohort_member++ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ cohort = self._create_static_cohort()+ CohortPeople.objects.create(cohort=cohort, person=person)+ self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)++ result = delete_cohort_member(self.team.id, cohort.id, person.id)++ assert result is True+ if not self.personhog:+ assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ self._assert_personhog_called("delete_cohort_member")++ def test_returns_false_for_non_member(self):+ from posthog.models.cohort.util import delete_cohort_member++ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ cohort = self._create_static_cohort()++ result = delete_cohort_member(self.team.id, cohort.id, person.id)++ assert result is False++ def test_rejects_cross_team_cohort(self):+ from posthog.models.cohort.util import delete_cohort_member++ other_team = Team.objects.create(organization=self.organization)+ person = self._seed_person(team=other_team, distinct_ids=["d1"])+ other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")+ CohortPeople.objects.create(cohort=other_cohort, person=person)+ self._seed_cohort_membership(person_id=person.id, cohort_id=other_cohort.id, is_member=True)++ result = delete_cohort_member(self.team.id, other_cohort.id, person.id)++ assert result is False+ assert CohortPeople.objects.filter(cohort=other_cohort, person=person).exists()+ self._assert_personhog_not_called("delete_cohort_member")+++class TestDeleteCohortMemberFallback(BaseTest):+ def test_falls_back_to_orm_when_personhog_disabled(self):+ from posthog.models.cohort.util import delete_cohort_member++ person = Person.objects.create(team=self.team, distinct_ids=["d1"])+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")+ CohortPeople.objects.create(cohort=cohort, person=person)++ with fake_personhog_client(gate_enabled=False) as fake:+ result = delete_cohort_member(self.team.id, cohort.id, person.id)++ assert result is True+ assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ fake.assert_not_called("delete_cohort_member")+++@parameterized_class(("personhog",), [(False,), (True,)])+class TestDeleteCohortMembersBulk(PersonhogTestMixin, BaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_deletes_all_members_for_cohorts(self):+ from posthog.models.cohort.util import delete_cohort_members_bulk++ p1 = self._seed_person(team=self.team, distinct_ids=["d1"])+ p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")+ c2 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c2")+ CohortPeople.objects.create(cohort=c1, person=p1)+ CohortPeople.objects.create(cohort=c2, person=p2)+ self._seed_cohort_membership(person_id=p1.id, cohort_id=c1.id, is_member=True)+ self._seed_cohort_membership(person_id=p2.id, cohort_id=c2.id, is_member=True)++ deleted = delete_cohort_members_bulk(self.team.id, [c1.id, c2.id])++ assert deleted >= 2+ if not self.personhog:+ assert CohortPeople.objects.filter(cohort_id__in=[c1.id, c2.id]).count() == 0+ self._assert_personhog_called("delete_cohort_members_bulk")++ def test_returns_zero_for_empty_list(self):+ from posthog.models.cohort.util import delete_cohort_members_bulk++ assert delete_cohort_members_bulk(self.team.id, []) == 0+ self._assert_personhog_not_called("delete_cohort_members_bulk")+++class TestDeleteCohortMembersBulkFallback(BaseTest):+ def test_falls_back_to_orm_when_personhog_disabled(self):+ from posthog.models.cohort.util import delete_cohort_members_bulk++ person = Person.objects.create(team=self.team, distinct_ids=["d1"])+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")+ CohortPeople.objects.create(cohort=cohort, person=person)++ with fake_personhog_client(gate_enabled=False) as fake:+ deleted = delete_cohort_members_bulk(self.team.id, [cohort.id])++ assert deleted == 1+ assert not CohortPeople.objects.filter(cohort=cohort).exists()+ fake.assert_not_called("delete_cohort_members_bulk")+++class TestDeleteCohortMembersBulkMaxIterations(BaseTest):+ def test_stops_after_max_iterations(self):+ from unittest.mock import MagicMock++ from posthog.models.cohort import util as cohort_util+ from posthog.personhog_client.proto import DeleteCohortMembersBulkResponse++ mock_client = MagicMock()+ mock_client.delete_cohort_members_bulk.return_value = DeleteCohortMembersBulkResponse(deleted_count=100)++ max_iters = 5+ with (+ patch.object(cohort_util, "_DELETE_BULK_MAX_ITERATIONS", max_iters),+ patch("posthog.personhog_client.client.get_personhog_client", return_value=mock_client),+ ):+ total = cohort_util._delete_cohort_members_bulk_via_personhog([1], batch_size=100)++ assert mock_client.delete_cohort_members_bulk.call_count == max_iters+ assert total == 100 * max_iters+++@parameterized_class(("personhog",), [(False,), (True,)])+class TestCountCohortMembers(PersonhogTestMixin, BaseTest):+ def test_returns_count(self):+ from posthog.models.cohort.util import count_cohort_members++ p1 = self._seed_person(team=self.team, distinct_ids=["d1"])+ p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")+ CohortPeople.objects.create(cohort=cohort, person=p1)+ CohortPeople.objects.create(cohort=cohort, person=p2)+ self._seed_cohort_membership(person_id=p1.id, cohort_id=cohort.id, is_member=True)+ self._seed_cohort_membership(person_id=p2.id, cohort_id=cohort.id, is_member=True)++ assert count_cohort_members(self.team.id, cohort.id) == 2+ self._assert_personhog_called("count_cohort_members")++ def test_returns_zero_for_empty_cohort(self):+ from posthog.models.cohort.util import count_cohort_members++ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")++ assert count_cohort_members(self.team.id, cohort.id) == 0++ def test_isolates_cross_team_cohort(self):+ from posthog.models.cohort.util import count_cohort_members++ other_team = Team.objects.create(organization=self.organization)+ person = self._seed_person(team=other_team, distinct_ids=["d1"])+ other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")+ CohortPeople.objects.create(cohort=other_cohort, person=person)+ self._seed_cohort_membership(person_id=person.id, cohort_id=other_cohort.id, is_member=True)++ assert count_cohort_members(self.team.id, other_cohort.id) == 0+ self._assert_personhog_not_called("count_cohort_members")+++class TestCountCohortMembersFallback(BaseTest):+ def test_falls_back_to_orm_when_personhog_disabled(self):+ from posthog.models.cohort.util import count_cohort_members++ person = Person.objects.create(team=self.team, distinct_ids=["d1"])+ cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")+ CohortPeople.objects.create(cohort=cohort, person=person)++ with fake_personhog_client(gate_enabled=False) as fake:+ assert count_cohort_members(self.team.id, cohort.id) == 1++ fake.assert_not_called("count_cohort_members")+++@parameterized_class(("personhog",), [(False,), (True,)])+class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _create_static_cohort(self) -> Cohort:+ return Cohort.objects.create(team=self.team, groups=[], is_static=True, name="test cohort")++ @patch("posthog.models.cohort.util.insert_static_cohort")+ def test_insert_users_by_uuid(self, mock_insert_ch):+ p1 = self._seed_person(team=self.team, distinct_ids=["d1"])+ p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ cohort = self._create_static_cohort()++ cohort.insert_users_list_by_uuid([str(p1.uuid), str(p2.uuid)], team_id=self.team.id)++ if self.personhog:+ self._assert_personhog_called("insert_cohort_members")+ else:+ assert CohortPeople.objects.filter(cohort=cohort).count() == 2++ @patch("posthog.models.cohort.util.insert_static_cohort")+ def test_insert_users_by_distinct_id(self, mock_insert_ch):+ self._seed_person(team=self.team, distinct_ids=["d1"])+ self._seed_person(team=self.team, distinct_ids=["d2"])+ cohort = self._create_static_cohort()++ cohort.insert_users_by_list(["d1", "d2"], team_id=self.team.id)++ if self.personhog:+ self._assert_personhog_called("insert_cohort_members")+ else:+ assert CohortPeople.objects.filter(cohort=cohort).count() == 2++ @patch("posthog.models.cohort.util.insert_static_cohort")+ def test_insert_idempotent(self, mock_insert_ch):+ person = self._seed_person(team=self.team, distinct_ids=["d1"])+ cohort = self._create_static_cohort()++ cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)+ cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)++ if not self.personhog:+ assert CohortPeople.objects.filter(cohort=cohort).count() == 1diff --git a/posthog/models/cohort/test/test_util.py b/posthog/models/cohort/test/test_util.pyindex 76032d87e4bd..605068b2e6fa 100644--- a/posthog/models/cohort/test/test_util.py+++ b/posthog/models/cohort/test/test_util.py@@ -399,31 +399,22 @@ class TestCohortUtils(BaseTest):self.assertIn("allow_experimental_object_type=1", sql)self.assertIn("optimize_min_equality_disjunction_chain_length=4294967295", sql)- def test_get_static_cohort_size_uses_specified_database(self):+ def test_get_static_cohort_size_with_strong_consistency(self):cohort = _create_cohort(team=self.team, name="test_cohort", groups=[], is_static=True)- mock_qs = MagicMock()- mock_qs.filter.return_value = mock_qs- mock_qs.using.return_value = mock_qs- mock_qs.count.return_value = 42+ with patch("posthog.models.cohort.util.count_cohort_members", return_value=42) as mock_count:+ result = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id, consistency="strong")- with patch("posthog.models.cohort.util.CohortPeople.objects", mock_qs):- result = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id, using_database="test_db")-- mock_qs.using.assert_called_once_with("test_db")+ mock_count.assert_called_once_with(team_id=self.team.id, cohort_id=cohort.id, consistency="strong")self.assertEqual(result, 42)- def test_get_static_cohort_size_without_database_does_not_call_using(self):+ def test_get_static_cohort_size_defaults_to_eventual_consistency(self):cohort = _create_cohort(team=self.team, name="test_cohort", groups=[], is_static=True)- mock_qs = MagicMock()- mock_qs.filter.return_value = mock_qs- mock_qs.count.return_value = 10-- with patch("posthog.models.cohort.util.CohortPeople.objects", mock_qs):+ with patch("posthog.models.cohort.util.count_cohort_members", return_value=10) as mock_count:result = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id)- mock_qs.using.assert_not_called()+ mock_count.assert_called_once_with(team_id=self.team.id, cohort_id=cohort.id, consistency="eventual")self.assertEqual(result, 10)def test_print_cohort_hogql_query_raises_error_on_mixed_id_types_in_union(self):diff --git a/posthog/models/cohort/util.py b/posthog/models/cohort/util.pyindex 53dd9f9aff5f..2ea3949ec604 100644--- a/posthog/models/cohort/util.py+++ b/posthog/models/cohort/util.py@@ -1,8 +1,10 @@+from __future__ import annotations+import copyimport uuidfrom datetime import datetime, timedeltafrom enum import StrEnum-from typing import Any, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Optional, Union, castfrom django.conf import settingsfrom django.utils import timezone@@ -36,7 +38,7 @@ from posthog.exceptions import (from posthog.models import Action, Filter, Teamfrom posthog.models.action.util import format_action_filterfrom posthog.models.cohort.calculation_history import CohortCalculationHistory-from posthog.models.cohort.cohort import Cohort, CohortOrEmpty, CohortPeople+from posthog.models.cohort.cohort import Cohort, CohortOrEmptyfrom posthog.models.cohort.dependencies import get_cohort_dependentsfrom posthog.models.cohort.sql import (CALCULATE_COHORT_PEOPLE_SQL,@@ -54,6 +56,9 @@ from posthog.models.person.sql import ()from posthog.models.property import Property, PropertyGroupfrom posthog.queries.person_distinct_id_query import get_team_distinct_ids_query++if TYPE_CHECKING:+ from posthog.personhog_client import ReadConsistencyfrom posthog.queries.util import PersonPropertiesMode# temporary marker to denote when cohortpeople table started being populated@@ -635,13 +640,13 @@ def remove_person_from_static_cohort(person_uuid: uuid.UUID, cohort_id: int, *,)-def get_static_cohort_size(*, cohort_id: int, team_id: int, using_database: str | None = None) -> int:- qs = CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm- cohort_id=cohort_id, person__team_id=team_id- ) # nosemgrep: no-direct-persons-db-orm- if using_database:- qs = qs.using(using_database)- return qs.count()+def get_static_cohort_size(+ *,+ cohort_id: int,+ team_id: int,+ consistency: ReadConsistency = "eventual",+) -> int:+ return count_cohort_members(team_id=team_id, cohort_id=cohort_id, consistency=consistency)def recalculate_cohortpeople(@@ -1034,7 +1039,7 @@ def cohort_filters_have_values(filters_dict: dict | None) -> bool:def insert_actors_into_cohort_by_query(- cohort: "Cohort",+ cohort: Cohort,query: str,params: dict[str, Any],context: HogQLContext,@@ -1054,13 +1059,13 @@ def insert_actors_into_cohort_by_query()-def insert_cohort_query_actors_into_ch(cohort: "Cohort", *, team: "Team"):+def insert_cohort_query_actors_into_ch(cohort: Cohort, *, team: Team):context = HogQLContext(enable_select_queries=True, team_id=team.id)query = print_cohort_hogql_query(cohort, context, team=team)insert_actors_into_cohort_by_query(cohort, query, {}, context, team_id=team.id)-def build_static_cohort_filters_query(cohort: "Cohort", *, team: "Team") -> tuple[str, dict[str, Any], HogQLContext]:+def build_static_cohort_filters_query(cohort: Cohort, *, team: Team) -> tuple[str, dict[str, Any], HogQLContext]:from posthog.queries.cohort_query import CohortQuerycontext = HogQLContext(enable_select_queries=True, team_id=team.id)@@ -1078,12 +1083,12 @@ def build_static_cohort_filters_query(cohort: "Cohort", *, team: "Team") -> tuplreturn f"SELECT id AS actor_id FROM ({base_query})", params, context-def insert_cohort_filter_actors_into_ch(cohort: "Cohort", *, team: "Team"):+def insert_cohort_filter_actors_into_ch(cohort: Cohort, *, team: Team):query, params, context = build_static_cohort_filters_query(cohort, team=team)insert_actors_into_cohort_by_query(cohort, query, params, context, team_id=team.id)-def insert_cohort_people_into_pg(cohort: "Cohort", *, team_id: int):+def insert_cohort_people_into_pg(cohort: Cohort, *, team_id: int):from posthog.helpers.batch_iterators import CursorBatchIteratortag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)@@ -1113,3 +1118,349 @@ def insert_cohort_people_into_pg(cohort: "Cohort", *, team_id: int):fetch_batch, CH_PAGE_SIZE, initial_cursor="00000000-0000-0000-0000-000000000000")cohort._insert_users_list_with_batching(batch_iterator, insert_in_clickhouse=False, team_id=team_id)+++# ── Cohort membership operations (Postgres / personhog) ───────────────+++def _check_cohort_membership_via_personhog(person_id: int, cohort_ids: list[int]) -> dict[int, bool]:+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import CheckCohortMembershipRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ resp = client.check_cohort_membership(CheckCohortMembershipRequest(person_id=person_id, cohort_ids=cohort_ids))+ membership_by_cohort: dict[int, bool] = {m.cohort_id: m.is_member for m in resp.memberships}+ return {cohort_id: membership_by_cohort.get(cohort_id, False) for cohort_id in cohort_ids}+++def check_cohort_membership(team_id: int, person_id: int, cohort_ids: list[int]) -> dict[int, bool]:+ """Return ``{cohort_id: is_member}`` for the given person.++ Routes through personhog when the gate is enabled, falling back to a Django+ ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.+ Membership for cohorts the person is not in is returned as ``False`` rather+ than being omitted, so callers can index directly by cohort_id.+ """+ from posthog.models.person.util import _personhog_routed++ if not cohort_ids:+ return {}++ # Local import to avoid circulars (cohort → person via CohortPeople FK).+ from posthog.models.cohort.cohort import Cohort, CohortPeople+ from posthog.models.person.person import READ_DB_FOR_PERSONS++ # Scope cohort_ids to the team via Cohort on the default DB before querying+ # either the personhog RPC or the persons-DB CohortPeople table. Neither+ # downstream path enforces team ownership (posthog_cohortpeople has no+ # team_id column; the RPC just filters by person_id + cohort_id), so the+ # tenant boundary has to be applied here. Cohorts belonging to a different+ # team are reported as ``False`` rather than looked up. Same pattern as+ # `posthog.models.team.util.delete_bulky_postgres_data`.+ scoped_cohort_ids = list(Cohort.objects.filter(id__in=cohort_ids, team_id=team_id).values_list("id", flat=True))+ if not scoped_cohort_ids:+ return dict.fromkeys(cohort_ids, False)++ def orm_fn() -> dict[int, bool]:+ member_ids = set(+ CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm+ .filter(person_id=person_id, cohort_id__in=scoped_cohort_ids)+ .values_list("cohort_id", flat=True)+ )+ return {cohort_id: cohort_id in member_ids for cohort_id in scoped_cohort_ids}++ scoped_result = _personhog_routed(+ "check_cohort_membership",+ lambda: _check_cohort_membership_via_personhog(person_id, scoped_cohort_ids),+ orm_fn,+ team_id=team_id,+ )+ # Expand back to the caller's original cohort_ids; cohorts that were scoped+ # out (not owned by this team) register as non-member.+ return {cohort_id: scoped_result.get(cohort_id, False) for cohort_id in cohort_ids}+++def is_person_in_cohort(team_id: int, person_id: int, cohort_id: int) -> bool:+ """Convenience single-cohort variant of ``check_cohort_membership``."""+ return check_cohort_membership(team_id, person_id, [cohort_id]).get(cohort_id, False)+++_LIST_COHORT_MEMBER_IDS_PAGE_SIZE = 10_000+++def _list_cohort_member_ids_via_personhog(cohort_id: int) -> list[int]:+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import ListCohortMemberIdsRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ all_ids: list[int] = []+ cursor = 0+ while True:+ resp = client.list_cohort_member_ids(+ ListCohortMemberIdsRequest(cohort_id=cohort_id, cursor=cursor, limit=_LIST_COHORT_MEMBER_IDS_PAGE_SIZE)+ )+ all_ids.extend(resp.person_ids)+ if resp.next_cursor == 0:+ break+ cursor = resp.next_cursor+ return all_ids+++def list_cohort_member_ids(team_id: int, cohort_id: int) -> list[int]:+ """Return all person IDs belonging to a static cohort.++ Routes through personhog when the gate is enabled, falling back to a Django+ ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.+ """+ from posthog.models.cohort.cohort import Cohort, CohortPeople+ from posthog.models.person.person import READ_DB_FOR_PERSONS+ from posthog.models.person.util import _personhog_routed++ # Validate cohort ownership on the default DB before querying the persons DB+ # or the personhog RPC — neither downstream path enforces team isolation+ # (posthog_cohortpeople has no team_id column; the proto has no team_id field).+ # Same pattern as check_cohort_membership / delete_bulky_postgres_data.+ if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():+ return []++ def orm_fn() -> list[int]:+ return list(+ CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS) # nosemgrep: no-direct-persons-db-orm+ .filter(cohort_id=cohort_id)+ .values_list("person_id", flat=True)+ )++ return _personhog_routed(+ "list_cohort_member_ids",+ lambda: _list_cohort_member_ids_via_personhog(cohort_id),+ orm_fn,+ team_id=team_id,+ )+++# ── Cohort write operations ─────────────────────────────────────────+++def _insert_cohort_members_via_personhog(cohort_id: int, person_ids: list[int], version: int | None) -> int:+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import InsertCohortMembersRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ resp = client.insert_cohort_members(+ InsertCohortMembersRequest(+ cohort_id=cohort_id,+ person_ids=person_ids,+ version=version,+ )+ )+ return resp.inserted_count+++def insert_cohort_members(+ team_id: int,+ cohort_id: int,+ person_ids: list[int],+ version: int | None,+ *,+ _skip_ownership_check: bool = False,+) -> int:+ """Insert person IDs into a static cohort's PG membership table.++ Routes through personhog when the gate is enabled, falling back to a raw+ SQL INSERT against ``posthog_cohortpeople`` (on the persons DB) otherwise.+ Returns the number of newly inserted rows (duplicates are skipped).+ """+ from posthog.models.person.util import _personhog_routed++ if not person_ids:+ return 0++ from posthog.models.cohort.cohort import Cohort, CohortPeople+ from posthog.models.person import Person++ if not _skip_ownership_check and not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():+ return 0++ def orm_fn() -> int:+ from django.db import connections, router++ db_write = router.db_for_write(Person) or "default"+ cursor = connections[db_write].cursor()+ table = CohortPeople._meta.db_table+ placeholders = ",".join(["%s"] * len(person_ids))+ query = f"""+ INSERT INTO "{table}" ("person_id", "cohort_id", "version")+ SELECT pid, %s, %s+ FROM UNNEST(ARRAY[{placeholders}]) AS t(pid)+ WHERE NOT EXISTS (+ SELECT 1 FROM "{table}" AS cp+ WHERE cp."person_id" = pid AND cp."cohort_id" = %s+ )+ """+ cursor.execute(query, [cohort_id, version, *person_ids, cohort_id])+ return cursor.rowcount++ return _personhog_routed(+ "insert_cohort_members",+ lambda: _insert_cohort_members_via_personhog(cohort_id, person_ids, version),+ orm_fn,+ team_id=team_id,+ )+++def _delete_cohort_member_via_personhog(cohort_id: int, person_id: int) -> bool:+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import DeleteCohortMemberRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ resp = client.delete_cohort_member(DeleteCohortMemberRequest(cohort_id=cohort_id, person_id=person_id))+ return resp.deleted+++def delete_cohort_member(team_id: int, cohort_id: int, person_id: int) -> bool:+ """Remove a single person from a static cohort's PG membership table.++ Routes through personhog when the gate is enabled, falling back to a Django+ ORM DELETE against ``posthog_cohortpeople`` (on the persons DB) otherwise.+ Returns ``True`` if a row was deleted, ``False`` otherwise.+ """+ from posthog.models.cohort.cohort import Cohort, CohortPeople+ from posthog.models.person.util import _personhog_routed++ if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():+ return False++ def orm_fn() -> bool:+ deleted_count, _ = CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm+ cohort_id=cohort_id, person_id=person_id+ ).delete() # nosemgrep: no-direct-persons-db-orm+ return deleted_count > 0++ return _personhog_routed(+ "delete_cohort_member",+ lambda: _delete_cohort_member_via_personhog(cohort_id, person_id),+ orm_fn,+ team_id=team_id,+ )+++_DELETE_BULK_MAX_ITERATIONS = 10_000+++def _delete_cohort_members_bulk_via_personhog(cohort_ids: list[int], batch_size: int) -> int:+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import DeleteCohortMembersBulkRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ total_deleted = 0+ for _ in range(_DELETE_BULK_MAX_ITERATIONS):+ resp = client.delete_cohort_members_bulk(+ DeleteCohortMembersBulkRequest(cohort_ids=cohort_ids, batch_size=batch_size)+ )+ total_deleted += resp.deleted_count+ if resp.deleted_count < batch_size:+ break+ else:+ logger.error(+ "delete_cohort_members_bulk_max_iterations",+ cohort_ids=cohort_ids,+ total_deleted=total_deleted,+ max_iterations=_DELETE_BULK_MAX_ITERATIONS,+ )+ return total_deleted+++def delete_cohort_members_bulk(team_id: int, cohort_ids: list[int], batch_size: int = 10_000) -> int:+ """Delete all PG cohort membership rows for the given cohort IDs.++ Routes through personhog when the gate is enabled, falling back to the+ Django ORM ``_raw_delete`` against ``posthog_cohortpeople`` otherwise.+ Returns the total number of deleted rows.+ """+ from posthog.models.person.util import _personhog_routed++ if not cohort_ids:+ return 0++ from posthog.models.cohort.cohort import CohortPeople++ def orm_fn() -> int:+ from django.db import router++ qs = CohortPeople.objects.filter(cohort_id__in=cohort_ids) # nosemgrep: no-direct-persons-db-orm+ db_alias = router.db_for_write(CohortPeople)+ return qs._raw_delete(db_alias)++ return _personhog_routed(+ "delete_cohort_members_bulk",+ lambda: _delete_cohort_members_bulk_via_personhog(cohort_ids, batch_size),+ orm_fn,+ team_id=team_id,+ )+++def _count_cohort_members_via_personhog(cohort_ids: list[int], consistency: ReadConsistency) -> int:+ from posthog.personhog_client import consistency_to_read_options+ from posthog.personhog_client.client import get_personhog_client+ from posthog.personhog_client.proto import CountCohortMembersRequest++ client = get_personhog_client()+ if client is None:+ raise RuntimeError("personhog client not configured")++ resp = client.count_cohort_members(+ CountCohortMembersRequest(+ cohort_ids=cohort_ids,+ read_options=consistency_to_read_options(consistency),+ )+ )+ return resp.count+++def count_cohort_members(team_id: int, cohort_id: int, *, consistency: ReadConsistency = "eventual") -> int:+ """Return the number of persons in a static cohort.++ Routes through personhog when the gate is enabled, falling back to a Django+ ORM COUNT against ``posthog_cohortpeople`` (on the persons DB) otherwise.++ Use ``consistency="strong"`` when reading immediately after a write+ (e.g. after inserting or deleting cohort members) to avoid stale counts+ from replication lag (ORM) or eventual consistency (personhog).+ """+ from posthog.models.cohort.cohort import Cohort, CohortPeople+ from posthog.models.person.util import _personhog_routed++ if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():+ return 0++ def orm_fn() -> int:+ qs = CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm+ cohort_id=cohort_id, person__team_id=team_id+ )+ if consistency == "strong":+ from posthog.person_db_router import PERSONS_DB_FOR_WRITE++ qs = qs.using(PERSONS_DB_FOR_WRITE)+ return qs.count()++ return _personhog_routed(+ "count_cohort_members",+ lambda: _count_cohort_members_via_personhog([cohort_id], consistency),+ orm_fn,+ team_id=team_id,+ )diff --git a/posthog/models/person/test/test_util_personhog_routing.py b/posthog/models/person/test/test_util_personhog_routing.pyindex 6f30b06229cc..118473a7ea7d 100644--- a/posthog/models/person/test/test_util_personhog_routing.py+++ b/posthog/models/person/test/test_util_personhog_routing.py@@ -317,17 +317,18 @@ class TestGetPersonsByUuidsRouting(SimpleTestCase):mock_qs = MagicMock()mock_objects.db_manager.return_value.filter.return_value = mock_qs- team = MagicMock()- team.pk = 1+ team_id = 1uuids = ["uuid-1", "uuid-2"]- result = get_persons_by_uuids(team, uuids)+ result = get_persons_by_uuids(team_id, uuids)if personhog_data is not None and gate_on:assert result == personhog_data+ mock_fetch_personhog.assert_called_once_with(team_id, uuids)mock_objects.db_manager.assert_not_called()else:assert result == mock_qs+ mock_objects.db_manager.return_value.filter.assert_called_with(team_id=team_id, uuid__in=uuids)mock_routing_counter.labels.assert_called_with(operation="get_persons_by_uuids", source=expected_source, client_name="posthog-django"diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex eb0e4e083a8c..cadfeb463313 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -26,7 +26,6 @@ from posthog.models.person.sql import (INSERT_PERSON_SQL,)from posthog.models.signals import mutable_receiver-from posthog.models.team import Teamfrom posthog.models.utils import UUIDTfrom posthog.personhog_client.converters import proto_person_to_modelfrom posthog.personhog_client.metrics import (@@ -36,7 +35,6 @@ from posthog.personhog_client.metrics import (get_client_name,)from posthog.personhog_client.proto import (- CheckCohortMembershipRequest,DeletePersonsRequest,GetDistinctIdsForPersonRequest,GetDistinctIdsForPersonsRequest,@@ -45,7 +43,6 @@ from posthog.personhog_client.proto import (GetPersonRequest,GetPersonsByDistinctIdsInTeamRequest,GetPersonsByUuidsRequest,- ListCohortMemberIdsRequest,)from posthog.settings import TEST@@ -446,16 +443,16 @@ def _fetch_persons_by_uuids_via_personhog(team_id: int, uuids: list[str]) -> lisreturn [proto_person_to_model(p, distinct_ids=distinct_ids_by_person.get(p.id, [])) for p in valid_persons]-def get_persons_by_uuids(team: Team, uuids: list[str]) -> QuerySet | list[Person]:- personhog_fn: Callable[[], QuerySet | list[Person]] = lambda: _fetch_persons_by_uuids_via_personhog(team.pk, uuids)+def get_persons_by_uuids(team_id: int, uuids: list[str]) -> QuerySet | list[Person]:+ personhog_fn: Callable[[], QuerySet | list[Person]] = lambda: _fetch_persons_by_uuids_via_personhog(team_id, uuids)orm_fn: Callable[[], QuerySet | list[Person]] = lambda: Person.objects.db_manager(READ_DB_FOR_PERSONS).filter(- team_id=team.pk, uuid__in=uuids+ team_id=team_id, uuid__in=uuids)return _personhog_routed("get_persons_by_uuids",personhog_fn,orm_fn,- team_id=team.pk,+ team_id=team_id,)@@ -560,120 +557,6 @@ def get_person_by_distinct_id(team_id: int, distinct_id: str) -> Optional[Person)-def _check_cohort_membership_via_personhog(person_id: int, cohort_ids: list[int]) -> dict[int, bool]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")-- resp = client.check_cohort_membership(CheckCohortMembershipRequest(person_id=person_id, cohort_ids=cohort_ids))- membership_by_cohort: dict[int, bool] = {m.cohort_id: m.is_member for m in resp.memberships}- return {cohort_id: membership_by_cohort.get(cohort_id, False) for cohort_id in cohort_ids}---def check_cohort_membership(team_id: int, person_id: int, cohort_ids: list[int]) -> dict[int, bool]:- """Return ``{cohort_id: is_member}`` for the given person.-- Routes through personhog when the gate is enabled, falling back to a Django- ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.- Membership for cohorts the person is not in is returned as ``False`` rather- than being omitted, so callers can index directly by cohort_id.- """- if not cohort_ids:- return {}-- # Local import to avoid circulars (cohort → person via CohortPeople FK).- from posthog.models.cohort.cohort import Cohort, CohortPeople-- # Scope cohort_ids to the team via Cohort on the default DB before querying- # either the personhog RPC or the persons-DB CohortPeople table. Neither- # downstream path enforces team ownership (posthog_cohortpeople has no- # team_id column; the RPC just filters by person_id + cohort_id), so the- # tenant boundary has to be applied here. Cohorts belonging to a different- # team are reported as ``False`` rather than looked up. Same pattern as- # `posthog.models.team.util.delete_bulky_postgres_data`.- scoped_cohort_ids = list(Cohort.objects.filter(id__in=cohort_ids, team_id=team_id).values_list("id", flat=True))- if not scoped_cohort_ids:- return dict.fromkeys(cohort_ids, False)-- def orm_fn() -> dict[int, bool]:- member_ids = set(- CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(person_id=person_id, cohort_id__in=scoped_cohort_ids)- .values_list("cohort_id", flat=True)- )- return {cohort_id: cohort_id in member_ids for cohort_id in scoped_cohort_ids}-- scoped_result = _personhog_routed(- "check_cohort_membership",- lambda: _check_cohort_membership_via_personhog(person_id, scoped_cohort_ids),- orm_fn,- team_id=team_id,- )- # Expand back to the caller's original cohort_ids; cohorts that were scoped- # out (not owned by this team) register as non-member.- return {cohort_id: scoped_result.get(cohort_id, False) for cohort_id in cohort_ids}---def is_person_in_cohort(team_id: int, person_id: int, cohort_id: int) -> bool:- """Convenience single-cohort variant of ``check_cohort_membership``."""- return check_cohort_membership(team_id, person_id, [cohort_id]).get(cohort_id, False)---_LIST_COHORT_MEMBER_IDS_PAGE_SIZE = 10_000---def _list_cohort_member_ids_via_personhog(cohort_id: int) -> list[int]:- from posthog.personhog_client.client import get_personhog_client-- client = get_personhog_client()- if client is None:- raise RuntimeError("personhog client not configured")-- all_ids: list[int] = []- cursor = 0- while True:- resp = client.list_cohort_member_ids(- ListCohortMemberIdsRequest(cohort_id=cohort_id, cursor=cursor, limit=_LIST_COHORT_MEMBER_IDS_PAGE_SIZE)- )- all_ids.extend(resp.person_ids)- if resp.next_cursor == 0:- break- cursor = resp.next_cursor- return all_ids---def list_cohort_member_ids(team_id: int, cohort_id: int) -> list[int]:- """Return all person IDs belonging to a static cohort.-- Routes through personhog when the gate is enabled, falling back to a Django- ORM query against ``posthog_cohortpeople`` (on the persons DB) otherwise.- """- from posthog.models.cohort.cohort import Cohort, CohortPeople-- # Validate cohort ownership on the default DB before querying the persons DB- # or the personhog RPC — neither downstream path enforces team isolation- # (posthog_cohortpeople has no team_id column; the proto has no team_id field).- # Same pattern as check_cohort_membership / delete_bulky_postgres_data.- if not Cohort.objects.filter(id=cohort_id, team_id=team_id).exists():- return []-- def orm_fn() -> list[int]:- return list(- CohortPeople.objects.db_manager(READ_DB_FOR_PERSONS)- .filter(cohort_id=cohort_id)- .values_list("person_id", flat=True)- )-- return _personhog_routed(- "list_cohort_member_ids",- lambda: _list_cohort_member_ids_via_personhog(cohort_id),- orm_fn,- team_id=team_id,- )--def get_person_by_pk_or_uuid(team_id: int, key: str) -> Optional[Person]:"""Look up a person by UUID or integer PK, routing through personhog when enabled."""try:diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex de48d613c29e..bc838a6962ae 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -456,10 +456,12 @@'__module__','__repr__','__str__',+ '_get_existing_ch_member_uuids','_get_uuids_for_distinct_ids_batch','_get_uuids_for_emails_batch','_get_uuids_for_emails_batch_ch','_get_uuids_for_emails_batch_pg',+ '_insert_batch_via_personhog','_insert_users_list_with_batching','_meta','_safe_reset_calculating_state',diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex bc56c076b154..cf1c8762a88d 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -25,7 +25,7 @@ actions_that_require_current_team = [def delete_bulky_postgres_data(team_ids: list[int]):"Efficiently delete large tables for teams from postgres. Using normal CASCADE delete here can time out"- from posthog.models.cohort import Cohort, CohortPeople+ from posthog.models.cohort import Cohortfrom posthog.models.feature_flag.feature_flag import FeatureFlagHashKeyOverridefrom posthog.models.insight_caching_state import InsightCachingStatefrom posthog.models.person import PersonlessDistinctId@@ -46,7 +46,8 @@ def delete_bulky_postgres_data(team_ids: list[int]):# Get cohort_ids from the default database first to avoid cross-database join# CohortPeople is in persons_db, Cohort is in default dbcohort_ids = list(Cohort.objects.filter(team_id__in=team_ids).values_list("id", flat=True))- _raw_delete(CohortPeople.objects.filter(cohort_id__in=cohort_ids)) # nosemgrep: no-direct-persons-db-orm+ if cohort_ids:+ _delete_cohort_members_for_teams(team_ids, cohort_ids)_raw_delete(FeatureFlagHashKeyOverride.objects.filter(team_id__in=team_ids)) # nosemgrep: no-direct-persons-db-orm_delete_groups_for_teams(team_ids)@@ -170,6 +171,21 @@ def _delete_group_type_mappings_for_teams(team_ids: list[int]) -> None:_raw_delete(GroupTypeMapping.objects.filter(team_id=team_id)) # nosemgrep: no-direct-persons-db-orm+def _delete_cohort_members_for_teams(team_ids: list[int], cohort_ids: list[int]) -> None:+ """Delete CohortPeople rows for teams via personhog RPC.++ Falls back to ORM _raw_delete when personhog is not available.+ Routes per-team for consistent gate/metrics/fallback behavior.+ """+ from posthog.models.cohort import Cohort+ from posthog.models.cohort.util import delete_cohort_members_bulk++ for team_id in team_ids:+ team_cohort_ids = list(Cohort.objects.filter(team_id=team_id, id__in=cohort_ids).values_list("id", flat=True))+ if team_cohort_ids:+ delete_cohort_members_bulk(team_id, team_cohort_ids)++def _raw_delete(queryset: Any):"Issues a single DELETE statement for the queryset"from django.db import routerdiff --git a/posthog/personhog_client/__init__.py b/posthog/personhog_client/__init__.pyindex e69de29bb2d1..ab251d55d1d7 100644--- a/posthog/personhog_client/__init__.py+++ b/posthog/personhog_client/__init__.py@@ -0,0 +1,10 @@+from typing import Literal++from posthog.personhog_client.proto import CONSISTENCY_LEVEL_EVENTUAL, CONSISTENCY_LEVEL_STRONG, ReadOptions++ReadConsistency = Literal["strong", "eventual"]+++def consistency_to_read_options(consistency: ReadConsistency) -> ReadOptions:+ level = CONSISTENCY_LEVEL_STRONG if consistency == "strong" else CONSISTENCY_LEVEL_EVENTUAL+ return ReadOptions(consistency=level)diff --git a/posthog/queries/base.py b/posthog/queries/base.pyindex 84ca3bbe5473..4be6ce9e4bea 100644--- a/posthog/queries/base.py+++ b/posthog/queries/base.py@@ -350,7 +350,7 @@ def property_to_Q(# falling back to the persons-DB ORM otherwise. Mirrors the override# short-circuit below (returning Q(pk__isnull=False|True)).if person_id is not None and team_id is not None:- from posthog.models.person.util import is_person_in_cohort+ from posthog.models.cohort.util import is_person_in_cohortif is_person_in_cohort(team_id=team_id, person_id=person_id, cohort_id=cohort_id):return Q(pk__isnull=False)@@ -362,7 +362,7 @@ def property_to_Q(# the Exists(CohortPeople) subquery so the persons DB is not# required on the personhog path.if team_id is not None:- from posthog.models.person.util import list_cohort_member_ids+ from posthog.models.cohort.util import list_cohort_member_idsmember_ids = list_cohort_member_ids(team_id=team_id, cohort_id=cohort_id)if not member_ids: