:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): collapse duplicate flag calls in flag_evaluations (#116519)
Phil Haackf35127d5d14f
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex ccba08021729..d891e0af22d9 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -170,12 +170,16 @@ A request naming `$feature_flag` therefore completes: the cleaned row goes backThe same names on `sharded_events` (`$session_id`, `$window_id`, `$group_0..4`) are true `MATERIALIZED` columns with that comment.The copy reads the `SELECT *` shape of the table, which leaves `MATERIALIZED` columns out, and the reingest recomputes them from the cleaned `properties`.-#### Replay duplicates--`sharded_flag_evaluations` is a plain `MergeTree` that keeps Kafka replay duplicates, so one uuid can have several identical rows.-The staged files keep every physical row, so the reingest puts every duplicate back, cleaned.-The copy, the delete's count, the reingest and the shard verify count each uuid once, so duplicates do not block the request.-The same counting covers unmerged `ReplacingMergeTree` duplicates on events.+#### Duplicate rows++`sharded_flag_evaluations` is a `ReplacingMergeTree` on `_timestamp`, like `sharded_events`, so the copies of one flag call collapse when their parts merge.+Until a merge, one uuid can have several rows.+The staged files keep every physical row.+The copy, the delete's count, the reingest and the shard verify count each uuid once, so unmerged duplicates do not block the request.+The reingest bumps `_timestamp` past the original's on both tables, so a merge that meets a cleaned row and a surviving original keeps the cleaned row.+A request that removes `$feature_flag` empties `flag_key`, which is in the sort key.+That cleaned row therefore never collapses with an original.+A table created before the switch to `ReplacingMergeTree` keeps every duplicate, and the job leaves its `_timestamp` as it is, because the job reads the engine from `system.tables` on each run.#### Rows past the TTLdiff --git a/posthog/clickhouse/hcl/golden/dev/data.hcl b/posthog/clickhouse/hcl/golden/dev/data.hclindex 40498e10d4c8..c975a49d0104 100644--- a/posthog/clickhouse/hcl/golden/dev/data.hcl+++ b/posthog/clickhouse/hcl/golden/dev/data.hcl@@ -5497,7 +5497,7 @@ database "posthog" {}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -5621,9 +5621,10 @@ database "posthog" {type = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}diff --git a/posthog/clickhouse/hcl/golden/local-multi/data.hcl b/posthog/clickhouse/hcl/golden/local-multi/data.hclindex 9b1258aa1b8d..c9ff9b9af778 100644--- a/posthog/clickhouse/hcl/golden/local-multi/data.hcl+++ b/posthog/clickhouse/hcl/golden/local-multi/data.hcl@@ -6007,7 +6007,7 @@ database "posthog" {}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -6131,9 +6131,10 @@ database "posthog" {type = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}diff --git a/posthog/clickhouse/hcl/golden/local-single/all.hcl b/posthog/clickhouse/hcl/golden/local-single/all.hclindex 143fa76e50bd..d967529e8b9b 100644--- a/posthog/clickhouse/hcl/golden/local-single/all.hcl+++ b/posthog/clickhouse/hcl/golden/local-single/all.hcl@@ -11685,7 +11685,7 @@ SQL}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -11809,9 +11809,10 @@ SQLtype = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}diff --git a/posthog/clickhouse/hcl/golden/prod-eu/data.hcl b/posthog/clickhouse/hcl/golden/prod-eu/data.hclindex 7e0224ab14ef..ce573843e311 100644--- a/posthog/clickhouse/hcl/golden/prod-eu/data.hcl+++ b/posthog/clickhouse/hcl/golden/prod-eu/data.hcl@@ -5672,7 +5672,7 @@ database "posthog" {}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -5796,9 +5796,10 @@ database "posthog" {type = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}diff --git a/posthog/clickhouse/hcl/golden/prod-us/data.hcl b/posthog/clickhouse/hcl/golden/prod-us/data.hclindex dcde195906ea..69ebe737908a 100644--- a/posthog/clickhouse/hcl/golden/prod-us/data.hcl+++ b/posthog/clickhouse/hcl/golden/prod-us/data.hcl@@ -5485,7 +5485,7 @@ database "posthog" {}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -5609,9 +5609,10 @@ database "posthog" {type = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}diff --git a/posthog/clickhouse/hcl/roles/data/shared/flag_evaluations.hcl b/posthog/clickhouse/hcl/roles/data/shared/flag_evaluations.hclindex a6dec55dc1a3..7d2d07e93993 100644--- a/posthog/clickhouse/hcl/roles/data/shared/flag_evaluations.hcl+++ b/posthog/clickhouse/hcl/roles/data/shared/flag_evaluations.hcl@@ -105,7 +105,7 @@ database "posthog" {}table "sharded_flag_evaluations" {- order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)"]+ order_by = ["team_id", "flag_key", "toDate(timestamp)", "cityHash64(distinct_id)", "cityHash64(uuid)"]partition_by = "toYYYYMM(timestamp)"ttl = "toDate(timestamp) + toIntervalDay(90)"settings = {@@ -165,9 +165,10 @@ database "posthog" {type = "minmax"granularity = 1}- engine "replicated_merge_tree" {- zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"- replica_name = "{replica}"+ engine "replicated_replacing_merge_tree" {+ zoo_path = "/clickhouse/tables/{shard}/posthog.flag_evaluations"+ replica_name = "{replica}"+ version_column = "_timestamp"}}}diff --git a/posthog/clickhouse/hcl/sql/dev/data.sql b/posthog/clickhouse/hcl/sql/dev/data.sqlindex 913c091fd102..393e7189e39a 100644--- a/posthog/clickhouse/hcl/sql/dev/data.sql+++ b/posthog/clickhouse/hcl/sql/dev/data.sql@@ -1133,7 +1133,7 @@ CREATE TABLE posthog.sharded_flag_evaluations (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;+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}', _timestamp) ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)) 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,diff --git a/posthog/clickhouse/hcl/sql/local-multi/data.sql b/posthog/clickhouse/hcl/sql/local-multi/data.sqlindex 253431a32775..d81b5174ada0 100644--- a/posthog/clickhouse/hcl/sql/local-multi/data.sql+++ b/posthog/clickhouse/hcl/sql/local-multi/data.sql@@ -1211,7 +1211,7 @@ CREATE TABLE posthog.sharded_flag_evaluations (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;+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}', _timestamp) ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)) 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,diff --git a/posthog/clickhouse/hcl/sql/local-single/all.sql b/posthog/clickhouse/hcl/sql/local-single/all.sqlindex 438527e97085..a9c7da836dee 100644--- a/posthog/clickhouse/hcl/sql/local-single/all.sql+++ b/posthog/clickhouse/hcl/sql/local-single/all.sql@@ -2246,7 +2246,7 @@ CREATE TABLE posthog.sharded_flag_evaluations (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;+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}', _timestamp) ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)) 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,diff --git a/posthog/clickhouse/hcl/sql/prod-eu/data.sql b/posthog/clickhouse/hcl/sql/prod-eu/data.sqlindex 36fbb0004ac8..1edabdd39a3b 100644--- a/posthog/clickhouse/hcl/sql/prod-eu/data.sql+++ b/posthog/clickhouse/hcl/sql/prod-eu/data.sql@@ -1410,7 +1410,7 @@ CREATE TABLE posthog.sharded_flag_evaluations (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;+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}', _timestamp) ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)) 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,diff --git a/posthog/clickhouse/hcl/sql/prod-us/data.sql b/posthog/clickhouse/hcl/sql/prod-us/data.sqlindex ab47778232ab..6466c1afc608 100644--- a/posthog/clickhouse/hcl/sql/prod-us/data.sql+++ b/posthog/clickhouse/hcl/sql/prod-us/data.sql@@ -1252,7 +1252,7 @@ CREATE TABLE posthog.sharded_flag_evaluations (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;+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/{shard}/posthog.flag_evaluations', '{replica}', _timestamp) ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid)) 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,diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambrindex c6a44da704d2..ce5a57ef1dcf 100644--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr@@ -7907,13 +7907,13 @@, _partition UInt64)- ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}')+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}', _timestamp)-- 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))+ ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid))SETTINGS ttl_only_drop_parts = 1@@ -13732,13 +13732,13 @@, _partition UInt64)- ENGINE = ReplicatedMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}')+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_{shard}/posthog.flag_evaluations', '{replica}', _timestamp)-- 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))+ ORDER BY (team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid))SETTINGS ttl_only_drop_parts = 1diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex 7908d1b3a3a6..74c760f93d59 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -1193,8 +1193,9 @@ def _cleaned_select_list(# Bump the ReplacingMergeTree version (ver=_timestamp) past the original's, so a merge that# meets a cleaned row and an original with the same sorting key keeps the cleaned row. +1# second because _timestamp is second-precision while the marker is microsecond-precision.- # A plain MergeTree such as flag_evaluations keeps the original value, because there _timestamp- # is the Kafka message time that flag_evaluations_backfill reads as the consumer position.+ # flag_evaluations_backfill reads max(_timestamp) per Kafka partition as the consumer position. On+ # flag_evaluations a bumped row can therefore make a stalled partition look current (see+ # _KAFKA_POSITION_QUERY there).if "ReplacingMergeTree" in engine:replacements["_timestamp"] = "toDateTime(toDateTime64(%(inserted_at_marker)s, 6, 'UTC')) + 1"# On the JSON table the column round-trips through a string: serialize it, drop the keys, and@@ -1559,7 +1560,7 @@ def reingest_property_removal_shard(# A failed earlier attempt may have inserted a month on another replica of this shard. Without# that part here, the leftover count below misses those rows and the insert adds them a second- # time, which a plain MergeTree such as flag_evaluations never merges away.+ # time._sync_replica(client, target, log)for month, expected in sorted(copied["months"].items()):if f"{_REINGESTED}_{month}" in steps:diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.pyindex c6af04dec312..3d668a8cfca9 100644--- a/posthog/dags/flag_evaluations_backfill.py+++ b/posthog/dags/flag_evaluations_backfill.py@@ -87,6 +87,11 @@ _COPIED_ROW_FILTER = "_partition = 0 AND _offset = 0 AND inserted_at = timestamp# lookback drops out of this query.# Lag comes from _timestamp, the Kafka message time. A consumer that works through a backlog writes# rows now, so the time a row is written does not show how far the consumer is behind.+# Rows that a property removal reingested also pass the inserted_at filter, but their _timestamp is one+# second after the request's marker, not the Kafka message time (see _cleaned_select_list in+# data_deletion_requests.py). A partition that stalls after a removal can therefore look current until the+# marker is max_consumer_lag_seconds old. Within that window the job can copy a call whose fork row is+# still in Kafka. The two rows collapse to one when their parts merge.# The lookback filters on inserted_at because only inserted_at has a skip index._KAFKA_LOOKBACK_DAYS = 7_KAFKA_POSITION_QUERY = f"""diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex d8e88bf209bb..b9740d7fc49c 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -140,14 +140,12 @@ def _truncate_writable_events(client: Client) -> None:def _insert_flag_evaluations_with_properties(rows: list[tuple], client: Client, **row_values: object) -> None:- # Rows of (team_id, distinct_id, properties_json, uuid, timestamp, inserted_at[, _timestamp]).+ # Rows of (team_id, distinct_id, properties_json, uuid, timestamp, inserted_at).# Each keyword in row_values sets that column to the same value on every row. The event name is# stamped here because a property-removal request narrows on it. inserted_at is set explicitly# rather than left to its `DEFAULT timestamp` so a test can place a row before or after the removal# marker, which is what the marker-bounded gate keys on.columns = "team_id, distinct_id, properties, uuid, timestamp, inserted_at"- if rows and len(rows[0]) == 7:- columns += ", _timestamp"stamped = {"event": FLAG_EVALUATIONS_SOURCE_EVENT, **row_values}client.execute(f"INSERT INTO writable_flag_evaluations ({columns}, {', '.join(stamped)}) VALUES",@@ -1042,7 +1040,18 @@ def test_auto_approve_schedule_launches_a_run_on_tick():PROP_TEAM_ID = 88888-def test_property_removal_cleaning_uses_unversioned_pool_udf() -> None:+ "engine, timestamp_expression",+ [+ pytest.param(+ "ReplicatedReplacingMergeTree",+ "CAST(toDateTime(toDateTime64(%(inserted_at_marker)s, 6, 'UTC')) + 1 AS DateTime) AS `_timestamp`",+ id="replacing_merge_tree_bumps_version",+ ),+ pytest.param("ReplicatedMergeTree", "`_timestamp`", id="plain_merge_tree_keeps_kafka_time"),+ ],+)+def test_property_removal_cleaned_select_expressions(engine: str, timestamp_expression: str) -> None:client = Mock(spec=Client)client.execute.side_effect = [[@@ -1051,7 +1060,7 @@ def test_property_removal_cleaning_uses_unversioned_pool_udf() -> None:("inserted_at", "Nullable(DateTime64(6, 'UTC'))"),("_timestamp", "DateTime"),],- [("ReplicatedReplacingMergeTree",)],+ [(engine,)],]request = DeletionRequestContext(request_id=str(uuid4()),@@ -1080,6 +1089,7 @@ def test_property_removal_cleaning_uses_unversioned_pool_udf() -> None:"JSONDropKeysPool(if(empty(person_properties), '{}', person_properties), %(person_keys)s)) ""AS String) AS `person_properties`" in cleaned.expressions)+ assert timestamp_expression in cleaned.expressionsdef _insert_events_with_properties(events: list[tuple], client: Client) -> None:@@ -2735,13 +2745,9 @@ def test_full_job_property_removal_rewrites_flag_evaluations() -> None:now = timezone.now()ingested = now - timedelta(hours=1)- kafka_time = ingested.replace(microsecond=0)stored = {"$feature_flag": "beta", "$session_id": "s1", "keep": "yes"}- replayed_uuid, single_uuid = str(uuid4()), str(uuid4())- rows = [- (PROP_TEAM_ID, "someone", json.dumps(stored), uuid, ingested, ingested, kafka_time)- for uuid in (replayed_uuid, replayed_uuid, single_uuid)- ]+ uuids = sorted(str(uuid4()) for _ in range(2))+ rows = [(PROP_TEAM_ID, "someone", json.dumps(stored), uuid, ingested, ingested) for uuid in uuids]cluster.any_host(_truncate_flag_evaluations).result()# Non-default values, so a copy that reset the person columns would fail the comparison below.cluster.any_host(@@ -2770,12 +2776,16 @@ def test_full_job_property_removal_rewrites_flag_evaluations()assert result.successassert count_remaining_for_request(request) == 0+ request.refresh_from_db()+ assert request.status == RequestStatus.COMPLETED+ marker = request.property_removal_marker+ assert marker is not Nonecleaned = {key: value for key, value in stored.items() if key not in properties}cleaned_person = (None if stored_person is None else {k: v for k, v in stored_person.items() if k not in person_properties})- # _timestamp keeps the Kafka message time, which flag_evaluations_backfill reads as the consumer position.+ # Cleaned rows carry a _timestamp version past the original's, so a merge with a surviving original keeps them.expected = [(uuid,@@ -2785,13 +2795,11 @@ def test_full_job_property_removal_rewrites_flag_evaluations("propertyless",cleaned.get("$feature_flag", ""),cleaned.get("$session_id", ""),- int(kafka_time.timestamp()),+ int(marker.timestamp()) + 1,)- for uuid in sorted((replayed_uuid, replayed_uuid, single_uuid))+ for uuid in uuids]assert cluster.any_host(partial(_flag_evaluation_rows, PROP_TEAM_ID)).result() == expected- request.refresh_from_db()- assert request.status == RequestStatus.COMPLETEDcluster.any_host(_truncate_flag_evaluations).result()diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.pyindex 121036d16a51..3ffb708e61a6 100644--- a/posthog/dags/tests/test_flag_evaluations_backfill.py+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py@@ -158,6 +158,11 @@ KAFKA_PATH_ROW = SourceEvent(label="kafka_path_row", team_id=TEAM_ONE, age=timedKAFKA_ROW_IN_ITS_EVENT_SECOND = SourceEvent(label="kafka_row_in_its_event_second", team_id=TEAM_ONE, age=timedelta(0), properties={})+# Its own label gives it its own uuid and distinct_id. Two copies of one event would share the sort key.+# A merge would then collapse them.+SECOND_KAFKA_ROW_IN_ITS_EVENT_SECOND = replace(+ KAFKA_ROW_IN_ITS_EVENT_SECOND, label="second_kafka_row_in_its_event_second"+)SAME_UUID_OTHER_TEAM = replace(INSIDE_RECENT, team_id=TEAM_TWO)@@ -254,7 +259,10 @@ def seed_kafka_path_row(def stored_rows(cluster: ClickhouseCluster) -> Counter[StoredRow]:- labels = {event.uuid: event.label for event in [*SOURCE_EVENTS, KAFKA_ROW_IN_ITS_EVENT_SECOND]}+ labels = {+ event.uuid: event.label+ for event in [*SOURCE_EVENTS, KAFKA_ROW_IN_ITS_EVENT_SECOND, SECOND_KAFKA_ROW_IN_ITS_EVENT_SECOND]+ }def select(client: Client) -> list[tuple[UUID, str, str, str, UUID, str, datetime, str, int]]:# The driver returns a naive datetime unless the column type names a time zone.@@ -480,11 +488,12 @@ def test_backfill_names_the_day_when_a_blocking_run_starts_during_its_copy() -> None:now = datetime.now(UTC)on_first_copied_day = replace(INSIDE_RECENT, age=age_at_noon(now, days_ago=2))- kafka_row_on_first_copied_day = replace(KAFKA_ROW_IN_ITS_EVENT_SECOND, age=on_first_copied_day.age)seed_source_events(cluster, now, [on_first_copied_day])seed_kafka_path_row(cluster, now)- for partition, offset in [(0, 1), (1, 0)]:- seed_kafka_path_row(cluster, now, kafka_row_on_first_copied_day, partition, offset, delivery_delay=timedelta(0))+ kafka_rows = [(KAFKA_ROW_IN_ITS_EVENT_SECOND, 0, 1), (SECOND_KAFKA_ROW_IN_ITS_EVENT_SECOND, 1, 0)]+ for event, partition, offset in kafka_rows:+ on_day = replace(event, age=on_first_copied_day.age)+ seed_kafka_path_row(cluster, now, on_day, partition, offset, delivery_delay=timedelta(0))instance = dagster.DagsterInstance.ephemeral()copy_day = ShardBackfill.copy_day@@ -503,12 +512,13 @@ def test_backfill_names_the_day_when_a_blocking_run_starts_during_its_copy(assert failure.step_failure_data.error is not Nonemessage = failure.step_failure_data.error.messageassert "started while" in message- assert stored_rows(cluster) == Counter({copied(on_first_copied_day): 1, forked(KAFKA_ROW_IN_ITS_EVENT_SECOND): 2})+ forked_rows = [forked(event) for event, _, _ in kafka_rows]+ assert stored_rows(cluster) == Counter([copied(on_first_copied_day), *forked_rows])[repair_delete] = re.findall(r"`(DELETE FROM [^`]+)`", message)cluster.map_one_host_per_shard(lambda client: client.execute(repair_delete)).result()- assert stored_rows(cluster) == Counter({forked(KAFKA_ROW_IN_ITS_EVENT_SECOND): 2})+ assert stored_rows(cluster) == Counter(forked_rows)@pytest.mark.parametrize(diff --git a/posthog/models/flag_evaluations/PARITY_CHECK.md b/posthog/models/flag_evaluations/PARITY_CHECK.mdindex d222bf927fc4..2b7619b59056 100644--- a/posthog/models/flag_evaluations/PARITY_CHECK.md+++ b/posthog/models/flag_evaluations/PARITY_CHECK.md@@ -92,7 +92,7 @@ A team with no rows on the day produces no result row at all. Compare the return### Group by `(team_id, uuid)` before counting-`flag_evaluations` is a plain MergeTree and keeps the duplicate rows a Kafka replay produces. The ReplacingMergeTree behind events collapses them. Counting rows per side instead of distinct uuids reports that difference in table engine as a parity failure.+Both tables are ReplacingMergeTrees, but each one collapses the duplicate rows of a uuid only when its own parts merge. A `flag_evaluations` table created before the switch to ReplacingMergeTree is a plain MergeTree and never collapses them. Counting rows per side instead of distinct uuids reports those unmerged duplicates as a parity failure.Grouping first also means a re-sent uuid that reached both tables lands in `in_both`, not in the excess column.diff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.pyindex b913ce3f1443..1d80e13e8387 100644--- a/posthog/models/flag_evaluations/sql.py+++ b/posthog/models/flag_evaluations/sql.py@@ -7,7 +7,7 @@ from posthog.clickhouse.kafka_engine import (trim_quotes_expr,ttl_period,)-from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplicationScheme+from posthog.clickhouse.table_engines import Distributed, MergeTreeEngine, ReplacingMergeTree, ReplicationSchemefrom posthog.kafka_client.topics import KAFKA_CLICKHOUSE_FLAG_EVALUATIONS# Flag evaluation telemetry ($feature_flag_called events routed out of the events@@ -24,7 +24,7 @@ from posthog.kafka_client.topics import KAFKA_CLICKHOUSE_FLAG_EVALUATIONS# 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.+# * `sharded_flag_evaluations` — sharded ReplicatedReplacingMergeTree 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@@ -57,11 +57,15 @@ FLAG_EVALUATIONS_SHARDING_KEY = "sipHash64(distinct_id)"# is monthly — without it, a one-day query for one flag would read that flag's# whole month. flag_key is a DEFAULT column; ClickHouse fills column defaults at# insert, before it sorts a part, so one can carry a sort key, though a key-# column can never be ALTER UPDATEd, whatever its kind. The trailing hash intentionally+# column can never be ALTER UPDATEd, whatever its kind. cityHash64(distinct_id) 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))"+# so the two must not silently move together. cityHash64(uuid) comes last, as on the+# events table, so that the sort key identifies one flag call. The ReplacingMergeTree+# collapses only rows whose whole sort key matches. Copies of a call that straddle UTC+# midnight get different toDate(timestamp) values. They never collapse, in either+# table.+FLAG_EVALUATIONS_ORDER_BY = "(team_id, flag_key, toDate(timestamp), cityHash64(distinct_id), cityHash64(uuid))"# 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@@ -185,9 +189,11 @@ _FLAG_EVALUATIONS_INDEXES = """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)+ # Ingestion can receive one flag call more than once. The copies collapse to one+ # row when their parts merge. Queries see every copy until then. The version+ # is _timestamp, as on the events table, so both tables keep the same copy of a+ # call. ZK path uses the base table name.+ return ReplacingMergeTree(FLAG_EVALUATIONS_TABLE, ver="_timestamp", replication_scheme=ReplicationScheme.SHARDED)# The actual data lives on the sharded main cluster.