Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): add flag_evaluations ClickHouse table (#72990)

Phil Haack3591ba0c2e10
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index ae52ad0bc05e..8eefb9ded9bf 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -511,6 +511,7 @@ services:
clickhouse_events_json \
clickhouse_ai_events_json \
clickhouse_heatmap_events \
+ clickhouse_flag_evaluations \
clickhouse_ingestion_warnings \
events_plugin_ingestion_dlq \
events_plugin_ingestion_overflow \
diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.yml
index 6ff9a54dcec5..d56d74ae12fd 100644
--- a/docker-compose.hobby.yml
+++ b/docker-compose.hobby.yml
@@ -584,6 +584,7 @@ services:
TOPICS="clickhouse_events_json \
clickhouse_ai_events_json \
clickhouse_heatmap_events \
+ clickhouse_flag_evaluations \
clickhouse_ingestion_warnings \
events_plugin_ingestion_dlq \
events_plugin_ingestion_overflow \
diff --git a/posthog/clickhouse/hcl/golden/local-multi/data.hcl b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
index 553a899a658b..16b665c71043 100644
--- a/posthog/clickhouse/hcl/golden/local-multi/data.hcl
+++ b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
@@ -1685,6 +1685,135 @@ database "posthog" {
}
}
+ table "flag_evaluations" {
+ column "team_id" {
+ type = "Int64"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "inserted_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "distinct_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "session_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "device_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "flag_key" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "response" {
+ type = "LowCardinality(String)"
+ }
+ column "flag_id" {
+ type = "UInt64"
+ }
+ column "flag_version" {
+ type = "UInt32"
+ }
+ column "reason" {
+ type = "LowCardinality(String)"
+ }
+ column "request_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "evaluated_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "error" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "locally_evaluated" {
+ type = "Bool"
+ }
+ column "lib" {
+ type = "LowCardinality(String)"
+ }
+ column "lib_version" {
+ type = "LowCardinality(String)"
+ }
+ column "is_server" {
+ type = "Bool"
+ }
+ column "os" {
+ type = "LowCardinality(String)"
+ }
+ column "os_version" {
+ type = "LowCardinality(String)"
+ }
+ column "app_version" {
+ type = "LowCardinality(String)"
+ }
+ column "current_url" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "pathname" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "country_code" {
+ type = "LowCardinality(String)"
+ }
+ column "subdivision_1_code" {
+ type = "LowCardinality(String)"
+ }
+ column "group_0" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_1" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_2" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_3" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_4" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "sharded_flag_evaluations"
+ sharding_key = "sipHash64(distinct_id)"
+ }
+ }
+
table "groups" {
order_by = ["team_id", "group_type_index", "group_key"]
settings = {
@@ -5996,6 +6125,160 @@ database "posthog" {
}
}
+ table "sharded_flag_evaluations" {
+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]
+ partition_by = "toYYYYMM(timestamp)"
+ ttl = "toDate(timestamp) + toIntervalDay(90)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "inserted_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "distinct_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "session_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "device_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "flag_key" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "response" {
+ type = "LowCardinality(String)"
+ }
+ column "flag_id" {
+ type = "UInt64"
+ }
+ column "flag_version" {
+ type = "UInt32"
+ }
+ column "reason" {
+ type = "LowCardinality(String)"
+ }
+ column "request_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "evaluated_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "error" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "locally_evaluated" {
+ type = "Bool"
+ }
+ column "lib" {
+ type = "LowCardinality(String)"
+ }
+ column "lib_version" {
+ type = "LowCardinality(String)"
+ }
+ column "is_server" {
+ type = "Bool"
+ }
+ column "os" {
+ type = "LowCardinality(String)"
+ }
+ column "os_version" {
+ type = "LowCardinality(String)"
+ }
+ column "app_version" {
+ type = "LowCardinality(String)"
+ }
+ column "current_url" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "pathname" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "country_code" {
+ type = "LowCardinality(String)"
+ }
+ column "subdivision_1_code" {
+ type = "LowCardinality(String)"
+ }
+ column "group_0" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_1" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_2" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_3" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_4" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ index "distinct_id_idx" {
+ expr = "distinct_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "session_id_idx" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "request_id_idx" {
+ expr = "request_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "inserted_at_idx" {
+ expr = "inserted_at"
+ type = "minmax"
+ granularity = 1
+ }
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"
+ replica_name = "{replica}"
+ }
+ }
+
table "sharded_heatmaps" {
order_by = ["type", "team_id", "toDate(timestamp)", "current_url", "viewport_width"]
partition_by = "toYYYYMM(timestamp)"
diff --git a/posthog/clickhouse/hcl/roles/data/local/tables.hcl b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
index 684f3f2b0317..2c8768f51616 100644
--- a/posthog/clickhouse/hcl/roles/data/local/tables.hcl
+++ b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
@@ -1,4 +1,127 @@
database "posthog" {
+ table "_flag_evaluations_columns" {
+ abstract = true
+ column "team_id" {
+ type = "Int64"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "inserted_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "distinct_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "session_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "device_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "flag_key" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "response" {
+ type = "LowCardinality(String)"
+ }
+ column "flag_id" {
+ type = "UInt64"
+ }
+ column "flag_version" {
+ type = "UInt32"
+ }
+ column "reason" {
+ type = "LowCardinality(String)"
+ }
+ column "request_id" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "evaluated_at" {
+ type = "DateTime64(6, 'UTC')"
+ default = "timestamp"
+ codec = "DoubleDelta, ZSTD(1)"
+ }
+ column "error" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "locally_evaluated" {
+ type = "Bool"
+ }
+ column "lib" {
+ type = "LowCardinality(String)"
+ }
+ column "lib_version" {
+ type = "LowCardinality(String)"
+ }
+ column "is_server" {
+ type = "Bool"
+ }
+ column "os" {
+ type = "LowCardinality(String)"
+ }
+ column "os_version" {
+ type = "LowCardinality(String)"
+ }
+ column "app_version" {
+ type = "LowCardinality(String)"
+ }
+ column "current_url" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "pathname" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "country_code" {
+ type = "LowCardinality(String)"
+ }
+ column "subdivision_1_code" {
+ type = "LowCardinality(String)"
+ }
+ column "group_0" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_1" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_2" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_3" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "group_4" {
+ type = "String"
+ codec = "ZSTD(1)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ }
table "adhoc_events_deletion" {
order_by = ["team_id", "uuid"]
ttl = "deleted_at + toIntervalMonth(3)"
@@ -2385,6 +2508,15 @@ database "posthog" {
sharding_key = "cityHash64(entity_id)"
}
}
+ table "flag_evaluations" {
+ extend = "_flag_evaluations_columns"
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "sharded_flag_evaluations"
+ sharding_key = "sipHash64(distinct_id)"
+ }
+ }
table "groups" {
order_by = ["team_id", "group_type_index", "group_key"]
settings = {
@@ -5684,6 +5816,40 @@ database "posthog" {
version_column = "computed_at"
}
}
+ table "sharded_flag_evaluations" {
+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]
+ partition_by = "toYYYYMM(timestamp)"
+ ttl = "toDate(timestamp) + toIntervalDay(90)"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ extend = "_flag_evaluations_columns"
+ index "distinct_id_idx" {
+ expr = "distinct_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "session_id_idx" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "request_id_idx" {
+ expr = "request_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "inserted_at_idx" {
+ expr = "inserted_at"
+ type = "minmax"
+ granularity = 1
+ }
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"
+ replica_name = "{replica}"
+ }
+ }
table "sharded_heatmaps" {
order_by = ["type", "team_id", "toDate(timestamp)", "current_url", "viewport_width"]
partition_by = "toYYYYMM(timestamp)"
diff --git a/posthog/clickhouse/hcl/sql/local-multi/data.sql b/posthog/clickhouse/hcl/sql/local-multi/data.sql
index 33f058576465..2754663d9855 100644
--- a/posthog/clickhouse/hcl/sql/local-multi/data.sql
+++ b/posthog/clickhouse/hcl/sql/local-multi/data.sql
@@ -1169,6 +1169,46 @@ CREATE TABLE posthog.sharded_experiment_exposures_preaggregated (
computed_at DateTime64(6, 'UTC') DEFAULT now(),
expires_at Date DEFAULT today() + toIntervalDay(7)
) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.experiment_exposures_preaggregated', '{replica}', computed_at) ORDER BY (team_id, job_id, entity_id, breakdown_value) PARTITION BY toYYYYMMDD(expires_at) TTL expires_at SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.sharded_flag_evaluations (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1)),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64,
+ INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX session_id_idx session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX request_id_idx request_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX inserted_at_idx inserted_at TYPE minmax GRANULARITY 1
+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}') ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id)) PARTITION BY toYYYYMM(timestamp) TTL toDate(timestamp) + toIntervalDay(90) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
CREATE TABLE posthog.sharded_heatmaps (
session_id String,
team_id Int64,
@@ -3079,6 +3119,42 @@ CREATE TABLE posthog.experiment_exposures_preaggregated (
computed_at DateTime64(6, 'UTC') DEFAULT now(),
expires_at Date DEFAULT today() + toIntervalDay(7)
) ENGINE = Distributed('posthog', 'posthog', 'sharded_experiment_exposures_preaggregated', cityHash64(entity_id));
+CREATE TABLE posthog.flag_evaluations (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1)),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64
+) ENGINE = Distributed('posthog', 'posthog', 'sharded_flag_evaluations', sipHash64(distinct_id));
CREATE TABLE posthog.heatmaps (
session_id String,
team_id Int64,
diff --git a/posthog/clickhouse/kafka_engine.py b/posthog/clickhouse/kafka_engine.py
index fe667c9274c0..5b446e229a73 100644
--- a/posthog/clickhouse/kafka_engine.py
+++ b/posthog/clickhouse/kafka_engine.py
@@ -29,6 +29,7 @@ CONSUMER_GROUP_DISTINCT_ID_USAGE = "clickhouse_distinct_id_usage"
CONSUMER_GROUP_TOPHOG = "clickhouse_tophog"
CONSUMER_GROUP_AI_EVENTS = "clickhouse_ai_events" if _US else "group1"
CONSUMER_GROUP_PROPERTY_VALUES = "clickhouse_property_values"
+CONSUMER_GROUP_FLAG_EVALUATIONS = "clickhouse_flag_evaluations"
# WarpStream consumer groups (separate from MSK so both can coexist)
CONSUMER_GROUP_LOG_ENTRIES_WS = "clickhouse_log_entries_ws"
diff --git a/posthog/clickhouse/migrations/0292_flag_evaluations.py b/posthog/clickhouse/migrations/0292_flag_evaluations.py
new file mode 100644
index 000000000000..1a641681e0c8
--- /dev/null
+++ b/posthog/clickhouse/migrations/0292_flag_evaluations.py
@@ -0,0 +1,37 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.models.flag_evaluations.sql import (
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,
+ FLAG_EVALUATIONS_MV_SQL,
+ FLAG_EVALUATIONS_TABLE_SQL,
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL,
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL,
+)
+
+operations = [
+ # 1. Sharded data table on the main cluster
+ run_sql_with_exceptions(
+ FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ # 2. Writable Distributed on the ingestion layer, fanning out to shards
+ run_sql_with_exceptions(
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ # 3. Distributed read table on data nodes
+ run_sql_with_exceptions(
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ # 4. Kafka engine table on the ingestion layer
+ run_sql_with_exceptions(
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ # 5. MV last, once its source and target exist
+ run_sql_with_exceptions(
+ FLAG_EVALUATIONS_MV_SQL(),
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index ae9ea76d440d..2ad3f6b92359 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0291_add_ai_channel_type
+0292_flag_evaluations
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 289c42d55901..31218ea0eee9 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -196,6 +196,13 @@ from posthog.models.exchange_rate.sql import (
EXCHANGE_RATE_TABLE_NAME,
EXCHANGE_RATE_TABLE_SQL,
)
+from posthog.models.flag_evaluations.sql import (
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,
+ FLAG_EVALUATIONS_MV_SQL,
+ FLAG_EVALUATIONS_TABLE_SQL,
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL,
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL,
+)
from posthog.models.group.sql import (
GROUPS_TABLE_MV_SQL,
GROUPS_TABLE_SQL,
@@ -380,6 +387,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
RAW_SESSIONS_TABLE_SQL,
SHARDED_RAW_SESSIONS_TABLE_SQL_V3,
HEATMAPS_TABLE_SQL,
+ FLAG_EVALUATIONS_TABLE_SQL,
PG_EMBEDDINGS_TABLE_SQL,
DOCUMENT_EMBEDDINGS_BUFFER_SHARDED_TABLE_SQL,
WEB_STATS_SQL,
@@ -451,6 +459,8 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
DISTRIBUTED_RAW_SESSIONS_TABLE_SQL_V3,
WRITABLE_HEATMAPS_TABLE_SQL,
DISTRIBUTED_HEATMAPS_TABLE_SQL,
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL,
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,
DISTRIBUTED_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
WRITABLE_QUERY_LOG_ARCHIVE_OPS_TABLE_SQL,
DISTRIBUTED_SYSTEM_PROCESSES_TABLE_SQL,
@@ -532,6 +542,7 @@ CREATE_KAFKA_TABLE_QUERIES = (
KAFKA_SESSION_REPLAY_EVENTS_TABLE_SQL,
KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL,
KAFKA_HEATMAPS_TABLE_SQL,
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL,
KAFKA_PRECALCULATED_EVENTS_TABLE_SQL,
KAFKA_PRECALCULATED_PERSON_PROPERTIES_TABLE_SQL,
KAFKA_COHORT_MEMBERSHIP_TABLE_SQL,
@@ -570,6 +581,7 @@ CREATE_MV_TABLE_QUERIES = (
RAW_SESSIONS_TABLE_MV_SQL_V3,
RAW_SESSIONS_TABLE_MV_RECORDINGS_SQL_V3,
HEATMAPS_TABLE_MV_SQL,
+ FLAG_EVALUATIONS_MV_SQL,
QUERY_LOG_ARCHIVE_OPS_MV_SQL(view_name=QUERY_LOG_ARCHIVE_OPS_MV, dest_table=WRITABLE_QUERY_LOG_ARCHIVE_TABLE),
COHORT_MEMBERSHIP_MV_SQL,
PRECALCULATED_EVENTS_MV_SQL,
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index a31163decd51..e541a6311a45 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -289,6 +289,49 @@
'''
# ---
+# name: test_create_kafka_table_with_different_kafka_host[kafka_flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS kafka_flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC'),
+ inserted_at DateTime64(6, 'UTC'),
+ distinct_id String,
+ session_id String,
+ device_id String,
+ flag_key String,
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String,
+ evaluated_at DateTime64(6, 'UTC'),
+ error String,
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String,
+ pathname String,
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String,
+ group_1 String,
+ group_2 String,
+ group_3 String,
+ group_4 String,
+ os_name LowCardinality(String)
+ )
+ ENGINE = Kafka(warpstream_ingestion, kafka_topic_list = 'clickhouse_flag_evaluations_test', kafka_group_name = 'clickhouse_flag_evaluations', kafka_format = 'JSONEachRow')
+ SETTINGS kafka_skip_broken_messages = 100
+
+ '''
+# ---
# name: test_create_kafka_table_with_different_kafka_host[kafka_groups]
'''
@@ -1857,6 +1900,98 @@
'''
# ---
+# name: test_create_table_query[flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1))
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = Distributed('posthog', 'posthog_test', 'sharded_flag_evaluations', sipHash64(distinct_id))
+
+ '''
+# ---
+# name: test_create_table_query[flag_evaluations_mv]
+ '''
+
+ CREATE MATERIALIZED VIEW IF NOT EXISTS flag_evaluations_mv
+ TO posthog_test.writable_flag_evaluations
+ AS SELECT
+ team_id,
+ uuid,
+ timestamp,
+ -- Fall back to the Kafka message timestamp, which is stable across replays
+ -- (inserted_at checkpoints the sync_feature_flag_last_called task).
+ if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,
+ distinct_id,
+ session_id,
+ device_id,
+ flag_key,
+ response,
+ flag_id,
+ flag_version,
+ reason,
+ request_id,
+ if(evaluated_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), timestamp, evaluated_at) AS evaluated_at,
+ error,
+ locally_evaluated,
+ lib,
+ lib_version,
+ is_server,
+ if(os = '', os_name, os) AS os,
+ os_version,
+ app_version,
+ current_url,
+ pathname,
+ country_code,
+ subdivision_1_code,
+ group_0,
+ group_1,
+ group_2,
+ group_3,
+ group_4,
+ _timestamp,
+ _offset,
+ _partition
+ FROM posthog_test.kafka_flag_evaluations
+
+ '''
+# ---
# name: test_create_table_query[groups]
'''
@@ -2423,6 +2558,49 @@
'''
# ---
+# name: test_create_table_query[kafka_flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS kafka_flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC'),
+ inserted_at DateTime64(6, 'UTC'),
+ distinct_id String,
+ session_id String,
+ device_id String,
+ flag_key String,
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String,
+ evaluated_at DateTime64(6, 'UTC'),
+ error String,
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String,
+ pathname String,
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String,
+ group_1 String,
+ group_2 String,
+ group_3 String,
+ group_4 String,
+ os_name LowCardinality(String)
+ )
+ ENGINE = Kafka(warpstream_ingestion, kafka_topic_list = 'clickhouse_flag_evaluations_test', kafka_group_name = 'clickhouse_flag_evaluations', kafka_format = 'JSONEachRow')
+ SETTINGS kafka_skip_broken_messages = 100
+
+ '''
+# ---
# name: test_create_table_query[kafka_groups]
'''
@@ -6749,6 +6927,64 @@
'''
# ---
+# name: test_create_table_query[sharded_flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1)),
+ INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX session_id_idx session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX request_id_idx request_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX inserted_at_idx inserted_at TYPE minmax GRANULARITY 1
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}')
+ -- Monthly, matching the events family. Daily partitions would put ~90 of them
+ -- under a 90-day TTL, and enough parts across them to strain merges. The cost
+ -- is coarser expiry: with ttl_only_drop_parts a part only drops once its newest
+ -- row expires, so rows survive up to a month past the TTL.
+ PARTITION BY toYYYYMM(timestamp)
+ ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id))
+
+ SETTINGS ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query[sharded_heatmaps]
'''
@@ -9001,6 +9237,52 @@
'''
# ---
+# name: test_create_table_query[writable_flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS writable_flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1))
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = Distributed('posthog', 'posthog_test', 'sharded_flag_evaluations', sipHash64(distinct_id))
+
+ '''
+# ---
# name: test_create_table_query[writable_groups]
'''
@@ -11614,6 +11896,64 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[sharded_flag_evaluations]
+ '''
+
+ CREATE TABLE IF NOT EXISTS sharded_flag_evaluations
+ (
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ distinct_id String CODEC(ZSTD(1)),
+ session_id String CODEC(ZSTD(1)),
+ device_id String CODEC(ZSTD(1)),
+ flag_key String CODEC(ZSTD(1)),
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String CODEC(ZSTD(1)),
+ evaluated_at DateTime64(6, 'UTC') DEFAULT timestamp CODEC(DoubleDelta, ZSTD(1)),
+ error String CODEC(ZSTD(1)),
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String CODEC(ZSTD(1)),
+ pathname String CODEC(ZSTD(1)),
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String CODEC(ZSTD(1)),
+ group_1 String CODEC(ZSTD(1)),
+ group_2 String CODEC(ZSTD(1)),
+ group_3 String CODEC(ZSTD(1)),
+ group_4 String CODEC(ZSTD(1)),
+ INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX session_id_idx session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX request_id_idx request_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX inserted_at_idx inserted_at TYPE minmax GRANULARITY 1
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}')
+ -- Monthly, matching the events family. Daily partitions would put ~90 of them
+ -- under a 90-day TTL, and enough parts across them to strain merges. The cost
+ -- is coarser expiry: with ttl_only_drop_parts a part only drops once its newest
+ -- row expires, so rows survive up to a month past the TTL.
+ PARTITION BY toYYYYMM(timestamp)
+ ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id))
+
+ SETTINGS ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query_replicated_and_storage[sharded_heatmaps]
'''
diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.py
index 8934e4ea633e..368e296e3d7a 100644
--- a/posthog/clickhouse/test/test_schema.py
+++ b/posthog/clickhouse/test/test_schema.py
@@ -2,7 +2,7 @@ import uuid
import pytest
-from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_EVENTS_JSON_NATIVE_JSON
+from posthog.clickhouse.kafka_engine import CONSUMER_GROUP_EVENTS_JSON_NATIVE_JSON, KAFKA_COLUMNS_WITH_PARTITION
from posthog.clickhouse.schema import (
CREATE_KAFKA_TABLE_QUERIES,
CREATE_MERGETREE_TABLE_QUERIES,
@@ -16,6 +16,7 @@ from posthog.models.event.sql import (
KAFKA_EVENTS_NATIVE_JSON_TABLE,
KAFKA_EVENTS_NATIVE_JSON_TABLE_SQL,
)
+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_KAFKA_COLUMNS, FLAG_EVALUATIONS_MV_SQL
@pytest.mark.parametrize("query", CREATE_TABLE_QUERIES, ids=get_table_name)
@@ -53,6 +54,39 @@ def test_events_json_table_uses_dedicated_kafka_consumer_group(settings):
assert f"FROM {settings.CLICKHOUSE_DATABASE}.{KAFKA_EVENTS_NATIVE_JSON_TABLE}" in mv_query
+def _declared_column_names(block: str) -> list[str]:
+ names: list[str] = []
+ for raw_line in block.splitlines():
+ line = raw_line.strip().lstrip(",").strip()
+ if not line or line.startswith("--"):
+ continue
+ names.append(line.split()[0])
+ return names
+
+
+def _mv_projected_names(mv_sql: str) -> list[str]:
+ projection = mv_sql.split("AS SELECT", 1)[1].split("\nFROM ", 1)[0]
+ names: list[str] = []
+ for raw_line in projection.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("--"):
+ continue
+ names.append(line.rstrip(",").rsplit(" AS ", 1)[-1].strip())
+ return names
+
+
+def test_flag_evaluations_mv_projection_matches_column_template():
+ # Every flag_evaluations table renders from one column template, but the MV
+ # hand-writes its SELECT projection. Order matters as much as membership: the
+ # MV writes to writable_flag_evaluations positionally, so a dropped or
+ # reordered column lands data in the wrong column without raising.
+ template_columns = _declared_column_names(FLAG_EVALUATIONS_KAFKA_COLUMNS)
+ assert template_columns
+
+ kafka_meta_columns = _declared_column_names(KAFKA_COLUMNS_WITH_PARTITION)
+ assert _mv_projected_names(FLAG_EVALUATIONS_MV_SQL()) == template_columns + kafka_meta_columns
+
+
@pytest.fixture(autouse=True)
def mock_uuid4(mocker):
mock_uuid4 = mocker.patch("uuid.uuid4")
diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.py
index d9e89e02d79d..08a9e79d7009 100644
--- a/posthog/kafka_client/topics.py
+++ b/posthog/kafka_client/topics.py
@@ -38,6 +38,7 @@ KAFKA_MESSAGE_ASSETS = f"{KAFKA_PREFIX}clickhouse_message_assets{SUFFIX}"
KAFKA_CLICKHOUSE_HEATMAP_EVENTS = f"{KAFKA_PREFIX}clickhouse_heatmap_events{SUFFIX}"
KAFKA_CLICKHOUSE_AI_EVENTS_JSON = f"{KAFKA_PREFIX}clickhouse_ai_events_json{SUFFIX}"
+KAFKA_CLICKHOUSE_FLAG_EVALUATIONS = f"{KAFKA_PREFIX}clickhouse_flag_evaluations{SUFFIX}"
# Legacy session recording topic — only retained because clickhouse migration 0063 still
# DROPs the old materialized view by name. Producers/consumers live in the Node.js services.
diff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.py
new file mode 100644
index 000000000000..8ec61939e50d
--- /dev/null
+++ b/posthog/models/flag_evaluations/sql.py
@@ -0,0 +1,240 @@
+from django.conf import settings
+
+from posthog.clickhouse.kafka_engine import (
+ CONSUMER_GROUP_FLAG_EVALUATIONS,
+ KAFKA_COLUMNS_WITH_PARTITION,
+ kafka_engine,
+ ttl_period,
+)
+from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme
+from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_FLAG_EVALUATIONS
+
+# Flag evaluation telemetry ($feature_flag_called events routed out of the events
+# table). One row per evaluation, personless, fixed schema, 90-day retention.
+#
+# Naming convention follows the sharded main-cluster table family (see heatmaps):
+# * `sharded_flag_evaluations` — sharded replicated MergeTree on DATA nodes.
+# * `writable_flag_evaluations` — Distributed write path on the ingestion layer,
+# fans rows out to shards by the distinct_id hash.
+# * `flag_evaluations` — Distributed read path on DATA nodes. This is the name
+# HogQL will expose as `posthog.flag_evaluations`.
+# * `kafka_flag_evaluations` — Kafka engine table on the ingestion layer.
+# * `flag_evaluations_mv` — MV on the ingestion layer, kafka → writable.
+FLAG_EVALUATIONS_TABLE = "flag_evaluations"
+FLAG_EVALUATIONS_DATA_TABLE = f"sharded_{FLAG_EVALUATIONS_TABLE}"
+FLAG_EVALUATIONS_WRITABLE_TABLE = f"writable_{FLAG_EVALUATIONS_TABLE}"
+KAFKA_FLAG_EVALUATIONS_TABLE = f"kafka_{FLAG_EVALUATIONS_TABLE}"
+FLAG_EVALUATIONS_MV_TABLE = f"{FLAG_EVALUATIONS_TABLE}_mv"
+
+FLAG_EVALUATIONS_TTL_DAYS = 90
+
+# Sharding by a distinct_id hash rather than anything team-based: a handful of
+# teams carry most of the volume, and sharding by team would hotspot single
+# shards. sipHash64 matches the events table's Distributed sharding key, so a
+# given distinct_id lands on the same shard in both tables and the events-table
+# backfill runs shard-local, with no network shuffle.
+FLAG_EVALUATIONS_SHARDING_KEY = "sipHash64(distinct_id)"
+
+# The sort key matches the queries we run: per-flag usage over a date range,
+# uniques by distinct_id. toDate(timestamp) sits inside it because PARTITION BY
+# is monthly — without it, a one-day query for one flag would read that flag's
+# whole month. The trailing hash intentionally differs from the sharding key —
+# cityHash64 is the events table's convention for within-shard ordering — and a
+# MergeTree ORDER BY is immutable once data exists, so the two must not silently
+# move together.
+FLAG_EVALUATIONS_ORDER_BY = "(team_id, flag_key, toDate(timestamp), cityHash64(distinct_id))"
+
+# One canonical column list, rendered in a Kafka variant and a storage variant.
+#
+# The Kafka engine table must NOT carry the timestamp DEFAULTs: JSONEachRow
+# fills omitted fields with the column default, and the MV's legacy-SDK
+# fallbacks detect exactly that zero-value sentinel — a DEFAULT there would mask
+# it. Both Distributed tables MUST carry them: an INSERT through a Distributed
+# table fills omitted columns from the Distributed table's own schema before
+# forwarding to the shard, so without them a direct insert via
+# writable_flag_evaluations would store epoch instead of the sharded table's
+# fallback. That makes the Distributed and sharded column lists identical, which
+# is also how the events family declares its CODECs.
+_FLAG_EVALUATIONS_COLUMNS_TEMPLATE = """
+ team_id Int64,
+ uuid UUID,
+ timestamp DateTime64(6, 'UTC'){dt_codec},
+ inserted_at DateTime64(6, 'UTC'){ts_default}{dt_codec},
+ distinct_id String{codec},
+ session_id String{codec},
+ device_id String{codec},
+ flag_key String{codec},
+ response LowCardinality(String),
+ flag_id UInt64,
+ flag_version UInt32,
+ reason LowCardinality(String),
+ request_id String{codec},
+ evaluated_at DateTime64(6, 'UTC'){ts_default}{dt_codec},
+ error String{codec},
+ locally_evaluated Bool,
+ lib LowCardinality(String),
+ lib_version LowCardinality(String),
+ is_server Bool,
+ os LowCardinality(String),
+ os_version LowCardinality(String),
+ app_version LowCardinality(String),
+ current_url String{codec},
+ pathname String{codec},
+ country_code LowCardinality(String),
+ subdivision_1_code LowCardinality(String),
+ group_0 String{codec},
+ group_1 String{codec},
+ group_2 String{codec},
+ group_3 String{codec},
+ group_4 String{codec}
+""".strip()
+
+FLAG_EVALUATIONS_KAFKA_COLUMNS = _FLAG_EVALUATIONS_COLUMNS_TEMPLATE.format(ts_default="", codec="", dt_codec="")
+
+# ZSTD on the plain String columns and DoubleDelta on the timestamps;
+# LowCardinality columns compress well on their own.
+_FLAG_EVALUATIONS_STORAGE_COLUMNS = _FLAG_EVALUATIONS_COLUMNS_TEMPLATE.format(
+ ts_default=" DEFAULT timestamp",
+ codec=" CODEC(ZSTD(1))",
+ dt_codec=" CODEC(DoubleDelta, ZSTD(1))",
+)
+
+
+def FLAG_EVALUATIONS_DATA_TABLE_ENGINE() -> MergeTreeEngine:
+ # Plain (non-replacing) MergeTree: Kafka replay duplicates are accepted for
+ # this telemetry, matching heatmaps. ZK path uses the base table name.
+ return MergeTreeEngine(FLAG_EVALUATIONS_TABLE, replication_scheme=ReplicationScheme.SHARDED)
+
+
+# The actual data lives on the sharded main cluster.
+#
+# The bloom filters cover point lookups the sort key can't serve (a specific
+# user, session, or flags-service request). The minmax on inserted_at serves
+# incremental consumers that checkpoint on it: partitioning is on timestamp, so
+# an inserted_at range predicate prunes no partitions on its own and would
+# otherwise read all 90 days. A skip index only covers parts written after it
+# exists, so retrofitting one means a full MATERIALIZE INDEX mutation — much
+# cheaper to declare up front.
+#
+# The DEFAULTs mean a direct insert that omits evaluated_at or inserted_at
+# (tests, the planned events-table backfill) falls back to the row's own
+# timestamp rather than the wall-clock insert time, so a bulk historical
+# backfill doesn't stamp every row as freshly inserted right now: that would
+# break anything windowing or checkpointing on inserted_at. Neither DEFAULT
+# reproduces the MV's Kafka-path fallback exactly (_timestamp, the Kafka broker
+# time, isn't available to a column default), but timestamp is the closest
+# available proxy for both columns.
+FLAG_EVALUATIONS_TABLE_SQL = lambda: (
+ f"""
+CREATE TABLE IF NOT EXISTS {FLAG_EVALUATIONS_DATA_TABLE}
+(
+ {_FLAG_EVALUATIONS_STORAGE_COLUMNS},
+ INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX session_id_idx session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX request_id_idx request_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX inserted_at_idx inserted_at TYPE minmax GRANULARITY 1
+ {KAFKA_COLUMNS_WITH_PARTITION}
+)
+ENGINE = {FLAG_EVALUATIONS_DATA_TABLE_ENGINE()}
+-- Monthly, matching the events family. Daily partitions would put ~90 of them
+-- under a 90-day TTL, and enough parts across them to strain merges. The cost
+-- is coarser expiry: with ttl_only_drop_parts a part only drops once its newest
+-- row expires, so rows survive up to a month past the TTL.
+PARTITION BY toYYYYMM(timestamp)
+ORDER BY {FLAG_EVALUATIONS_ORDER_BY}
+{ttl_period("timestamp", FLAG_EVALUATIONS_TTL_DAYS, unit="DAY")}
+SETTINGS ttl_only_drop_parts = 1
+"""
+)
+
+
+def _distributed_table_sql(table_name: str) -> str:
+ return f"""
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ {_FLAG_EVALUATIONS_STORAGE_COLUMNS}
+ {KAFKA_COLUMNS_WITH_PARTITION}
+)
+ENGINE = {Distributed(data_table=FLAG_EVALUATIONS_DATA_TABLE, sharding_key=FLAG_EVALUATIONS_SHARDING_KEY)}
+"""
+
+
+# Fans writes out to sharded_flag_evaluations. Lives on the ingestion layer.
+WRITABLE_FLAG_EVALUATIONS_TABLE_SQL = lambda: _distributed_table_sql(FLAG_EVALUATIONS_WRITABLE_TABLE)
+
+# Read path on DATA nodes, and the name queries use.
+DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL = lambda: _distributed_table_sql(FLAG_EVALUATIONS_TABLE)
+
+
+# `os_name` exists only here: mobile SDKs send $os_name where browser SDKs send
+# $os, and the MV coalesces the two into the single stored `os` column.
+KAFKA_FLAG_EVALUATIONS_TABLE_SQL = lambda: (
+ f"""
+CREATE TABLE IF NOT EXISTS {KAFKA_FLAG_EVALUATIONS_TABLE}
+(
+ {FLAG_EVALUATIONS_KAFKA_COLUMNS},
+ os_name LowCardinality(String)
+)
+ENGINE = {
+ kafka_engine(
+ topic=KAFKA_CLICKHOUSE_FLAG_EVALUATIONS,
+ group=CONSUMER_GROUP_FLAG_EVALUATIONS,
+ named_collection=settings.CLICKHOUSE_KAFKA_WARPSTREAM_INGESTION_NAMED_COLLECTION,
+ )
+ }
+SETTINGS kafka_skip_broken_messages = 100
+"""
+)
+
+
+# The MV defends against absent properties from legacy SDKs: the Kafka
+# JSONEachRow parser fills missing fields with the type's zero value, so
+# DateTime64 columns read as epoch when a producer omits them. `flag_id` and
+# `flag_version` zero-fill to 0, which is the accepted sentinel for "SDK too
+# old to send it" — no substitution needed.
+_EPOCH_DT64 = "toDateTime64('1970-01-01 00:00:00', 6, 'UTC')"
+
+FLAG_EVALUATIONS_MV_SQL = lambda: (
+ f"""
+CREATE MATERIALIZED VIEW IF NOT EXISTS {FLAG_EVALUATIONS_MV_TABLE}
+TO {settings.CLICKHOUSE_DATABASE}.{FLAG_EVALUATIONS_WRITABLE_TABLE}
+AS SELECT
+ team_id,
+ uuid,
+ timestamp,
+ -- Fall back to the Kafka message timestamp, which is stable across replays
+ -- (inserted_at checkpoints the sync_feature_flag_last_called task).
+ if(inserted_at = {_EPOCH_DT64}, _timestamp, inserted_at) AS inserted_at,
+ distinct_id,
+ session_id,
+ device_id,
+ flag_key,
+ response,
+ flag_id,
+ flag_version,
+ reason,
+ request_id,
+ if(evaluated_at = {_EPOCH_DT64}, timestamp, evaluated_at) AS evaluated_at,
+ error,
+ locally_evaluated,
+ lib,
+ lib_version,
+ is_server,
+ if(os = '', os_name, os) AS os,
+ os_version,
+ app_version,
+ current_url,
+ pathname,
+ country_code,
+ subdivision_1_code,
+ group_0,
+ group_1,
+ group_2,
+ group_3,
+ group_4,
+ _timestamp,
+ _offset,
+ _partition
+FROM {settings.CLICKHOUSE_DATABASE}.{KAFKA_FLAG_EVALUATIONS_TABLE}
+"""
+)