:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(clickhouse): add person-group membership storage (#109512)
Arthur Moreira de Deus296a008ace20
diff --git a/posthog/clickhouse/hcl/golden/dev/auxiliary.hcl b/posthog/clickhouse/hcl/golden/dev/auxiliary.hclindex 4f63aa0bd560..30c5cb737cb1 100644--- a/posthog/clickhouse/hcl/golden/dev/auxiliary.hcl+++ b/posthog/clickhouse/hcl/golden/dev/auxiliary.hcl@@ -1082,6 +1082,30 @@ database "posthog" {}}+ table "person_group_membership_config" {+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+table "platform_alert_events" {column "team_id" {type = "Int64"@@ -2269,6 +2293,42 @@ database "posthog" {}}+ table "sharded_person_group_membership" {+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ settings = {+ index_granularity = "8192"+ min_bytes_for_wide_part = "0"+ min_rows_for_wide_part = "0"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }+table "sharded_platform_alert_events" {primary_key = ["team_id", "configuration_id", "alert_id", "occurred_at"]order_by = ["team_id", "configuration_id", "alert_id", "occurred_at", "evaluation_key"]diff --git a/posthog/clickhouse/hcl/golden/dev/data.hcl b/posthog/clickhouse/hcl/golden/dev/data.hclindex 2362a619da77..552acc8323a2 100644--- a/posthog/clickhouse/hcl/golden/dev/data.hcl+++ b/posthog/clickhouse/hcl/golden/dev/data.hcl@@ -778,6 +778,27 @@ database "posthog" {}}+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "distributed_posthog_document_embeddings" {column "team_id" {type = "Int64"@@ -2824,6 +2845,33 @@ database "posthog" {}}+ table "person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "person_overrides" {order_by = ["team_id", "old_person_id"]partition_by = "toYYYYMM(oldest_event)"diff --git a/posthog/clickhouse/hcl/golden/local-multi/auxiliary.hcl b/posthog/clickhouse/hcl/golden/local-multi/auxiliary.hclindex 19c7a65d2c53..74ae82666513 100644--- a/posthog/clickhouse/hcl/golden/local-multi/auxiliary.hcl+++ b/posthog/clickhouse/hcl/golden/local-multi/auxiliary.hcl@@ -1125,6 +1125,30 @@ database "posthog" {}}+ table "person_group_membership_config" {+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+table "platform_alert_events" {column "team_id" {type = "Int64"@@ -2276,6 +2300,42 @@ database "posthog" {}}+ table "sharded_person_group_membership" {+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ settings = {+ index_granularity = "8192"+ min_bytes_for_wide_part = "0"+ min_rows_for_wide_part = "0"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }+table "sharded_platform_alert_events" {primary_key = ["team_id", "configuration_id", "alert_id", "occurred_at"]order_by = ["team_id", "configuration_id", "alert_id", "occurred_at", "evaluation_key"]diff --git a/posthog/clickhouse/hcl/golden/local-multi/data.hcl b/posthog/clickhouse/hcl/golden/local-multi/data.hclindex db376ec4a1a9..86dcfa596dec 100644--- a/posthog/clickhouse/hcl/golden/local-multi/data.hcl+++ b/posthog/clickhouse/hcl/golden/local-multi/data.hcl@@ -752,6 +752,27 @@ database "posthog" {}}+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "distributed_posthog_document_embeddings" {column "team_id" {type = "Int64"@@ -3253,6 +3274,33 @@ database "posthog" {}}+ table "person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "person_overrides" {order_by = ["team_id", "old_person_id"]partition_by = "toYYYYMM(oldest_event)"diff --git a/posthog/clickhouse/hcl/golden/local-multi/ingestion_small.hcl b/posthog/clickhouse/hcl/golden/local-multi/ingestion_small.hclindex 0fa3a346fe2b..0550326be3d4 100644--- a/posthog/clickhouse/hcl/golden/local-multi/ingestion_small.hcl+++ b/posthog/clickhouse/hcl/golden/local-multi/ingestion_small.hcl@@ -8,6 +8,27 @@ node "small" {}database "posthog" {+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "kafka_app_metrics" {column "team_id" {type = "Int64"@@ -1632,6 +1653,33 @@ database "posthog" {}}+ table "writable_person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "writable_plugin_log_entries" {column "id" {type = "UUID"@@ -2927,6 +2975,31 @@ SQLtype = "AggregateFunction(sum, UInt64)"}}++ dictionary "person_group_membership_config_dict" {+ primary_key = ["team_id"]+ lifetime {+ min = 60+ max = 120+ }+ attribute "team_id" {+ type = "Int64"+ }+ attribute "group_type_index" {+ type = "UInt8"+ default = "255"+ }+ attribute "enabled" {+ type = "UInt8"+ default = "0"+ }+ source "clickhouse" {+ user = "default"+ query = "SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4"+ }+ layout "complex_key_hashed" {+ }+ }}named_collection "msk_cluster" {diff --git a/posthog/clickhouse/hcl/golden/local-single/all.hcl b/posthog/clickhouse/hcl/golden/local-single/all.hclindex 3af04d1ac906..222ec4139de4 100644--- a/posthog/clickhouse/hcl/golden/local-single/all.hcl+++ b/posthog/clickhouse/hcl/golden/local-single/all.hcl@@ -779,6 +779,27 @@ database "posthog" {}}+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "distributed_posthog_document_embeddings" {column "team_id" {type = "Int64"@@ -8416,6 +8437,57 @@ SQL}}+ table "person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }++ table "person_group_membership_config" {+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+table "person_overrides" {order_by = ["team_id", "old_person_id"]partition_by = "toYYYYMM(oldest_event)"@@ -12360,6 +12432,42 @@ SQL}}+ table "sharded_person_group_membership" {+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ settings = {+ index_granularity = "8192"+ min_bytes_for_wide_part = "0"+ min_rows_for_wide_part = "0"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }+table "sharded_platform_alert_events" {primary_key = ["team_id", "configuration_id", "alert_id", "occurred_at"]order_by = ["team_id", "configuration_id", "alert_id", "occurred_at", "evaluation_key"]@@ -17988,6 +18096,33 @@ SQL}}+ table "writable_person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "writable_plugin_log_entries" {column "id" {type = "UUID"@@ -26038,6 +26173,31 @@ SQL}}+ dictionary "person_group_membership_config_dict" {+ primary_key = ["team_id"]+ lifetime {+ min = 60+ max = 120+ }+ attribute "team_id" {+ type = "Int64"+ }+ attribute "group_type_index" {+ type = "UInt8"+ default = "255"+ }+ attribute "enabled" {+ type = "UInt8"+ default = "0"+ }+ source "clickhouse" {+ user = "default"+ query = "SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4"+ }+ layout "complex_key_hashed" {+ }+ }+dictionary "person_overrides_dict" {primary_key = ["team_id", "old_person_id"]lifetime {diff --git a/posthog/clickhouse/hcl/golden/prod-eu/auxiliary.hcl b/posthog/clickhouse/hcl/golden/prod-eu/auxiliary.hclindex 47adb199dac0..1237db2d847b 100644--- a/posthog/clickhouse/hcl/golden/prod-eu/auxiliary.hcl+++ b/posthog/clickhouse/hcl/golden/prod-eu/auxiliary.hcl@@ -1082,6 +1082,30 @@ database "posthog" {}}+ table "person_group_membership_config" {+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+table "platform_alert_events" {column "team_id" {type = "Int64"@@ -2269,6 +2293,42 @@ database "posthog" {}}+ table "sharded_person_group_membership" {+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ settings = {+ index_granularity = "8192"+ min_bytes_for_wide_part = "0"+ min_rows_for_wide_part = "0"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }+table "sharded_platform_alert_events" {primary_key = ["team_id", "configuration_id", "alert_id", "occurred_at"]order_by = ["team_id", "configuration_id", "alert_id", "occurred_at", "evaluation_key"]diff --git a/posthog/clickhouse/hcl/golden/prod-eu/data.hcl b/posthog/clickhouse/hcl/golden/prod-eu/data.hclindex 3395ee31f2b8..bfdf6e969f40 100644--- a/posthog/clickhouse/hcl/golden/prod-eu/data.hcl+++ b/posthog/clickhouse/hcl/golden/prod-eu/data.hcl@@ -763,6 +763,27 @@ database "posthog" {}}+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "distributed_posthog_document_embeddings" {column "team_id" {type = "Int64"@@ -3568,6 +3589,33 @@ database "posthog" {}}+ table "person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "person_overrides" {order_by = ["team_id", "old_person_id"]partition_by = "toYYYYMM(oldest_event)"diff --git a/posthog/clickhouse/hcl/golden/prod-us/auxiliary.hcl b/posthog/clickhouse/hcl/golden/prod-us/auxiliary.hclindex 67837fb73f4b..adcf11dfb2e7 100644--- a/posthog/clickhouse/hcl/golden/prod-us/auxiliary.hcl+++ b/posthog/clickhouse/hcl/golden/prod-us/auxiliary.hcl@@ -1120,6 +1120,30 @@ database "posthog" {}}+ table "person_group_membership_config" {+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+table "platform_alert_events" {column "team_id" {type = "Int64"@@ -2307,6 +2331,42 @@ database "posthog" {}}+ table "sharded_person_group_membership" {+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ settings = {+ index_granularity = "8192"+ min_bytes_for_wide_part = "0"+ min_rows_for_wide_part = "0"+ }+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }+table "sharded_platform_alert_events" {primary_key = ["team_id", "configuration_id", "alert_id", "occurred_at"]order_by = ["team_id", "configuration_id", "alert_id", "occurred_at", "evaluation_key"]diff --git a/posthog/clickhouse/hcl/golden/prod-us/data.hcl b/posthog/clickhouse/hcl/golden/prod-us/data.hclindex ae59d2566f11..0de7eba5e432 100644--- a/posthog/clickhouse/hcl/golden/prod-us/data.hcl+++ b/posthog/clickhouse/hcl/golden/prod-us/data.hcl@@ -856,6 +856,27 @@ database "posthog" {}}+ table "distributed_person_group_membership_config" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+table "distributed_posthog_document_embeddings" {column "team_id" {type = "Int64"@@ -3339,6 +3360,33 @@ database "posthog" {}}+ table "person_group_membership" {+ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+table "person_overrides" {order_by = ["team_id", "old_person_id"]partition_by = "toYYYYMM(oldest_event)"diff --git a/posthog/clickhouse/hcl/manifest.hcl b/posthog/clickhouse/hcl/manifest.hclindex 6d9fdc8de6de..7ffd9994ab1e 100644--- a/posthog/clickhouse/hcl/manifest.hcl+++ b/posthog/clickhouse/hcl/manifest.hcl@@ -118,10 +118,10 @@ role "batch_exports" {# columns per env that are added out-of-band and churn constantly, so their goldens# live in PostHog/posthog-cloud-infra (clickhouse/hcl/), not the OSS gate.role "data" {- env "dev" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/coshared/log_entries_write", "roles/data/dev"] }- env "prod-us" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/data/prod", "roles/data/prod-us"] }- env "prod-eu" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/coshared/log_entries_write", "roles/data/prod", "roles/data/prod-eu"] }- env "local-multi" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/ai_events_data", "roles/coshared/tophog", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/batch_exports_data", "roles/coshared/ingestion_warnings_store", "roles/coshared/events_json_write", "roles/coshared/log_entries_write", "roles/coshared/session_replay_write", "roles/data/shared", "roles/data/common", "roles/data/local"] }+ env "dev" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/coshared/person_group_membership_config", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/coshared/log_entries_write", "roles/data/dev"] }+ env "prod-us" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/coshared/person_group_membership_config", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/data/prod", "roles/data/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/custom_metrics", "roles/coshared/ai_events_data", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/session_replay_write", "roles/coshared/person_group_membership_config", "roles/data/shared", "roles/data/common", "roles/data/cloud", "roles/coshared/log_entries_write", "roles/data/prod", "roles/data/prod-eu"] }+ env "local-multi" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/sessions_data", "roles/coshared/ai_events_data", "roles/coshared/tophog", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/batch_exports_data", "roles/coshared/ingestion_warnings_store", "roles/coshared/events_json_write", "roles/coshared/log_entries_write", "roles/coshared/session_replay_write", "roles/coshared/person_group_membership_config", "roles/data/shared", "roles/data/common", "roles/data/local"] }}# INGESTION satellites: the Kafka consumer layer. Each node carries the kafka_* engine@@ -134,7 +134,7 @@ role "events" {}role "small" {- env "local-multi" { layers = ["roles/shared/qla.hcl", "roles/coshared/named_collections", "roles/coshared/aux_small", "roles/coshared/log_entries_write", "roles/coshared/log_entries_aux_write", "roles/coshared/session_replay_write", "roles/ingestion_small/local"] }+ env "local-multi" { layers = ["roles/shared/qla.hcl", "roles/shared/person_group_membership.hcl", "roles/coshared/person_group_membership_config", "roles/ingestion_small/shared", "roles/coshared/named_collections", "roles/coshared/aux_small", "roles/coshared/log_entries_write", "roles/coshared/log_entries_aux_write", "roles/coshared/session_replay_write", "roles/ingestion_small/local"] }}role "medium" {@@ -146,7 +146,7 @@ role "medium" {# and not MULTINODE_CLICKHOUSE. Composed as the deduped union of the local-multi stacks it# hosts, so any name two of those roles declare fails this load instead of drifting.role "all" {- env "local-single" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/apm_ingest", "roles/coshared/logs_avro_ingest", "roles/coshared/custom_metrics", "roles/ops/shared", "roles/ops/local", "roles/logs/base", "roles/logs/traces", "roles/logs/traces_kafka_metrics", "roles/logs/metrics", "roles/logs/local", "roles/apm/shared", "roles/apm/local", "roles/coshared/ai_events_data", "roles/ai_events/shared", "roles/ai_events/local", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/aux_small", "roles/auxiliary/shared", "roles/auxiliary/local", "roles/coshared/sessions_data", "roles/coshared/tophog", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/batch_exports_data", "roles/coshared/ingestion_warnings_store", "roles/coshared/events_json_write", "roles/coshared/log_entries_write", "roles/coshared/log_entries_aux_write", "roles/coshared/session_replay_write", "roles/data/shared", "roles/data/common", "roles/data/local", "roles/ingestion_events/local", "roles/ingestion_events/local-single", "roles/ingestion_small/local", "roles/ingestion_medium/local"] }+ env "local-single" { layers = ["roles/shared", "roles/coshared/named_collections", "roles/coshared/apm_ingest", "roles/coshared/logs_avro_ingest", "roles/coshared/custom_metrics", "roles/ops/shared", "roles/ops/local", "roles/logs/base", "roles/logs/traces", "roles/logs/traces_kafka_metrics", "roles/logs/metrics", "roles/logs/local", "roles/apm/shared", "roles/apm/local", "roles/coshared/ai_events_data", "roles/ai_events/shared", "roles/ai_events/local", "roles/coshared/aux_data", "roles/coshared/log_entries_aux", "roles/coshared/aux_small", "roles/auxiliary/shared", "roles/auxiliary/local", "roles/coshared/sessions_data", "roles/coshared/tophog", "roles/coshared/events_recent", "roles/coshared/events_recent_write", "roles/coshared/batch_exports_data", "roles/coshared/ingestion_warnings_store", "roles/coshared/events_json_write", "roles/coshared/log_entries_write", "roles/coshared/log_entries_aux_write", "roles/coshared/session_replay_write", "roles/coshared/person_group_membership_config", "roles/ingestion_small/shared", "roles/data/shared", "roles/data/common", "roles/data/local", "roles/ingestion_events/local", "roles/ingestion_events/local-single", "roles/ingestion_small/local", "roles/ingestion_medium/local"] }}# role "endpoints" {diff --git a/posthog/clickhouse/hcl/roles/auxiliary/shared/person_group_membership.hcl b/posthog/clickhouse/hcl/roles/auxiliary/shared/person_group_membership.hclnew file mode 100644index 000000000000..1fa87ebd8b93--- /dev/null+++ b/posthog/clickhouse/hcl/roles/auxiliary/shared/person_group_membership.hcl@@ -0,0 +1,33 @@+database "posthog" {+ table "sharded_person_group_membership" {+ extend = "_person_group_membership"+ order_by = ["team_id", "group_type_index", "group_key", "distinct_id"]+ index "idx_distinct_id" {+ expr = "distinct_id"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ settings = {+ index_granularity = "8192"+ min_rows_for_wide_part = "0"+ min_bytes_for_wide_part = "0"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.sharded_person_group_membership"+ replica_name = "{replica}"+ }+ }++ table "person_group_membership_config" {+ extend = "_person_group_membership_config"+ order_by = ["team_id"]+ settings = {+ index_granularity = "8192"+ }+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.person_group_membership_config"+ replica_name = "{replica}-{shard}"+ version_column = "version"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/coshared/person_group_membership_config/tables.hcl b/posthog/clickhouse/hcl/roles/coshared/person_group_membership_config/tables.hclnew file mode 100644index 000000000000..8385cbb0159a--- /dev/null+++ b/posthog/clickhouse/hcl/roles/coshared/person_group_membership_config/tables.hcl@@ -0,0 +1,11 @@+database "posthog" {+ table "distributed_person_group_membership_config" {+ extend = "_person_group_membership_config"+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "person_group_membership_config"+ sharding_key = "sipHash64(team_id)"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/data/common/person_group_membership.hcl b/posthog/clickhouse/hcl/roles/data/common/person_group_membership.hclnew file mode 100644index 000000000000..5581df33adf6--- /dev/null+++ b/posthog/clickhouse/hcl/roles/data/common/person_group_membership.hcl@@ -0,0 +1,11 @@+database "posthog" {+ table "person_group_membership" {+ extend = "_person_group_membership"+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/ingestion_small/local/person_group_membership.hcl b/posthog/clickhouse/hcl/roles/ingestion_small/local/person_group_membership.hclnew file mode 100644index 000000000000..d3aa09b2be2c--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ingestion_small/local/person_group_membership.hcl@@ -0,0 +1,8 @@+database "posthog" {+ patch_dictionary "person_group_membership_config_dict" {+ source "clickhouse" {+ user = "default"+ query = "SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/ingestion_small/shared/person_group_membership.hcl b/posthog/clickhouse/hcl/roles/ingestion_small/shared/person_group_membership.hclnew file mode 100644index 000000000000..cd426704d328--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ingestion_small/shared/person_group_membership.hcl@@ -0,0 +1,36 @@+database "posthog" {+ table "writable_person_group_membership" {+ extend = "_person_group_membership"+ engine "distributed" {+ cluster_name = "aux"+ remote_database = "posthog"+ remote_table = "sharded_person_group_membership"+ sharding_key = "sipHash64(team_id, group_type_index, group_key)"+ }+ }++ dictionary "person_group_membership_config_dict" {+ primary_key = ["team_id"]+ lifetime {+ min = 60+ max = 120+ }+ attribute "team_id" {+ type = "Int64"+ }+ attribute "group_type_index" {+ type = "UInt8"+ default = "255"+ }+ attribute "enabled" {+ type = "UInt8"+ default = "0"+ }+ source "clickhouse" {+ user = "dict_reader"+ query = "SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4"+ }+ layout "complex_key_hashed" {+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/shared/person_group_membership.hcl b/posthog/clickhouse/hcl/roles/shared/person_group_membership.hclnew file mode 100644index 000000000000..ea006944b93a--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/person_group_membership.hcl@@ -0,0 +1,41 @@+database "posthog" {+ table "_person_group_membership" {+ abstract = true++ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "group_key" {+ type = "String"+ }+ column "distinct_id" {+ type = "String"+ }+ column "first_seen" {+ type = "SimpleAggregateFunction(min, DateTime64(6, 'UTC'))"+ }+ column "last_seen" {+ type = "SimpleAggregateFunction(max, DateTime64(6, 'UTC'))"+ }+ }++ table "_person_group_membership_config" {+ abstract = true++ column "team_id" {+ type = "Int64"+ }+ column "group_type_index" {+ type = "UInt8"+ }+ column "enabled" {+ type = "UInt8"+ }+ column "version" {+ type = "UInt64"+ }+ }+}diff --git a/posthog/clickhouse/hcl/sql/dev/auxiliary.sql b/posthog/clickhouse/hcl/sql/dev/auxiliary.sqlindex 46acdebecd9c..76ddbbe62380 100644--- a/posthog/clickhouse/hcl/sql/dev/auxiliary.sql+++ b/posthog/clickhouse/hcl/sql/dev/auxiliary.sql@@ -167,6 +167,12 @@ CREATE TABLE posthog.message_assets_data (INDEX person_id_idx person_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX recipient_idx recipient TYPE bloom_filter(0.01) GRANULARITY 1) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.message_assets_data', '{replica}-{shard}', version) ORDER BY (team_id, function_kind, function_id, invocation_id, action_id) PARTITION BY toYYYYMMDD(sent_at) TTL toDate(sent_at) + toIntervalDay(30) SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1;+CREATE TABLE posthog.person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_group_membership_config', '{replica}-{shard}', version) ORDER BY (team_id) SETTINGS index_granularity = 8192;CREATE TABLE posthog.property_values (team_id Int64 CODEC(DoubleDelta, ZSTD(1)),property_type LowCardinality(String),@@ -415,6 +421,15 @@ CREATE TABLE posthog.sharded_marketing_touchpoints_preaggregated (computed_at DateTime64(6, 'UTC') DEFAULT now(),expires_at Date DEFAULT today() + toIntervalDay(7)) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.marketing_touchpoints_preaggregated', '{replica}-{shard}', computed_at) ORDER BY (team_id, job_id, person_id, touchpoint_timestamp) PARTITION BY toYYYYMMDD(expires_at) TTL expires_at SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE TABLE posthog.sharded_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/posthog.sharded_person_group_membership', '{replica}') ORDER BY (team_id, group_type_index, group_key, distinct_id) SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;CREATE TABLE posthog.sharded_platform_alert_events (team_id Int64,configuration_id UUID,diff --git a/posthog/clickhouse/hcl/sql/dev/data.sql b/posthog/clickhouse/hcl/sql/dev/data.sqlindex 7b8c36ddb5c2..f4bdabc2937b 100644--- a/posthog/clickhouse/hcl/sql/dev/data.sql+++ b/posthog/clickhouse/hcl/sql/dev/data.sql@@ -176,6 +176,12 @@ CREATE TABLE posthog.distributed_events_recent (inserted_at DateTime64(6, 'UTC') DEFAULT now64(),_timestamp_ms DateTime64(3)) ENGINE = Distributed('batch_exports', 'posthog', 'sharded_events_recent', sipHash64(distinct_id));+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.distributed_posthog_document_embeddings (team_id Int64,product LowCardinality(String),@@ -580,6 +586,14 @@ CREATE TABLE posthog.person_distinct_id_overrides (_partition UInt64,INDEX kafka_timestamp_minmax_person_distinct_id_overrides _timestamp TYPE minmax GRANULARITY 3) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_distinct_id_overrides', '{replica}-{shard}', version) ORDER BY (team_id, distinct_id) SETTINGS index_granularity = 512;+CREATE TABLE posthog.person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.person_overrides (team_id Int32,old_person_id UUID,diff --git a/posthog/clickhouse/hcl/sql/local-multi/auxiliary.sql b/posthog/clickhouse/hcl/sql/local-multi/auxiliary.sqlindex 615247d89815..f57ecdc6814b 100644--- a/posthog/clickhouse/hcl/sql/local-multi/auxiliary.sql+++ b/posthog/clickhouse/hcl/sql/local-multi/auxiliary.sql@@ -181,6 +181,12 @@ CREATE TABLE posthog.message_assets_data (INDEX person_id_idx person_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX recipient_idx recipient TYPE bloom_filter(0.01) GRANULARITY 1) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.message_assets_data', '{replica}-{shard}', version) ORDER BY (team_id, function_kind, function_id, invocation_id, action_id) PARTITION BY toYYYYMMDD(sent_at) TTL toDate(sent_at) + toIntervalDay(30) SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1;+CREATE TABLE posthog.person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_group_membership_config', '{replica}-{shard}', version) ORDER BY (team_id) SETTINGS index_granularity = 8192;CREATE TABLE posthog.property_values (team_id Int64 CODEC(DoubleDelta, ZSTD(1)),property_type LowCardinality(String),@@ -419,6 +425,15 @@ CREATE TABLE posthog.sharded_marketing_touchpoints_preaggregated (computed_at DateTime64(6, 'UTC') DEFAULT now(),expires_at Date DEFAULT today() + toIntervalDay(7)) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.marketing_touchpoints_preaggregated', '{replica}-{shard}', computed_at) ORDER BY (team_id, job_id, person_id, touchpoint_timestamp) PARTITION BY toYYYYMMDD(expires_at) TTL expires_at SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE TABLE posthog.sharded_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/posthog.sharded_person_group_membership', '{replica}') ORDER BY (team_id, group_type_index, group_key, distinct_id) SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;CREATE TABLE posthog.sharded_platform_alert_events (team_id Int64,configuration_id UUID,diff --git a/posthog/clickhouse/hcl/sql/local-multi/data.sql b/posthog/clickhouse/hcl/sql/local-multi/data.sqlindex b02968bda270..49b46e919ca1 100644--- a/posthog/clickhouse/hcl/sql/local-multi/data.sql+++ b/posthog/clickhouse/hcl/sql/local-multi/data.sql@@ -155,6 +155,12 @@ CREATE TABLE posthog.conversion_goal_attributed_preaggregated (computed_at DateTime64(6, 'UTC') DEFAULT now(),expires_at Date DEFAULT today() + toIntervalDay(7)) ENGINE = Distributed('aux', 'posthog', 'sharded_conversion_goal_attributed_preaggregated', cityHash64(person_id));+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.distributed_system_processes (is_initial_query UInt8,user String,@@ -604,6 +610,14 @@ CREATE TABLE posthog.person_distinct_id_overrides (_partition UInt64,INDEX kafka_timestamp_minmax_person_distinct_id_overrides _timestamp TYPE minmax GRANULARITY 3) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_distinct_id_overrides', '{replica}-{shard}', version) ORDER BY (team_id, distinct_id) SETTINGS index_granularity = 512;+CREATE TABLE posthog.person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.person_overrides (team_id Int32,old_person_id UUID,diff --git a/posthog/clickhouse/hcl/sql/local-multi/ingestion_small.sql b/posthog/clickhouse/hcl/sql/local-multi/ingestion_small.sqlindex f561988e6af0..de245990a565 100644--- a/posthog/clickhouse/hcl/sql/local-multi/ingestion_small.sql+++ b/posthog/clickhouse/hcl/sql/local-multi/ingestion_small.sql@@ -1,6 +1,12 @@-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.-- Full CREATE schema for the local-multi/small node. Apply to a fresh ClickHouse to build it.+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.kafka_app_metrics (team_id Int64,timestamp DateTime64(6, 'UTC'),@@ -485,6 +491,14 @@ CREATE TABLE posthog.writable_person_distinct_id_overrides (_offset UInt64,_partition UInt64) ENGINE = Distributed('posthog_single_shard', 'posthog', 'person_distinct_id_overrides');+CREATE TABLE posthog.writable_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.writable_plugin_log_entries (id UUID,team_id Int64,@@ -830,3 +844,4 @@ CREATE MATERIALIZED VIEW posthog.usage_report_events_preagg_mv TO posthog.writabFROM posthog.kafka_usage_report_events_preaggGROUP BYdate, team_id, person_mode, lib, event;+CREATE OR REPLACE DICTIONARY posthog.person_group_membership_config_dict (`team_id` Int64, `group_type_index` UInt8 DEFAULT 255, `enabled` UInt8 DEFAULT 0) PRIMARY KEY team_id SOURCE(CLICKHOUSE(USER 'default' QUERY 'SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4')) LAYOUT(COMPLEX_KEY_HASHED()) LIFETIME(MIN 60 MAX 120);diff --git a/posthog/clickhouse/hcl/sql/local-single/all.sql b/posthog/clickhouse/hcl/sql/local-single/all.sqlindex de2f623d4941..b69547b8bedc 100644--- a/posthog/clickhouse/hcl/sql/local-single/all.sql+++ b/posthog/clickhouse/hcl/sql/local-single/all.sql@@ -1741,6 +1741,12 @@ CREATE TABLE posthog.person_distinct_id_overrides (_partition UInt64,INDEX kafka_timestamp_minmax_person_distinct_id_overrides _timestamp TYPE minmax GRANULARITY 3) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_distinct_id_overrides', '{replica}-{shard}', version) ORDER BY (team_id, distinct_id) SETTINGS index_granularity = 512;+CREATE TABLE posthog.person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_group_membership_config', '{replica}-{shard}', version) ORDER BY (team_id) SETTINGS index_granularity = 8192;CREATE TABLE posthog.person_overrides (team_id Int32,old_person_id UUID,@@ -2435,6 +2441,15 @@ CREATE TABLE posthog.sharded_performance_events (_offset UInt64,_partition UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/posthog.performance_events', '{replica}') ORDER BY (team_id, toDate(timestamp), session_id, pageview_id, timestamp) PARTITION BY toYYYYMM(timestamp) TTL toDate(timestamp) + toIntervalWeek(3) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.sharded_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/posthog.sharded_person_group_membership', '{replica}') ORDER BY (team_id, group_type_index, group_key, distinct_id) SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;CREATE TABLE posthog.sharded_platform_alert_events (team_id Int64,configuration_id UUID,@@ -4105,6 +4120,14 @@ CREATE TABLE posthog.writable_person_distinct_id_overrides (_offset UInt64,_partition UInt64) ENGINE = Distributed('posthog_single_shard', 'posthog', 'person_distinct_id_overrides');+CREATE TABLE posthog.writable_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.writable_plugin_log_entries (id UUID,team_id Int64,@@ -6594,6 +6617,12 @@ CREATE TABLE posthog.distributed_events_recent (_offset UInt64,inserted_at DateTime64(6, 'UTC') DEFAULT now64()) ENGINE = Distributed('posthog_primary_replica', 'posthog', 'sharded_events_recent', sipHash64(distinct_id));+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.distributed_posthog_document_embeddings (team_id Int64,product LowCardinality(String),@@ -7118,6 +7147,14 @@ CREATE TABLE posthog.performance_events (_offset UInt64,_partition UInt64) ENGINE = Distributed('posthog', 'posthog', 'sharded_performance_events', sipHash64(session_id));+CREATE TABLE posthog.person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.platform_alert_events (team_id Int64,configuration_id UUID,@@ -8058,3 +8095,4 @@ CREATE VIEW posthog.sessions_v AS SELECTFROM posthog.sessionsGROUP BYsession_id, team_id;+CREATE OR REPLACE DICTIONARY posthog.person_group_membership_config_dict (`team_id` Int64, `group_type_index` UInt8 DEFAULT 255, `enabled` UInt8 DEFAULT 0) PRIMARY KEY team_id SOURCE(CLICKHOUSE(USER 'default' QUERY 'SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4')) LAYOUT(COMPLEX_KEY_HASHED()) LIFETIME(MIN 60 MAX 120);diff --git a/posthog/clickhouse/hcl/sql/prod-eu/auxiliary.sql b/posthog/clickhouse/hcl/sql/prod-eu/auxiliary.sqlindex 56447ae470df..7dc00e959ee9 100644--- a/posthog/clickhouse/hcl/sql/prod-eu/auxiliary.sql+++ b/posthog/clickhouse/hcl/sql/prod-eu/auxiliary.sql@@ -167,6 +167,12 @@ CREATE TABLE posthog.message_assets_data (INDEX person_id_idx person_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX recipient_idx recipient TYPE bloom_filter(0.01) GRANULARITY 1) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.message_assets_data', '{replica}-{shard}', version) ORDER BY (team_id, function_kind, function_id, invocation_id, action_id) PARTITION BY toYYYYMMDD(sent_at) TTL toDate(sent_at) + toIntervalDay(30) SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1;+CREATE TABLE posthog.person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_group_membership_config', '{replica}-{shard}', version) ORDER BY (team_id) SETTINGS index_granularity = 8192;CREATE TABLE posthog.property_values (team_id Int64 CODEC(DoubleDelta, ZSTD(1)),property_type LowCardinality(String),@@ -415,6 +421,15 @@ CREATE TABLE posthog.sharded_marketing_touchpoints_preaggregated (computed_at DateTime64(6, 'UTC') DEFAULT now(),expires_at Date DEFAULT today() + toIntervalDay(7)) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.marketing_touchpoints_preaggregated', '{replica}-{shard}', computed_at) ORDER BY (team_id, job_id, person_id, touchpoint_timestamp) PARTITION BY toYYYYMMDD(expires_at) TTL expires_at SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE TABLE posthog.sharded_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/posthog.sharded_person_group_membership', '{replica}') ORDER BY (team_id, group_type_index, group_key, distinct_id) SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;CREATE TABLE posthog.sharded_platform_alert_events (team_id Int64,configuration_id UUID,diff --git a/posthog/clickhouse/hcl/sql/prod-eu/data.sql b/posthog/clickhouse/hcl/sql/prod-eu/data.sqlindex 5b5c148e3a64..9afa5aa37ef4 100644--- a/posthog/clickhouse/hcl/sql/prod-eu/data.sql+++ b/posthog/clickhouse/hcl/sql/prod-eu/data.sql@@ -201,6 +201,12 @@ CREATE TABLE posthog.distributed_events_recent (inserted_at DateTime64(6, 'UTC') DEFAULT now64(),_timestamp_ms DateTime64(3)) ENGINE = Distributed('batch_exports', 'posthog', 'sharded_events_recent', sipHash64(distinct_id));+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.distributed_posthog_document_embeddings (team_id Int64,product LowCardinality(String),@@ -848,6 +854,14 @@ CREATE TABLE posthog.person_distinct_id_overrides (_partition UInt64,INDEX kafka_timestamp_minmax_person_distinct_id_overrides _timestamp TYPE minmax GRANULARITY 3) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_distinct_id_overrides', '{replica}-{shard}', version) ORDER BY (team_id, distinct_id) SETTINGS index_granularity = 512;+CREATE TABLE posthog.person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.person_overrides (team_id Int32,old_person_id UUID,diff --git a/posthog/clickhouse/hcl/sql/prod-us/auxiliary.sql b/posthog/clickhouse/hcl/sql/prod-us/auxiliary.sqlindex 7439b2059495..beb728a27f3f 100644--- a/posthog/clickhouse/hcl/sql/prod-us/auxiliary.sql+++ b/posthog/clickhouse/hcl/sql/prod-us/auxiliary.sql@@ -167,6 +167,12 @@ CREATE TABLE posthog.message_assets_data (INDEX person_id_idx person_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX recipient_idx recipient TYPE bloom_filter(0.01) GRANULARITY 1) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.message_assets_data', '{replica}-{shard}', version) ORDER BY (team_id, function_kind, function_id, invocation_id, action_id) PARTITION BY toYYYYMMDD(sent_at) TTL toDate(sent_at) + toIntervalDay(30) SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1;+CREATE TABLE posthog.person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.person_group_membership_config', '{replica}-{shard}', version) ORDER BY (team_id) SETTINGS index_granularity = 8192;CREATE TABLE posthog.property_values (team_id Int64 CODEC(DoubleDelta, ZSTD(1)),property_type LowCardinality(String),@@ -415,6 +421,15 @@ CREATE TABLE posthog.sharded_marketing_touchpoints_preaggregated (computed_at DateTime64(6, 'UTC') DEFAULT now(),expires_at Date DEFAULT today() + toIntervalDay(7)) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/noshard/posthog.marketing_touchpoints_preaggregated', '{replica}-{shard}', computed_at) ORDER BY (team_id, job_id, person_id, touchpoint_timestamp) PARTITION BY toYYYYMMDD(expires_at) TTL expires_at SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE TABLE posthog.sharded_person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/{shard}/posthog.sharded_person_group_membership', '{replica}') ORDER BY (team_id, group_type_index, group_key, distinct_id) SETTINGS index_granularity = 8192, min_bytes_for_wide_part = 0, min_rows_for_wide_part = 0;CREATE TABLE posthog.sharded_platform_alert_events (team_id Int64,configuration_id UUID,diff --git a/posthog/clickhouse/hcl/sql/prod-us/data.sql b/posthog/clickhouse/hcl/sql/prod-us/data.sqlindex e8399202c44b..e713d84e1525 100644--- a/posthog/clickhouse/hcl/sql/prod-us/data.sql+++ b/posthog/clickhouse/hcl/sql/prod-us/data.sql@@ -211,6 +211,12 @@ CREATE TABLE posthog.distributed_events_recent (inserted_at DateTime64(6, 'UTC') DEFAULT now64(),_timestamp_ms DateTime64(3)) ENGINE = Distributed('batch_exports', 'posthog', 'sharded_events_recent', sipHash64(distinct_id));+CREATE TABLE posthog.distributed_person_group_membership_config (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+) ENGINE = Distributed('aux', 'posthog', 'person_group_membership_config', sipHash64(team_id));CREATE TABLE posthog.distributed_posthog_document_embeddings (team_id Int64,product LowCardinality(String),@@ -712,6 +718,14 @@ CREATE TABLE posthog.person_distinct_id_overrides_to_delete_join (distinct_id String,version Int64) ENGINE = Join(ANY, LEFT, team_id, distinct_id);+CREATE TABLE posthog.person_group_membership (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+) ENGINE = Distributed('aux', 'posthog', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key));CREATE TABLE posthog.person_overrides (team_id Int32,old_person_id UUID,diff --git a/posthog/clickhouse/migrations/0343_person_group_membership.py b/posthog/clickhouse/migrations/0343_person_group_membership.pynew file mode 100644index 000000000000..c492766e2431--- /dev/null+++ b/posthog/clickhouse/migrations/0343_person_group_membership.py@@ -0,0 +1,38 @@+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions+from posthog.models.person_group_membership.sql import (+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+)++operations = [+ run_sql_with_exceptions(+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ sharded=True,+ ),+ run_sql_with_exceptions(+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL(),+ node_roles=[NodeRole.AUX],+ ),+ run_sql_with_exceptions(+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL(),+ node_roles=[NodeRole.DATA, NodeRole.INGESTION_SMALL],+ ),+ run_sql_with_exceptions(+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL(),+ node_roles=[NodeRole.DATA],+ ),+ run_sql_with_exceptions(+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE_SQL(),+ node_roles=[NodeRole.INGESTION_SMALL],+ ),+ run_sql_with_exceptions(+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL(),+ node_roles=[NodeRole.INGESTION_SMALL],+ ),+]diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex b08a9384384f..a748768a7c03 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0342_metrics4_names_service_name+0343_person_group_membershipdiff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex cf2393391fd7..89a54c593b3b 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -308,6 +308,14 @@ from posthog.models.person.sql import (PERSONS_TABLE_SQL,PERSONS_WRITABLE_TABLE_SQL,)+from posthog.models.person_group_membership.sql import (+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+)from posthog.models.person_overrides.sql import (KAFKA_PERSON_OVERRIDES_TABLE_SQL,PERSON_OVERRIDES_CREATE_DICTIONARY_SQL,@@ -415,6 +423,8 @@ from products.event_definitions.backend.models.property_definition import PROPER# Queries to create tables, you must pass function, otherwise the table is created before# objects are mocked and the ambr will go into infinite loop update.CREATE_MERGETREE_TABLE_QUERIES = (+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,SHARDED_PLATFORM_ALERT_EVENTS_TABLE_SQL,LOG_ENTRIES_TABLE_SQL,LOG_ENTRIES_DATA_TABLE_SQL,@@ -514,6 +524,9 @@ CREATE_MERGETREE_TABLE_QUERIES = (DMAT_SLOT_ASSIGNMENTS_TABLE_SQL,)CREATE_DISTRIBUTED_TABLE_QUERIES = (+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE_SQL,+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL,DISTRIBUTED_PLATFORM_ALERT_EVENTS_TABLE_SQL,LOG_ENTRIES_AUX_DISTRIBUTED_TABLE_SQL,LOG_ENTRIES_AUX_WRITABLE_TABLE_SQL,@@ -721,6 +734,7 @@ CREATE_TABLE_QUERIES = ()CREATE_DICTIONARY_QUERIES = (+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL,PERSON_OVERRIDES_CREATE_DICTIONARY_SQL,CHANNEL_DEFINITION_DICTIONARY_SQL,EXCHANGE_RATE_DICTIONARY_SQL,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex c83b485814dc..54e78ee06a97 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -1431,6 +1431,20 @@'''# ---+# name: test_create_table_query[distributed_person_group_membership_config]+ '''++ CREATE TABLE IF NOT EXISTS distributed_person_group_membership_config+ (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+ )+ ENGINE = Distributed('aux', 'posthog_test', 'person_group_membership_config', sipHash64(team_id))++ '''+# ---# name: test_create_table_query[distributed_posthog_document_embeddings]'''@@ -5762,6 +5776,38 @@'''# ---+# name: test_create_table_query[person_group_membership]+ '''++ CREATE TABLE IF NOT EXISTS person_group_membership+ (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+ )+ ENGINE = Distributed('aux', 'posthog_test', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key))++ '''+# ---+# name: test_create_table_query[person_group_membership_config]+ '''++ CREATE TABLE IF NOT EXISTS person_group_membership_config+ (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+ )+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.person_group_membership_config', '{replica}-{shard}', version)+ ORDER BY team_id+ SETTINGS index_granularity = 8192++ '''+# ---# name: test_create_table_query[person_mv]'''@@ -8374,6 +8420,25 @@+ '''+# ---+# name: test_create_table_query[sharded_person_group_membership]+ '''++ CREATE TABLE IF NOT EXISTS sharded_person_group_membership+ (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+ )+ ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.sharded_person_group_membership', '{replica}')+ ORDER BY (team_id, group_type_index, group_key, distinct_id)+ SETTINGS index_granularity = 8192, min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0+'''# ---# name: test_create_table_query[sharded_platform_alert_events]@@ -10844,6 +10909,22 @@'''# ---+# name: test_create_table_query[writable_person_group_membership]+ '''++ CREATE TABLE IF NOT EXISTS writable_person_group_membership+ (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+ )+ ENGINE = Distributed('aux', 'posthog_test', 'sharded_person_group_membership', sipHash64(team_id, group_type_index, group_key))++ '''+# ---# name: test_create_table_query[writable_plugin_log_entries]'''@@ -12940,6 +13021,22 @@'''# ---+# name: test_create_table_query_replicated_and_storage[person_group_membership_config]+ '''++ CREATE TABLE IF NOT EXISTS person_group_membership_config+ (+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+ )+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.person_group_membership_config', '{replica}-{shard}', version)+ ORDER BY team_id+ SETTINGS index_granularity = 8192++ '''+# ---# name: test_create_table_query_replicated_and_storage[person_overrides]'''@@ -14063,6 +14160,25 @@'''# ---+# name: test_create_table_query_replicated_and_storage[sharded_person_group_membership]+ '''++ CREATE TABLE IF NOT EXISTS sharded_person_group_membership+ (+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC')),+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+ )+ ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.sharded_person_group_membership', '{replica}')+ ORDER BY (team_id, group_type_index, group_key, distinct_id)+ SETTINGS index_granularity = 8192, min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0++ '''+# ---# name: test_create_table_query_replicated_and_storage[sharded_platform_alert_events]'''diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.pyindex 0bd6f7492cf8..6850d0a6e2cd 100644--- a/posthog/clickhouse/test/test_schema.py+++ b/posthog/clickhouse/test/test_schema.py@@ -40,6 +40,7 @@ from posthog.settings.kafka import KAFKA_PREFIX@pytest.mark.parametrize("query", CREATE_TABLE_QUERIES, ids=get_table_name)def test_create_table_query(query, snapshot, settings):+ settings.CLICKHOUSE_DATABASE = "posthog_test"settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA = Falseassert build_query(query) == snapshot@@ -47,6 +48,7 @@ def test_create_table_query(query, snapshot, settings):@pytest.mark.parametrize("query", CREATE_MERGETREE_TABLE_QUERIES, ids=get_table_name)def test_create_table_query_replicated_and_storage(query, snapshot, settings):+ settings.CLICKHOUSE_DATABASE = "posthog_test"settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA = Falsesettings.CLICKHOUSE_ENABLE_STORAGE_POLICY = Truediff --git a/posthog/models/person_group_membership/__init__.py b/posthog/models/person_group_membership/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/models/person_group_membership/sql.py b/posthog/models/person_group_membership/sql.pynew file mode 100644index 000000000000..0164b71d8dd9--- /dev/null+++ b/posthog/models/person_group_membership/sql.py@@ -0,0 +1,136 @@+from django.conf import settings++from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string++from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds+from posthog.clickhouse.table_engines import AggregatingMergeTree, Distributed, ReplacingMergeTree, ReplicationScheme++PERSON_GROUP_MEMBERSHIP_TABLE = "person_group_membership"+SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE = f"sharded_{PERSON_GROUP_MEMBERSHIP_TABLE}"+WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE = f"writable_{PERSON_GROUP_MEMBERSHIP_TABLE}"++PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE = "person_group_membership_config"+DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE = f"distributed_{PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}"+PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY = f"{PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}_dict"++PERSON_GROUP_MEMBERSHIP_MAX_GROUP_TYPE_INDEX = 4+PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_LIFETIME_MAX_SECONDS = 120+PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_DEFAULT_GROUP_TYPE_INDEX = 255++PERSON_GROUP_MEMBERSHIP_COLUMNS = """+ team_id Int64,+ group_type_index UInt8,+ group_key String,+ distinct_id String,+ first_seen SimpleAggregateFunction(min, DateTime64(6, 'UTC')),+ last_seen SimpleAggregateFunction(max, DateTime64(6, 'UTC'))+""".strip()++PERSON_GROUP_MEMBERSHIP_CONFIG_COLUMNS = """+ team_id Int64,+ group_type_index UInt8,+ enabled UInt8,+ version UInt64+""".strip()+++def SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL() -> str:+ # Wide parts let lightweight deletes rewrite the row mask without rewriting membership columns.+ # The distinct_id index serves person lookups and person deletion, which the sort key cannot narrow.+ return f"""+CREATE TABLE IF NOT EXISTS {SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE}+(+ {PERSON_GROUP_MEMBERSHIP_COLUMNS},+ INDEX idx_distinct_id distinct_id TYPE bloom_filter(0.01) GRANULARITY 1+)+ENGINE = {AggregatingMergeTree(SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE, replication_scheme=ReplicationScheme.SHARDED)}+ORDER BY (team_id, group_type_index, group_key, distinct_id)+SETTINGS index_granularity = 8192, min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0+"""+++def DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_TABLE_SQL() -> str:+ return f"""+CREATE TABLE IF NOT EXISTS {PERSON_GROUP_MEMBERSHIP_TABLE}+(+ {PERSON_GROUP_MEMBERSHIP_COLUMNS}+)+ENGINE = {+ Distributed(+ data_table=SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE,+ sharding_key="sipHash64(team_id, group_type_index, group_key)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ )+ }+"""+++def WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE_SQL() -> str:+ return f"""+CREATE TABLE IF NOT EXISTS {WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE}+(+ {PERSON_GROUP_MEMBERSHIP_COLUMNS}+)+ENGINE = {+ Distributed(+ data_table=SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE,+ sharding_key="sipHash64(team_id, group_type_index, group_key)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ )+ }+"""+++def PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL() -> str:+ return f"""+CREATE TABLE IF NOT EXISTS {PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}+(+ {PERSON_GROUP_MEMBERSHIP_CONFIG_COLUMNS}+)+ENGINE = {ReplacingMergeTree(PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE, ver="version")}+ORDER BY team_id+SETTINGS index_granularity = 8192+"""+++def DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE_SQL() -> str:+ return f"""+CREATE TABLE IF NOT EXISTS {DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}+(+ {PERSON_GROUP_MEMBERSHIP_CONFIG_COLUMNS}+)+ENGINE = {+ Distributed(+ data_table=PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ sharding_key="sipHash64(team_id)",+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ )+ }+"""+++def PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL() -> str:+ database = escape_clickhouse_identifier(settings.CLICKHOUSE_DATABASE)+ creds = get_clickhouse_creds(ClickHouseUser.DICT_READER)+ # Filter after argMax so a newer disabled or invalid row cannot revive an older valid config.+ query = (+ "SELECT team_id, config.1 AS group_type_index, config.2 AS enabled "+ "FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config "+ f"FROM {database}.{DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE} GROUP BY team_id) "+ f"WHERE enabled = 1 AND group_type_index <= {PERSON_GROUP_MEMBERSHIP_MAX_GROUP_TYPE_INDEX}"+ )+ source = f"QUERY {escape_clickhouse_string(query)} USER {escape_clickhouse_string(creds.user)}"+ if creds.password:+ source += f" PASSWORD {escape_clickhouse_string(creds.password)}"+ return f"""+CREATE DICTIONARY IF NOT EXISTS {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}+(+ team_id Int64,+ group_type_index UInt8 DEFAULT {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_DEFAULT_GROUP_TYPE_INDEX},+ enabled UInt8 DEFAULT 0+)+PRIMARY KEY team_id+SOURCE(CLICKHOUSE({source}))+LIFETIME(MIN 60 MAX {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_LIFETIME_MAX_SECONDS})+LAYOUT(COMPLEX_KEY_HASHED())+"""diff --git a/posthog/models/person_group_membership/test/__init__.py b/posthog/models/person_group_membership/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/models/person_group_membership/test/__snapshots__/test_sql.ambr b/posthog/models/person_group_membership/test/__snapshots__/test_sql.ambrnew file mode 100644index 000000000000..26ae415fc6a1--- /dev/null+++ b/posthog/models/person_group_membership/test/__snapshots__/test_sql.ambr@@ -0,0 +1,17 @@+# serializer version: 1+# name: test_dictionary_sql+ '''++ CREATE DICTIONARY IF NOT EXISTS person_group_membership_config_dict+ (+ team_id Int64,+ group_type_index UInt8 DEFAULT 255,+ enabled UInt8 DEFAULT 0+ )+ PRIMARY KEY team_id+ SOURCE(CLICKHOUSE(QUERY 'SELECT team_id, config.1 AS group_type_index, config.2 AS enabled FROM (SELECT team_id, argMax(tuple(group_type_index, enabled), version) AS config FROM posthog.distributed_person_group_membership_config GROUP BY team_id) WHERE enabled = 1 AND group_type_index <= 4' USER 'dict_reader' PASSWORD 'fake\'password\\with_escape'))+ LIFETIME(MIN 60 MAX 120)+ LAYOUT(COMPLEX_KEY_HASHED())++ '''+# ---diff --git a/posthog/models/person_group_membership/test/test_sql.py b/posthog/models/person_group_membership/test/test_sql.pynew file mode 100644index 000000000000..6a79b226a0e4--- /dev/null+++ b/posthog/models/person_group_membership/test/test_sql.py@@ -0,0 +1,256 @@+import importlib+from collections.abc import Callable, Iterator+from datetime import UTC, datetime++import pytest+from unittest.mock import patch++from django.conf import settings as django_settings++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import ClickHouseCredentials, ClickHouseUser, NodeRole+from posthog.clickhouse.schema import (+ CREATE_DICTIONARY_QUERIES,+ CREATE_DISTRIBUTED_TABLE_QUERIES,+ CREATE_MERGETREE_TABLE_QUERIES,+ get_table_name,+)+from posthog.models.person_group_membership.sql import (+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY,+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL,+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ PERSON_GROUP_MEMBERSHIP_TABLE,+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE,+)++MIGRATION = "posthog.clickhouse.migrations.0343_person_group_membership"+++def test_dictionary_sql(snapshot, mocker, settings) -> None:+ settings.CLICKHOUSE_DATABASE = "posthog"+ creds = mocker.patch(+ "posthog.models.person_group_membership.sql.get_clickhouse_creds",+ return_value=ClickHouseCredentials(user="dict_reader", password="fake'password\\with_escape"),+ )+ assert PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY_SQL() == snapshot+ creds.assert_called_once_with(ClickHouseUser.DICT_READER)++[email protected]("deployment", ["", "DEV", "US", "EU"])[email protected]("multinode", [False, True])+def test_migration_placement(deployment: str, multinode: bool) -> None:+ module = importlib.import_module(MIGRATION)+ try:+ with patch.multiple("posthog.settings", CLOUD_DEPLOYMENT=deployment, MULTINODE_CLICKHOUSE=multinode):+ operations = importlib.reload(module).operations+ expected_roles = [+ [NodeRole.AUX],+ [NodeRole.AUX],+ [NodeRole.DATA, NodeRole.INGESTION_SMALL],+ [NodeRole.DATA],+ [NodeRole.INGESTION_SMALL],+ [NodeRole.INGESTION_SMALL],+ ]+ assert [op._node_roles for op in operations] == expected_roles+ assert [op._effective_node_roles for op in operations] == (+ expected_roles if deployment or multinode else [[NodeRole.ALL]] * 6+ )+ for op in operations:+ assert "ON CLUSTER" not in op._sql+ assert "IF NOT EXISTS" in op._sql+ assert "Kafka" not in op._sql+ assert "MATERIALIZED VIEW" not in op._sql+ finally:+ importlib.reload(module)+++ "queries,expected",+ [+ (+ CREATE_MERGETREE_TABLE_QUERIES,+ {SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE, PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE},+ ),+ (+ CREATE_DISTRIBUTED_TABLE_QUERIES,+ {+ PERSON_GROUP_MEMBERSHIP_TABLE,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE,+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ },+ ),+ (CREATE_DICTIONARY_QUERIES, {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}),+ ],+ ids=["storage", "proxies", "dictionary"],+)+def test_local_schema_includes_membership_objects(+ queries: tuple[str | Callable[[], str], ...], expected: set[str]+) -> None:+ assert expected <= {get_table_name(query) for query in queries}+++def membership_schema(clickhouse_database) -> Iterator[None]:+ module = importlib.reload(importlib.import_module(MIGRATION))+ for _ in range(2):+ for operation in module.operations:+ sync_execute(operation._sql)+ try:+ for table in (SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE, PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE):+ sync_execute(f"TRUNCATE TABLE {table}")+ sync_execute(f"SYSTEM RELOAD DICTIONARY {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}")+ yield+ finally:+ for table in (SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE, PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE):+ sync_execute(f"TRUNCATE TABLE {table}")+ sync_execute(f"SYSTEM RELOAD DICTIONARY {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}")++[email protected]("membership_schema")+def test_empty_schema_engines_and_keys() -> None:+ rows = sync_execute(+ """SELECT name, engine, sorting_key, engine_full, create_table_query+ FROM system.tables WHERE database = %(database)s AND name IN %(tables)s""",+ {+ "database": django_settings.CLICKHOUSE_DATABASE,+ "tables": (+ SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE,+ PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ PERSON_GROUP_MEMBERSHIP_TABLE,+ WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE,+ DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE,+ PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY,+ ),+ },+ )+ tables = {row[0]: row[1:] for row in rows}+ assert len(tables) == 6+ storage = tables[SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE]+ assert storage[0] == "ReplicatedAggregatingMergeTree"+ assert storage[1] == "team_id, group_type_index, group_key, distinct_id"+ assert "min_rows_for_wide_part = 0" in storage[3]+ assert "min_bytes_for_wide_part = 0" in storage[3]+ assert sync_execute(+ """SELECT expr, type_full, granularity FROM system.data_skipping_indices+ WHERE database = %(database)s AND table = %(table)s""",+ {"database": django_settings.CLICKHOUSE_DATABASE, "table": SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE},+ ) == [("distinct_id", "bloom_filter(0.01)", 1)]+ config = tables[PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE]+ assert config[0] == "ReplicatedReplacingMergeTree"+ assert config[1] == "team_id"+ assert ", version)" in config[2]+ for table in (PERSON_GROUP_MEMBERSHIP_TABLE, WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE):+ engine = tables[table]+ assert engine[0] == "Distributed"+ assert f"'{django_settings.CLICKHOUSE_AUX_CLUSTER}'" in engine[2]+ assert "sipHash64(team_id, group_type_index, group_key)" in engine[2]+ assert sync_execute(f"SELECT count() FROM {table}") == [(0,)]+ assert sync_execute(f"SELECT count() FROM {DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}") == [(0,)]++[email protected]("membership_schema")+def test_dictionary_uses_latest_valid_enabled_config() -> None:+ rows = [+ (1001, 0, 1, 1),+ (1002, 4, 1, 1),+ (1003, 5, 1, 1),+ (1004, 255, 1, 1),+ (1005, 0, 0, 1),+ (1006, 0, 1, 1),+ (1006, 0, 0, 2),+ (1007, 0, 1, 1),+ (1007, 5, 1, 2),+ (1008, 2, 1, 3),+ (1008, 0, 1, 1),+ (1008, 4, 1, 2),+ (1009, 5, 0, 1),+ (1009, 3, 1, 2),+ ]+ sync_execute(f"SYSTEM STOP MERGES {PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}")+ try:+ sync_execute(+ f"INSERT INTO {DISTRIBUTED_PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE} VALUES",+ rows,+ settings={"distributed_foreground_insert": 1},+ )+ sync_execute(f"SYSTEM RELOAD DICTIONARY {PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}")+ result = sync_execute(+ f"""SELECT team_id,+ dictHas('{PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}', tuple(team_id)),+ dictGet('{PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}', 'group_type_index', tuple(team_id)),+ dictGet('{PERSON_GROUP_MEMBERSHIP_CONFIG_DICTIONARY}', 'enabled', tuple(team_id))+ FROM (SELECT toInt64(arrayJoin(range(1000, 1010))) AS team_id) ORDER BY team_id"""+ )+ assert result == [+ (1000, 0, 255, 0),+ (1001, 1, 0, 1),+ (1002, 1, 4, 1),+ (1003, 0, 255, 0),+ (1004, 0, 255, 0),+ (1005, 0, 255, 0),+ (1006, 0, 255, 0),+ (1007, 0, 255, 0),+ (1008, 1, 2, 1),+ (1009, 1, 3, 1),+ ]+ finally:+ sync_execute(f"SYSTEM START MERGES {PERSON_GROUP_MEMBERSHIP_CONFIG_TABLE}")++[email protected]("membership_schema")+def test_distributed_writes_and_reads_aggregate_overlap() -> None:+ for table, first_seen, last_seen in [+ (WRITABLE_PERSON_GROUP_MEMBERSHIP_TABLE, "2024-01-02 00:00:00.123456", "2024-01-04 00:00:00.654321"),+ (PERSON_GROUP_MEMBERSHIP_TABLE, "2024-01-01 00:00:00.123456", "2024-01-03 00:00:00.654321"),+ ]:+ sync_execute(+ f"""INSERT INTO {table}+ SELECT 1001, 0, 'example-account', 'example-distinct-id',+ toDateTime64(%(first_seen)s, 6, 'UTC'), toDateTime64(%(last_seen)s, 6, 'UTC')""",+ {"first_seen": first_seen, "last_seen": last_seen},+ settings={"distributed_foreground_insert": 1},+ )+ assert sync_execute(+ f"""SELECT team_id, group_type_index, group_key, distinct_id, min(first_seen), max(last_seen)+ FROM {PERSON_GROUP_MEMBERSHIP_TABLE} GROUP BY team_id, group_type_index, group_key, distinct_id"""+ ) == [+ (+ 1001,+ 0,+ "example-account",+ "example-distinct-id",+ datetime(2024, 1, 1, microsecond=123456, tzinfo=UTC),+ datetime(2024, 1, 4, microsecond=654321, tzinfo=UTC),+ )+ ]++[email protected]("lightweight", [False, True], ids=["mutation", "lightweight"])[email protected]("membership_schema")+def test_storage_supports_distinct_id_and_team_deletion(lightweight: bool) -> None:+ sync_execute(+ f"""INSERT INTO {PERSON_GROUP_MEMBERSHIP_TABLE}+ SELECT team_id, 0, group_key, distinct_id, now64(6, 'UTC'), now64(6, 'UTC')+ FROM values('team_id Int64, group_key String, distinct_id String',+ (1001, 'account-a', 'person-a'), (1001, 'account-b', 'person-a'),+ (1001, 'account-a', 'person-b'), (1002, 'account-a', 'person-a'))""",+ settings={"distributed_foreground_insert": 1},+ )+ for predicate, expected in [+ ("team_id = 1001 AND distinct_id = 'person-a'", [(1001, "person-b"), (1002, "person-a")]),+ ("team_id = 1001", [(1002, "person-a")]),+ ]:+ sql = (+ f"DELETE FROM {SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE} WHERE {predicate}"+ if lightweight+ else f"ALTER TABLE {SHARDED_PERSON_GROUP_MEMBERSHIP_TABLE} DELETE WHERE {predicate}"+ )+ sync_execute(sql, settings={"mutations_sync": 2, "lightweight_deletes_sync": 2})+ assert (+ sync_execute(+ f"SELECT team_id, distinct_id FROM {PERSON_GROUP_MEMBERSHIP_TABLE} ORDER BY team_id, distinct_id"+ )+ == expected+ )