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): mirror the events schema in flag_evaluations (#80994)

Phil Haackb38bae0b4607
diff --git a/posthog/clickhouse/hcl/golden/local-multi/data.hcl b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
index eb18641c3441..9347ba413bdf 100644
--- a/posthog/clickhouse/hcl/golden/local-multi/data.hcl
+++ b/posthog/clickhouse/hcl/golden/local-multi/data.hcl
@@ -1689,100 +1689,87 @@ database "posthog" {
}
table "flag_evaluations" {
- column "team_id" {
- type = "Int64"
- }
column "uuid" {
type = "UUID"
}
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "properties" {
+ type = "String"
+ }
column "timestamp" {
type = "DateTime64(6, 'UTC')"
}
- column "inserted_at" {
- type = "DateTime64(6, 'UTC')"
- default = "timestamp"
+ column "team_id" {
+ type = "Int64"
}
column "distinct_id" {
type = "String"
}
- column "session_id" {
- type = "String"
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
}
- column "device_id" {
- type = "String"
+ column "person_id" {
+ type = "UUID"
}
- column "flag_key" {
+ column "person_properties" {
type = "String"
}
- column "response" {
- type = "LowCardinality(String)"
+ column "group0_properties" {
+ type = "String"
}
- column "flag_id" {
- type = "UInt64"
+ column "group1_properties" {
+ type = "String"
}
- column "flag_version" {
- type = "UInt32"
+ column "group2_properties" {
+ type = "String"
}
- column "reason" {
- type = "LowCardinality(String)"
+ column "group3_properties" {
+ type = "String"
}
- column "request_id" {
+ column "group4_properties" {
type = "String"
}
- column "evaluated_at" {
+ column "inserted_at" {
type = "DateTime64(6, 'UTC')"
default = "timestamp"
}
- column "error" {
- type = "String"
- }
- 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"
+ column "$group_0" {
+ type = "String"
+ comment = "column_materializer::$group_0"
}
- column "pathname" {
- type = "String"
+ column "$group_1" {
+ type = "String"
+ comment = "column_materializer::$group_1"
}
- column "country_code" {
- type = "LowCardinality(String)"
+ column "$group_2" {
+ type = "String"
+ comment = "column_materializer::$group_2"
}
- column "subdivision_1_code" {
- type = "LowCardinality(String)"
+ column "$group_3" {
+ type = "String"
+ comment = "column_materializer::$group_3"
}
- column "group_0" {
- type = "String"
+ column "$group_4" {
+ type = "String"
+ comment = "column_materializer::$group_4"
}
- column "group_1" {
- type = "String"
+ column "flag_key" {
+ type = "String"
+ comment = "column_materializer::properties::$feature_flag"
}
- column "group_2" {
- type = "String"
+ column "response" {
+ type = "LowCardinality(String)"
+ comment = "column_materializer::properties::$feature_flag_response"
}
- column "group_3" {
- type = "String"
+ column "session_id" {
+ type = "String"
+ comment = "column_materializer::properties::$session_id"
}
- column "group_4" {
- type = "String"
+ column "request_id" {
+ type = "String"
+ comment = "column_materializer::properties::$feature_flag_request_id"
}
column "_timestamp" {
type = "DateTime"
@@ -6125,100 +6112,96 @@ database "posthog" {
index_granularity = "8192"
ttl_only_drop_parts = "1"
}
- column "team_id" {
- type = "Int64"
- }
column "uuid" {
type = "UUID"
}
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "properties" {
+ type = "String"
+ }
column "timestamp" {
type = "DateTime64(6, 'UTC')"
}
- column "inserted_at" {
- type = "DateTime64(6, 'UTC')"
- default = "timestamp"
+ column "team_id" {
+ type = "Int64"
}
column "distinct_id" {
type = "String"
}
- column "session_id" {
- type = "String"
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
}
- column "device_id" {
- type = "String"
+ column "person_id" {
+ type = "UUID"
}
- column "flag_key" {
+ column "person_properties" {
type = "String"
}
- column "response" {
- type = "LowCardinality(String)"
+ column "group0_properties" {
+ type = "String"
}
- column "flag_id" {
- type = "UInt64"
+ column "group1_properties" {
+ type = "String"
}
- column "flag_version" {
- type = "UInt32"
+ column "group2_properties" {
+ type = "String"
}
- column "reason" {
- type = "LowCardinality(String)"
+ column "group3_properties" {
+ type = "String"
}
- column "request_id" {
+ column "group4_properties" {
type = "String"
}
- column "evaluated_at" {
+ column "inserted_at" {
type = "DateTime64(6, 'UTC')"
default = "timestamp"
}
- column "error" {
- type = "String"
- }
- 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"
+ column "$group_0" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^\"|\"$', '')"
+ comment = "column_materializer::$group_0"
}
- column "pathname" {
- type = "String"
+ column "$group_1" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^\"|\"$', '')"
+ comment = "column_materializer::$group_1"
}
- column "country_code" {
- type = "LowCardinality(String)"
+ column "$group_2" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_2'), '^\"|\"$', '')"
+ comment = "column_materializer::$group_2"
}
- column "subdivision_1_code" {
- type = "LowCardinality(String)"
+ column "$group_3" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_3'), '^\"|\"$', '')"
+ comment = "column_materializer::$group_3"
}
- column "group_0" {
- type = "String"
+ column "$group_4" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_4'), '^\"|\"$', '')"
+ comment = "column_materializer::$group_4"
}
- column "group_1" {
- type = "String"
+ column "flag_key" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^\"|\"$', '')"
+ comment = "column_materializer::properties::$feature_flag"
}
- column "group_2" {
- type = "String"
+ column "response" {
+ type = "LowCardinality(String)"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_response'), '^\"|\"$', '')"
+ comment = "column_materializer::properties::$feature_flag_response"
}
- column "group_3" {
- type = "String"
+ column "session_id" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$session_id'), '^\"|\"$', '')"
+ comment = "column_materializer::properties::$session_id"
}
- column "group_4" {
- type = "String"
+ column "request_id" {
+ type = "String"
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_request_id'), '^\"|\"$', '')"
+ comment = "column_materializer::properties::$feature_flag_request_id"
}
column "_timestamp" {
type = "DateTime"
@@ -6234,6 +6217,11 @@ database "posthog" {
type = "bloom_filter(0.01)"
granularity = 1
}
+ index "person_id_idx" {
+ expr = "person_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
index "session_id_idx" {
expr = "session_id"
type = "bloom_filter(0.01)"
diff --git a/posthog/clickhouse/hcl/roles/data/local/tables.hcl b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
index 0291532fb210..0288b9be12e3 100644
--- a/posthog/clickhouse/hcl/roles/data/local/tables.hcl
+++ b/posthog/clickhouse/hcl/roles/data/local/tables.hcl
@@ -1,100 +1,91 @@
database "posthog" {
+ # Mirrors the events column set minus events' materialized property columns, with
+ # the full properties JSON kept as the source of truth. The materialized columns
+ # below carry their expression only on sharded_flag_evaluations; the Distributed
+ # proxy repeats them plain, because a Distributed engine computes nothing.
table "_flag_evaluations_columns" {
abstract = true
- column "team_id" {
- type = "Int64"
- }
column "uuid" {
type = "UUID"
}
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "properties" {
+ type = "String"
+ }
column "timestamp" {
type = "DateTime64(6, 'UTC')"
}
- column "inserted_at" {
- type = "DateTime64(6, 'UTC')"
- default = "timestamp"
+ column "team_id" {
+ type = "Int64"
}
column "distinct_id" {
type = "String"
}
- column "session_id" {
- type = "String"
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
}
- column "device_id" {
- type = "String"
+ column "person_id" {
+ type = "UUID"
}
- column "flag_key" {
+ column "person_properties" {
type = "String"
}
- column "response" {
- type = "LowCardinality(String)"
+ column "group0_properties" {
+ type = "String"
}
- column "flag_id" {
- type = "UInt64"
+ column "group1_properties" {
+ type = "String"
}
- column "flag_version" {
- type = "UInt32"
+ column "group2_properties" {
+ type = "String"
}
- column "reason" {
- type = "LowCardinality(String)"
+ column "group3_properties" {
+ type = "String"
}
- column "request_id" {
+ column "group4_properties" {
type = "String"
}
- column "evaluated_at" {
+ column "inserted_at" {
type = "DateTime64(6, 'UTC')"
default = "timestamp"
}
- column "error" {
- type = "String"
- }
- 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"
+ column "$group_0" {
+ type = "String"
+ comment = "column_materializer::$group_0"
}
- column "pathname" {
- type = "String"
+ column "$group_1" {
+ type = "String"
+ comment = "column_materializer::$group_1"
}
- column "country_code" {
- type = "LowCardinality(String)"
+ column "$group_2" {
+ type = "String"
+ comment = "column_materializer::$group_2"
}
- column "subdivision_1_code" {
- type = "LowCardinality(String)"
+ column "$group_3" {
+ type = "String"
+ comment = "column_materializer::$group_3"
}
- column "group_0" {
- type = "String"
+ column "$group_4" {
+ type = "String"
+ comment = "column_materializer::$group_4"
}
- column "group_1" {
- type = "String"
+ column "flag_key" {
+ type = "String"
+ comment = "column_materializer::properties::$feature_flag"
}
- column "group_2" {
- type = "String"
+ column "response" {
+ type = "LowCardinality(String)"
+ comment = "column_materializer::properties::$feature_flag_response"
}
- column "group_3" {
- type = "String"
+ column "session_id" {
+ type = "String"
+ comment = "column_materializer::properties::$session_id"
}
- column "group_4" {
- type = "String"
+ column "request_id" {
+ type = "String"
+ comment = "column_materializer::properties::$feature_flag_request_id"
}
column "_timestamp" {
type = "DateTime"
@@ -3586,11 +3577,43 @@ database "posthog" {
ttl_only_drop_parts = "1"
}
extend = "_flag_evaluations_columns"
+ patch_column "$group_0" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^\"|\"$', '')"
+ }
+ patch_column "$group_1" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^\"|\"$', '')"
+ }
+ patch_column "$group_2" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_2'), '^\"|\"$', '')"
+ }
+ patch_column "$group_3" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_3'), '^\"|\"$', '')"
+ }
+ patch_column "$group_4" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$group_4'), '^\"|\"$', '')"
+ }
+ patch_column "flag_key" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^\"|\"$', '')"
+ }
+ patch_column "response" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_response'), '^\"|\"$', '')"
+ }
+ patch_column "session_id" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$session_id'), '^\"|\"$', '')"
+ }
+ patch_column "request_id" {
+ materialized = "replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_request_id'), '^\"|\"$', '')"
+ }
index "distinct_id_idx" {
expr = "distinct_id"
type = "bloom_filter(0.01)"
granularity = 1
}
+ index "person_id_idx" {
+ expr = "person_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
index "session_id_idx" {
expr = "session_id"
type = "bloom_filter(0.01)"
diff --git a/posthog/clickhouse/hcl/sql/local-multi/data.sql b/posthog/clickhouse/hcl/sql/local-multi/data.sql
index 0815e905de27..5d74dd07abef 100644
--- a/posthog/clickhouse/hcl/sql/local-multi/data.sql
+++ b/posthog/clickhouse/hcl/sql/local-multi/data.sql
@@ -1172,41 +1172,35 @@ CREATE TABLE posthog.sharded_experiment_exposures_preaggregated (
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,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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,
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ $group_0 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^"|"$', '') COMMENT 'column_materializer::$group_0',
+ $group_1 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^"|"$', '') COMMENT 'column_materializer::$group_1',
+ $group_2 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_2'), '^"|"$', '') COMMENT 'column_materializer::$group_2',
+ $group_3 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_3'), '^"|"$', '') COMMENT 'column_materializer::$group_3',
+ $group_4 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_4'), '^"|"$', '') COMMENT 'column_materializer::$group_4',
+ flag_key String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag',
+ response LowCardinality(String) MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_response'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_response',
+ session_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$session_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$session_id',
+ request_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_request_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_request_id',
_timestamp DateTime,
_offset UInt64,
_partition UInt64,
INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX person_id_idx person_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
@@ -3122,37 +3116,30 @@ CREATE TABLE posthog.experiment_exposures_preaggregated (
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,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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,
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ $group_0 String COMMENT 'column_materializer::$group_0',
+ $group_1 String COMMENT 'column_materializer::$group_1',
+ $group_2 String COMMENT 'column_materializer::$group_2',
+ $group_3 String COMMENT 'column_materializer::$group_3',
+ $group_4 String COMMENT 'column_materializer::$group_4',
+ flag_key String COMMENT 'column_materializer::properties::$feature_flag',
+ response LowCardinality(String) COMMENT 'column_materializer::properties::$feature_flag_response',
+ session_id String COMMENT 'column_materializer::properties::$session_id',
+ request_id String COMMENT 'column_materializer::properties::$feature_flag_request_id',
_timestamp DateTime,
_offset UInt64,
_partition UInt64
diff --git a/posthog/clickhouse/migrations/0297_flag_evaluations_events_mirror.py b/posthog/clickhouse/migrations/0297_flag_evaluations_events_mirror.py
new file mode 100644
index 000000000000..791770248425
--- /dev/null
+++ b/posthog/clickhouse/migrations/0297_flag_evaluations_events_mirror.py
@@ -0,0 +1,71 @@
+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_DATA_TABLE,
+ FLAG_EVALUATIONS_MV_SQL,
+ FLAG_EVALUATIONS_MV_TABLE,
+ FLAG_EVALUATIONS_TABLE,
+ FLAG_EVALUATIONS_TABLE_SQL,
+ FLAG_EVALUATIONS_WRITABLE_TABLE,
+ KAFKA_FLAG_EVALUATIONS_TABLE,
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL,
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL,
+)
+
+# Reshapes flag_evaluations before launch, replacing the typed flag columns 0292
+# created. posthog/models/flag_evaluations/sql.py carries the rationale for the
+# shape.
+#
+# Drop-and-recreate rather than ALTER: nothing produces to the topic yet, so every
+# table in the family is empty; recreating from the canonical column template can't
+# drift from what a fresh install gets out of schema.py; and it avoids DROP COLUMN
+# mutations, which can get stuck and block releases. The sharded table is
+# replicated, so its drop carries SYNC to clear ZooKeeper metadata before the
+# recreate. The Distributed, Kafka, and MV objects are not replicated and drop
+# plain.
+#
+# Drops run in reverse dependency order (MV → its Kafka source → the Distributed
+# fronts → storage); recreates mirror 0292's order and node roles.
+operations = [
+ run_sql_with_exceptions(
+ f"DROP TABLE IF EXISTS {FLAG_EVALUATIONS_MV_TABLE}",
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ run_sql_with_exceptions(
+ f"DROP TABLE IF EXISTS {KAFKA_FLAG_EVALUATIONS_TABLE}",
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ run_sql_with_exceptions(
+ f"DROP TABLE IF EXISTS {FLAG_EVALUATIONS_TABLE}",
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ f"DROP TABLE IF EXISTS {FLAG_EVALUATIONS_WRITABLE_TABLE}",
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ run_sql_with_exceptions(
+ f"DROP TABLE IF EXISTS {FLAG_EVALUATIONS_DATA_TABLE} SYNC",
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ WRITABLE_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ KAFKA_FLAG_EVALUATIONS_TABLE_SQL(),
+ node_roles=[NodeRole.INGESTION_MEDIUM],
+ ),
+ 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 7ee0b6131720..b75f23b80c0a 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0296_logs_volume_buckets_time_bucket
+0297_flag_evaluations_events_mirror
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index 7307feccc820..a44bb4562cdc 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -295,38 +295,21 @@
CREATE TABLE IF NOT EXISTS kafka_flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC'),
+ team_id Int64,
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)
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC')
)
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
@@ -1908,37 +1891,32 @@
CREATE TABLE IF NOT EXISTS flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp
+
+ , $group_0 String COMMENT 'column_materializer::$group_0'
+ , $group_1 String COMMENT 'column_materializer::$group_1'
+ , $group_2 String COMMENT 'column_materializer::$group_2'
+ , $group_3 String COMMENT 'column_materializer::$group_3'
+ , $group_4 String COMMENT 'column_materializer::$group_4'
+ , flag_key String COMMENT 'column_materializer::properties::$feature_flag'
+ , response LowCardinality(String) COMMENT 'column_materializer::properties::$feature_flag_response'
+ , session_id String COMMENT 'column_materializer::properties::$session_id'
+ , request_id String COMMENT 'column_materializer::properties::$feature_flag_request_id'
+
, _timestamp DateTime
, _offset UInt64
@@ -1955,39 +1933,24 @@
CREATE MATERIALIZED VIEW IF NOT EXISTS flag_evaluations_mv
TO posthog_test.writable_flag_evaluations
AS SELECT
- team_id,
uuid,
+ event,
+ properties,
timestamp,
+ team_id,
+ distinct_id,
+ created_at,
+ person_id,
+ person_properties,
+ group0_properties,
+ group1_properties,
+ group2_properties,
+ group3_properties,
+ group4_properties,
-- Fall back to the Kafka message timestamp, which is stable across replays
- -- (inserted_at checkpoints the sync_feature_flag_last_called task).
+ -- (inserted_at checkpoints the sync_feature_flag_last_called task, and an
+ -- epoch-stamped row would stay invisible to it forever).
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
@@ -2567,38 +2530,21 @@
CREATE TABLE IF NOT EXISTS kafka_flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC'),
+ team_id Int64,
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)
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC')
)
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
@@ -6966,41 +6912,39 @@
CREATE TABLE IF NOT EXISTS sharded_flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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,
- 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
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp
+
+ , $group_0 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^"|"$', '') COMMENT 'column_materializer::$group_0'
+ , $group_1 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^"|"$', '') COMMENT 'column_materializer::$group_1'
+ , $group_2 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_2'), '^"|"$', '') COMMENT 'column_materializer::$group_2'
+ , $group_3 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_3'), '^"|"$', '') COMMENT 'column_materializer::$group_3'
+ , $group_4 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_4'), '^"|"$', '') COMMENT 'column_materializer::$group_4'
+ , flag_key String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag'
+ , response LowCardinality(String) MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_response'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_response'
+ , session_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$session_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$session_id'
+ , request_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_request_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_request_id'
+
+
+ , INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1
+ , INDEX person_id_idx person_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
@@ -9277,37 +9221,22 @@
CREATE TABLE IF NOT EXISTS writable_flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp
+
, _timestamp DateTime
, _offset UInt64
@@ -11959,41 +11888,39 @@
CREATE TABLE IF NOT EXISTS sharded_flag_evaluations
(
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC') DEFAULT timestamp,
+ team_id Int64,
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') DEFAULT timestamp,
- 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,
- 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
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC') DEFAULT timestamp
+
+ , $group_0 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_0'), '^"|"$', '') COMMENT 'column_materializer::$group_0'
+ , $group_1 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_1'), '^"|"$', '') COMMENT 'column_materializer::$group_1'
+ , $group_2 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_2'), '^"|"$', '') COMMENT 'column_materializer::$group_2'
+ , $group_3 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_3'), '^"|"$', '') COMMENT 'column_materializer::$group_3'
+ , $group_4 String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$group_4'), '^"|"$', '') COMMENT 'column_materializer::$group_4'
+ , flag_key String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag'
+ , response LowCardinality(String) MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_response'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_response'
+ , session_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$session_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$session_id'
+ , request_id String MATERIALIZED replaceRegexpAll(JSONExtractRaw(properties, '$feature_flag_request_id'), '^"|"$', '') COMMENT 'column_materializer::properties::$feature_flag_request_id'
+
+
+ , INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1
+ , INDEX person_id_idx person_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
diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.py
index 368e296e3d7a..17be8e15860c 100644
--- a/posthog/clickhouse/test/test_schema.py
+++ b/posthog/clickhouse/test/test_schema.py
@@ -1,4 +1,6 @@
+import re
import uuid
+from collections.abc import Iterator
import pytest
@@ -16,7 +18,12 @@ 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
+from posthog.models.flag_evaluations.sql import (
+ DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,
+ FLAG_EVALUATIONS_KAFKA_COLUMNS,
+ FLAG_EVALUATIONS_MV_SQL,
+ FLAG_EVALUATIONS_TABLE_SQL,
+)
@pytest.mark.parametrize("query", CREATE_TABLE_QUERIES, ids=get_table_name)
@@ -54,14 +61,30 @@ 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] = []
+def _column_definition_lines(block: str) -> Iterator[str]:
for raw_line in block.splitlines():
line = raw_line.strip().lstrip(",").strip()
- if not line or line.startswith("--"):
+ if not line or line.startswith("--") or line.startswith("INDEX "):
continue
- names.append(line.split()[0])
- return names
+ yield line
+
+
+def _declared_column_names(block: str) -> list[str]:
+ return [line.split()[0] for line in _column_definition_lines(block)]
+
+
+# Cuts a column definition down to its name and type, so a parenthesized type
+# survives intact while a MATERIALIZED expression or a COMMENT is dropped.
+_COLUMN_MODIFIER = re.compile(r"\s+(?:MATERIALIZED|DEFAULT|ALIAS|COMMENT|CODEC)\b")
+
+
+def _flag_evaluations_table_columns(create_sql: str) -> list[str]:
+ # Fail closed: without the anchor, rpartition would hand back the whole
+ # statement and every caller would compare the same junk list, passing while
+ # checking nothing.
+ body, anchor, _ = create_sql.split("(", 1)[1].rpartition(")\nENGINE")
+ assert anchor, f"no column list found in {create_sql[:60]!r}"
+ return [_COLUMN_MODIFIER.split(line, maxsplit=1)[0] for line in _column_definition_lines(body)]
def _mv_projected_names(mv_sql: str) -> list[str]:
@@ -87,6 +110,18 @@ def test_flag_evaluations_mv_projection_matches_column_template():
assert _mv_projected_names(FLAG_EVALUATIONS_MV_SQL()) == template_columns + kafka_meta_columns
+def test_flag_evaluations_read_table_declares_every_stored_column():
+ # The materialized columns are declared on sharded_flag_evaluations, which
+ # computes them, and repeated as plain columns on the Distributed read table,
+ # which computes nothing. Those two lists are maintained by hand, so a column
+ # or a type changed in one and not the other stays invisible until a query
+ # asks flag_evaluations for something only the shards have.
+ stored_columns = _flag_evaluations_table_columns(FLAG_EVALUATIONS_TABLE_SQL())
+ assert stored_columns
+
+ assert _flag_evaluations_table_columns(DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL()) == stored_columns
+
+
@pytest.fixture(autouse=True)
def mock_uuid4(mocker):
mock_uuid4 = mocker.patch("uuid.uuid4")
diff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.py
index 7345e0841ed0..7d35dcbc0d45 100644
--- a/posthog/models/flag_evaluations/sql.py
+++ b/posthog/models/flag_evaluations/sql.py
@@ -4,13 +4,18 @@ from posthog.clickhouse.kafka_engine import (
CONSUMER_GROUP_FLAG_EVALUATIONS,
KAFKA_COLUMNS_WITH_PARTITION,
kafka_engine,
+ trim_quotes_expr,
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.
+# table). The column set is the events table's, narrowed to what a flag evaluation
+# actually carries: no elements_chain, no person_mode, no *_created_at companions
+# to the person and group properties. It keeps the full properties JSON as the
+# source of truth, so queries and integrations built on event properties survive
+# the routing switch. The 90-day TTL is what makes rows that wide affordable.
#
# Naming convention follows the sharded main-cluster table family (see heatmaps):
# * `sharded_flag_evaluations` — sharded replicated MergeTree on DATA nodes.
@@ -35,72 +40,116 @@ FLAG_EVALUATIONS_TTL_DAYS = 90
# 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
+# The sort key matches the queries we run: per-flag usage over a date range, and
+# uniques within one flag. 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.
+# whole month. flag_key is a materialized column; ClickHouse computes those before
+# it sorts a part, so one can carry a sort key. 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, a Distributed and a storage variant.
+# One canonical column list, rendered in a Kafka, a Distributed and a storage
+# variant. Column order follows the events table so converging the two schemas
+# later reads as a diff rather than a rewrite.
#
-# 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.
+# The Kafka engine table must NOT carry the inserted_at DEFAULT: JSONEachRow fills
+# omitted fields with the column default, and the MV's fallback detects exactly
+# that zero-value sentinel — a DEFAULT there would mask it. Both Distributed
+# tables MUST carry it: an INSERT through a Distributed table fills omitted
+# columns from the Distributed table's own schema before forwarding to the shard,
+# so without it a direct insert via writable_flag_evaluations would store epoch
+# instead of the sharded table's fallback.
#
-# No column carries a CODEC. The server already compresses everything with ZSTD,
-# and the delta family needs a near-sorted sequence to beat it: ORDER BY only
-# buckets timestamp to a day and then sorts on a distinct_id hash, so on disk all
-# three DateTime64 columns jump around inside a 24h window. DoubleDelta on that
-# widens its encoding to fit the largest jump and strips the byte structure ZSTD
-# would otherwise find. Revisit only with measurements, and note that a codec
-# would then belong on the sharded table alone — a Distributed table stores
-# nothing, so one there is inert metadata that invites the lists to drift.
+# No column carries a CODEC, including the JSON blobs the events table wraps in
+# ZSTD(3); the general rule is in posthog/clickhouse/migrations/AGENTS.md. Nothing
+# here earns an exception: this ORDER BY only buckets timestamp to a day before
+# sorting on a distinct_id hash, so the three DateTime64 columns land on disk in
+# effectively random order, which is where the delta family loses. Revisit only
+# with measurements.
_FLAG_EVALUATIONS_COLUMNS_TEMPLATE = """
- team_id Int64,
uuid UUID,
+ event LowCardinality(String),
+ properties String,
timestamp DateTime64(6, 'UTC'),
- inserted_at DateTime64(6, 'UTC'){ts_default},
+ team_id Int64,
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'){ts_default},
- 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
+ created_at DateTime64(6, 'UTC'),
+ person_id UUID,
+ person_properties String,
+ group0_properties String,
+ group1_properties String,
+ group2_properties String,
+ group3_properties String,
+ group4_properties String,
+ inserted_at DateTime64(6, 'UTC'){ts_default}
""".strip()
FLAG_EVALUATIONS_KAFKA_COLUMNS = _FLAG_EVALUATIONS_COLUMNS_TEMPLATE.format(ts_default="")
_FLAG_EVALUATIONS_COLUMNS = _FLAG_EVALUATIONS_COLUMNS_TEMPLATE.format(ts_default=" DEFAULT timestamp")
+# Typed copies of properties the hot path cannot afford to parse per row. A
+# property earns one only when queries filter or group on it across many rows
+# (flag_key, response) or a skip index needs a real column to sit on (session_id,
+# request_id). Everything else stays in the properties JSON, and the TTL keeps
+# widening this list cheap later.
+#
+# JSONExtractRaw with the quotes trimmed rather than JSONExtractString. The two
+# agree on strings, booleans and numbers, and differ only on JSON null: this form
+# stores the literal 'null' that json_extract_trim_quotes and the plugin-server's
+# jsonExtractRawAndTrimQuotes both map back to SQL NULL, where JSONExtractString
+# stores '' and loses the difference between a null response and an absent
+# property. It is also the expression the events table uses for its own
+# materialized columns, so both tables encode the same value the same way.
+#
+# $group_0..$group_4 carry the events table's names, types and comment form so
+# group filtering resolves the same columns on both.
+_FLAG_EVALUATIONS_MATERIALIZED_COLUMNS = f"""
+ , $group_0 String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$group_0')")} COMMENT 'column_materializer::$group_0'
+ , $group_1 String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$group_1')")} COMMENT 'column_materializer::$group_1'
+ , $group_2 String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$group_2')")} COMMENT 'column_materializer::$group_2'
+ , $group_3 String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$group_3')")} COMMENT 'column_materializer::$group_3'
+ , $group_4 String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$group_4')")} COMMENT 'column_materializer::$group_4'
+ , flag_key String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$feature_flag')")} COMMENT 'column_materializer::properties::$feature_flag'
+ , response LowCardinality(String) MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$feature_flag_response')")} COMMENT 'column_materializer::properties::$feature_flag_response'
+ , session_id String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$session_id')")} COMMENT 'column_materializer::properties::$session_id'
+ , request_id String MATERIALIZED {trim_quotes_expr("JSONExtractRaw(properties, '$feature_flag_request_id')")} COMMENT 'column_materializer::properties::$feature_flag_request_id'
+"""
+
+# A Distributed engine computes nothing, so the read table repeats the same names
+# and types without the expression, which is what lets a query against
+# flag_evaluations select the columns the shards store. The writable table omits
+# them entirely, because rows arrive there without these columns and the shard
+# fills them in.
+_FLAG_EVALUATIONS_PROXY_MATERIALIZED_COLUMNS = """
+ , $group_0 String COMMENT 'column_materializer::$group_0'
+ , $group_1 String COMMENT 'column_materializer::$group_1'
+ , $group_2 String COMMENT 'column_materializer::$group_2'
+ , $group_3 String COMMENT 'column_materializer::$group_3'
+ , $group_4 String COMMENT 'column_materializer::$group_4'
+ , flag_key String COMMENT 'column_materializer::properties::$feature_flag'
+ , response LowCardinality(String) COMMENT 'column_materializer::properties::$feature_flag_response'
+ , session_id String COMMENT 'column_materializer::properties::$session_id'
+ , request_id String COMMENT 'column_materializer::properties::$feature_flag_request_id'
+"""
+
+# The bloom filters cover point lookups the sort key can't serve (a specific user,
+# person, 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.
+_FLAG_EVALUATIONS_INDEXES = """
+ , INDEX distinct_id_idx distinct_id TYPE bloom_filter(0.01) GRANULARITY 1
+ , INDEX person_id_idx person_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
+"""
+
def FLAG_EVALUATIONS_DATA_TABLE_ENGINE() -> MergeTreeEngine:
# Plain (non-replacing) MergeTree: Kafka replay duplicates are accepted for
@@ -110,31 +159,20 @@ def FLAG_EVALUATIONS_DATA_TABLE_ENGINE() -> MergeTreeEngine:
# 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.
+# The inserted_at DEFAULT means a direct insert that omits it (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. It doesn't reproduce 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.
FLAG_EVALUATIONS_TABLE_SQL = lambda: (
f"""
CREATE TABLE IF NOT EXISTS {FLAG_EVALUATIONS_DATA_TABLE}
(
- {_FLAG_EVALUATIONS_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
+ {_FLAG_EVALUATIONS_COLUMNS}
+ {_FLAG_EVALUATIONS_MATERIALIZED_COLUMNS}
+ {_FLAG_EVALUATIONS_INDEXES}
{KAFKA_COLUMNS_WITH_PARTITION}
)
ENGINE = {FLAG_EVALUATIONS_DATA_TABLE_ENGINE()}
@@ -150,11 +188,12 @@ SETTINGS ttl_only_drop_parts = 1
)
-def _distributed_table_sql(table_name: str) -> str:
+def _distributed_table_sql(table_name: str, *, materialized_columns: str = "") -> str:
return f"""
CREATE TABLE IF NOT EXISTS {table_name}
(
{_FLAG_EVALUATIONS_COLUMNS}
+ {materialized_columns}
{KAFKA_COLUMNS_WITH_PARTITION}
)
ENGINE = {Distributed(data_table=FLAG_EVALUATIONS_DATA_TABLE, sharding_key=FLAG_EVALUATIONS_SHARDING_KEY)}
@@ -165,17 +204,16 @@ ENGINE = {Distributed(data_table=FLAG_EVALUATIONS_DATA_TABLE, sharding_key=FLAG_
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)
+DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL = lambda: _distributed_table_sql(
+ FLAG_EVALUATIONS_TABLE, materialized_columns=_FLAG_EVALUATIONS_PROXY_MATERIALIZED_COLUMNS
+)
-# `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)
+ {FLAG_EVALUATIONS_KAFKA_COLUMNS}
)
ENGINE = {
kafka_engine(
@@ -189,11 +227,8 @@ 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.
+# The Kafka JSONEachRow parser fills missing fields with the type's zero value, so
+# a DateTime64 column reads as epoch when a producer omits it.
_EPOCH_DT64 = "toDateTime64('1970-01-01 00:00:00', 6, 'UTC')"
FLAG_EVALUATIONS_MV_SQL = lambda: (
@@ -201,39 +236,24 @@ FLAG_EVALUATIONS_MV_SQL = lambda: (
CREATE MATERIALIZED VIEW IF NOT EXISTS {FLAG_EVALUATIONS_MV_TABLE}
TO {settings.CLICKHOUSE_DATABASE}.{FLAG_EVALUATIONS_WRITABLE_TABLE}
AS SELECT
- team_id,
uuid,
+ event,
+ properties,
timestamp,
+ team_id,
+ distinct_id,
+ created_at,
+ person_id,
+ person_properties,
+ group0_properties,
+ group1_properties,
+ group2_properties,
+ group3_properties,
+ group4_properties,
-- Fall back to the Kafka message timestamp, which is stable across replays
- -- (inserted_at checkpoints the sync_feature_flag_last_called task).
+ -- (inserted_at checkpoints the sync_feature_flag_last_called task, and an
+ -- epoch-stamped row would stay invisible to it forever).
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