:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): stamp flag_evaluations inserted_at with the insert time (#112264)
Phil Haack592aabe38284
diff --git a/posthog/clickhouse/hcl/golden/local-multi/ingestion_medium.hcl b/posthog/clickhouse/hcl/golden/local-multi/ingestion_medium.hclindex d5affb3d7b78..032df63cb403 100644--- a/posthog/clickhouse/hcl/golden/local-multi/ingestion_medium.hcl+++ b/posthog/clickhouse/hcl/golden/local-multi/ingestion_medium.hcl@@ -1609,7 +1609,7 @@ SELECTdistinct_id,created_at,person_id,- if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,+ now64() AS inserted_at,_timestamp,_offset,_partition@@ -1641,7 +1641,7 @@ SQLtype = "UUID"}column "inserted_at" {- type = "Nullable(DateTime64(6, 'UTC'))"+ type = "DateTime64(3)"}column "_timestamp" {type = "Nullable(DateTime)"diff --git a/posthog/clickhouse/hcl/golden/local-single/all.hcl b/posthog/clickhouse/hcl/golden/local-single/all.hclindex bf7c4edb8bce..a36689cdaa11 100644--- a/posthog/clickhouse/hcl/golden/local-single/all.hcl+++ b/posthog/clickhouse/hcl/golden/local-single/all.hcl@@ -20940,7 +20940,7 @@ SELECTdistinct_id,created_at,person_id,- if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,+ now64() AS inserted_at,_timestamp,_offset,_partition@@ -20972,7 +20972,7 @@ SQLtype = "UUID"}column "inserted_at" {- type = "Nullable(DateTime64(6, 'UTC'))"+ type = "DateTime64(3)"}column "_timestamp" {type = "Nullable(DateTime)"diff --git a/posthog/clickhouse/hcl/roles/ingestion_medium/local/tables.hcl b/posthog/clickhouse/hcl/roles/ingestion_medium/local/tables.hclindex 08ae49370994..7ae10ecd7b5d 100644--- a/posthog/clickhouse/hcl/roles/ingestion_medium/local/tables.hcl+++ b/posthog/clickhouse/hcl/roles/ingestion_medium/local/tables.hcl@@ -1248,7 +1248,7 @@ SELECTdistinct_id,created_at,person_id,- if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,+ now64() AS inserted_at,_timestamp,_offset,_partition@@ -1280,7 +1280,7 @@ SQLtype = "UUID"}column "inserted_at" {- type = "Nullable(DateTime64(6, 'UTC'))"+ type = "DateTime64(3)"}column "_timestamp" {type = "Nullable(DateTime)"diff --git a/posthog/clickhouse/hcl/sql/local-multi/ingestion_medium.sql b/posthog/clickhouse/hcl/sql/local-multi/ingestion_medium.sqlindex e5d6cb4d0a3b..ef627759c937 100644--- a/posthog/clickhouse/hcl/sql/local-multi/ingestion_medium.sql+++ b/posthog/clickhouse/hcl/sql/local-multi/ingestion_medium.sql@@ -461,7 +461,7 @@ CREATE MATERIALIZED VIEW posthog.cohort_membership_mv TO posthog.writable_cohortFROM posthog.kafka_cohort_membership;CREATE MATERIALIZED VIEW posthog.distinct_id_usage_mv TO posthog.writable_distinct_id_usage (team_id Int64, distinct_id String, minute DateTime('UTC'), event_count UInt8) AS SELECT team_id, distinct_id, toStartOfMinute(timestamp) AS minute, 1 AS event_countFROM posthog.kafka_distinct_id_usage;-CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evaluations (uuid UUID, event LowCardinality(String), properties String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, created_at DateTime64(6, 'UTC'), person_id UUID, inserted_at Nullable(DateTime64(6, 'UTC')), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECT+CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evaluations (uuid UUID, event LowCardinality(String), properties String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, created_at DateTime64(6, 'UTC'), person_id UUID, inserted_at DateTime64(3), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECTuuid,event,properties,@@ -470,7 +470,7 @@ CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evdistinct_id,created_at,person_id,- if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,+ now64() AS inserted_at,_timestamp,_offset,_partitiondiff --git a/posthog/clickhouse/hcl/sql/local-single/all.sql b/posthog/clickhouse/hcl/sql/local-single/all.sqlindex 9fbb043557bd..11b6521dfba4 100644--- a/posthog/clickhouse/hcl/sql/local-single/all.sql+++ b/posthog/clickhouse/hcl/sql/local-single/all.sql@@ -4859,7 +4859,7 @@ CREATE MATERIALIZED VIEW posthog.events_recent_json_mv TO posthog.writable_event_timestamp,_offsetFROM posthog.sharded_events;-CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evaluations (uuid UUID, event LowCardinality(String), properties String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, created_at DateTime64(6, 'UTC'), person_id UUID, inserted_at Nullable(DateTime64(6, 'UTC')), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECT+CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evaluations (uuid UUID, event LowCardinality(String), properties String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, created_at DateTime64(6, 'UTC'), person_id UUID, inserted_at DateTime64(3), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECTuuid,event,properties,@@ -4868,7 +4868,7 @@ CREATE MATERIALIZED VIEW posthog.flag_evaluations_mv TO posthog.writable_flag_evdistinct_id,created_at,person_id,- if(inserted_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), _timestamp, inserted_at) AS inserted_at,+ now64() AS inserted_at,_timestamp,_offset,_partitiondiff --git a/posthog/clickhouse/migrations/0350_flag_evaluations_mv_insert_time.py b/posthog/clickhouse/migrations/0350_flag_evaluations_mv_insert_time.pynew file mode 100644index 000000000000..73e92cc7dd25--- /dev/null+++ b/posthog/clickhouse/migrations/0350_flag_evaluations_mv_insert_time.py@@ -0,0 +1,19 @@+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 FLAG_EVALUATIONS_MV_SELECT_SQL, FLAG_EVALUATIONS_MV_TABLE++# After this migration, flag_evaluations_mv stamps inserted_at with the time the+# view processes each row. posthog/models/flag_evaluations/sql.py carries the+# rationale. Rows written before this migration keep their old value.+#+# The migration uses MODIFY QUERY rather than drop-and-recreate, because only the+# SELECT changes. The MV stays attached to the Kafka table, so consumption does+# not stop.+operations = [+ run_sql_with_exceptions(+ f"ALTER TABLE {FLAG_EVALUATIONS_MV_TABLE} MODIFY QUERY\n{FLAG_EVALUATIONS_MV_SELECT_SQL()}",+ node_roles=[NodeRole.INGESTION_MEDIUM],+ sharded=False,+ is_alter_on_replicated_table=False,+ ),+]diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txtindex 6f775b750940..541eb85fd1a2 100644--- a/posthog/clickhouse/migrations/max_migration.txt+++ b/posthog/clickhouse/migrations/max_migration.txt@@ -1 +1 @@-0349_warehouse_object_reads_daily+0350_flag_evaluations_mv_insert_timediff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex dea8e733e1fb..b8c0b5daea40 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -2123,10 +2123,13 @@distinct_id,created_at,person_id,- -- Fall back to the Kafka message timestamp, which is stable across replays- -- (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,+ -- inserted_at is the time this view processes the row, as in the native-JSON+ -- events MV. The sync_feature_flag_last_called checkpoint and the deletion+ -- sweeps need a row that ClickHouse consumes after their cutoff to fall after+ -- it. The Kafka message time is earlier by the consumer lag. The Distributed+ -- forward and the replication happen after this stamp, so those readers still+ -- need a buffer.+ now64() AS inserted_at,_timestamp,_offset,_partitiondiff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.pyindex 1246f4d3f942..76f9f31b3ded 100644--- a/posthog/clickhouse/test/test_schema.py+++ b/posthog/clickhouse/test/test_schema.py@@ -31,9 +31,11 @@ from posthog.models.event.sql import (from posthog.models.flag_evaluations.sql import (DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,FLAG_EVALUATIONS_KAFKA_COLUMNS,+ FLAG_EVALUATIONS_MV_SELECT_SQL,FLAG_EVALUATIONS_MV_SQL,FLAG_EVALUATIONS_TABLE,FLAG_EVALUATIONS_TABLE_SQL,+ KAFKA_FLAG_EVALUATIONS_TABLE,)from posthog.models.ingestion_warnings.sql_v2 import INGESTION_WARNINGS_V2_DATA_TABLE_SQLfrom posthog.settings.data_stores import SUFFIX@@ -197,6 +199,35 @@ def test_flag_evaluations_mv_projection_matches_column_template():assert _mv_projected_names(FLAG_EVALUATIONS_MV_SQL()) == template_columns + kafka_meta_columns[email protected]("clickhouse_database")+def test_flag_evaluations_mv_ignores_producer_inserted_at() -> None:+ select = FLAG_EVALUATIONS_MV_SELECT_SQL().replace(+ f"FROM {django_settings.CLICKHOUSE_DATABASE}.{KAFKA_FLAG_EVALUATIONS_TABLE}", "FROM mv_input"+ )+ rows = sync_execute(+ """+ WITH mv_input AS (+ SELECT+ generateUUIDv4() AS uuid,+ '$feature_flag_called' AS event,+ '{}' AS properties,+ toDateTime64('2020-01-01 00:00:00', 6, 'UTC') AS timestamp,+ 1 AS team_id,+ 'user' AS distinct_id,+ timestamp AS created_at,+ generateUUIDv4() AS person_id,+ timestamp AS inserted_at,+ toDateTime('2020-01-01 00:00:00', 'UTC') AS _timestamp,+ 0 AS _offset,+ 0 AS _partition+ )+ SELECT inserted_at > timestamp FROM ("""+ + select+ + ")"+ )+ assert rows == [(1,)]++def test_flag_evaluations_read_table_declares_every_stored_column():# The typed property columns carry their DEFAULT expression on# sharded_flag_evaluations, which computes them, and are repeated as plaindiff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.pyindex b3b41ecfedf7..c390cf44f82e 100644--- a/posthog/models/flag_evaluations/sql.py+++ b/posthog/models/flag_evaluations/sql.py@@ -62,13 +62,15 @@ FLAG_EVALUATIONS_ORDER_BY = "(team_id, flag_key, toDate(timestamp), cityHash64(d# 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 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.+# The MV ignores the Kafka table's inserted_at and stamps the time it processes+# the row, so a producer cannot set the value that deletion sweeps compare+# against. The Kafka table still declares inserted_at with no DEFAULT, because+# changing a Kafka engine table's columns means recreating the table and its MV.+# Both Distributed tables MUST carry the DEFAULT: 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+# DEFAULT.## 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@@ -173,13 +175,13 @@ def FLAG_EVALUATIONS_DATA_TABLE_ENGINE() -> MergeTreeEngine:# The actual data lives on the sharded main cluster.#-# The inserted_at DEFAULT means a direct insert that omits it (tests, the planned+# The inserted_at DEFAULT means a direct insert that omits it (tests, the# 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.+# wall-clock insert time that the MV stamps on rows from Kafka. A bulk historical+# backfill therefore does not stamp every row as freshly inserted, which would+# break anything windowing or checkpointing on inserted_at.+# posthog/dags/flag_evaluations_backfill.py also relies on it to tell copied rows+# from Kafka rows.FLAG_EVALUATIONS_TABLE_SQL = lambda: (f"""CREATE TABLE IF NOT EXISTS {FLAG_EVALUATIONS_DATA_TABLE}@@ -271,15 +273,10 @@ SETTINGS""")-# 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: (- f"""-CREATE MATERIALIZED VIEW IF NOT EXISTS {FLAG_EVALUATIONS_MV_TABLE}-TO {settings.CLICKHOUSE_DATABASE}.{FLAG_EVALUATIONS_WRITABLE_TABLE}-AS SELECT+# The CREATE below and migrations that ALTER ... MODIFY QUERY both use this+# SELECT, so a fresh install and a migrated node run the same query.+FLAG_EVALUATIONS_MV_SELECT_SQL = lambda: (+ f"""SELECTuuid,event,properties,@@ -288,13 +285,23 @@ AS SELECTdistinct_id,created_at,person_id,- -- Fall back to the Kafka message timestamp, which is stable across replays- -- (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,+ -- inserted_at is the time this view processes the row, as in the native-JSON+ -- events MV. The sync_feature_flag_last_called checkpoint and the deletion+ -- sweeps need a row that ClickHouse consumes after their cutoff to fall after+ -- it. The Kafka message time is earlier by the consumer lag. The Distributed+ -- forward and the replication happen after this stamp, so those readers still+ -- need a buffer.+ now64() AS inserted_at,_timestamp,_offset,_partitionFROM {settings.CLICKHOUSE_DATABASE}.{KAFKA_FLAG_EVALUATIONS_TABLE}""")++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 {FLAG_EVALUATIONS_MV_SELECT_SQL()}"""+)