: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): copy person columns in the flag_evaluations backfill (#116540)
Phil Haack01366c105cc6
diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.pyindex 87e730eecb1b..4446aaf88ac2 100644--- a/posthog/clickhouse/test/test_schema.py+++ b/posthog/clickhouse/test/test_schema.py@@ -23,12 +23,14 @@ from posthog.clickhouse.schema import (build_query,get_table_name,)+from posthog.dags.flag_evaluations_backfill import _COPIED_COLUMNSfrom posthog.models.event.sql import (EVENTS_JSON_TABLE_MV_SQL,KAFKA_EVENTS_NATIVE_JSON_TABLE,KAFKA_EVENTS_NATIVE_JSON_TABLE_SQL,)from posthog.models.flag_evaluations.sql import (+ _FLAG_EVALUATIONS_TYPED_COLUMNS,DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,FLAG_EVALUATIONS_KAFKA_COLUMNS,FLAG_EVALUATIONS_MV_SELECT_SQL,@@ -244,6 +246,21 @@ def test_flag_evaluations_read_table_declares_every_stored_column():assert _flag_evaluations_table_columns(DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL()) == stored_columns+# The comment above _COPIED_COLUMNS gives the reason the backfill leaves out each of these columns.+_FLAG_EVALUATIONS_COLUMNS_THE_BACKFILL_LEAVES_OUT = {"inserted_at", "_offset", "_partition"}+++def test_flag_evaluations_backfill_copies_every_stored_column():+ # A column that the backfill does not copy gets its DEFAULT on every backfilled row. No error+ # reports this. The typed columns compute their DEFAULT from properties, so the copy leaves them+ # out by design. Any other new column fails here until the copy or the set above names it.+ stored = {column.split()[0] for column in _flag_evaluations_table_columns(FLAG_EVALUATIONS_TABLE_SQL())}+ typed = set(_declared_column_names(_FLAG_EVALUATIONS_TYPED_COLUMNS))++ assert typed+ assert stored == set(_COPIED_COLUMNS) | typed | _FLAG_EVALUATIONS_COLUMNS_THE_BACKFILL_LEAVES_OUT++def _hogql_column_names(table: Table) -> set[str]:names: set[str] = set()for field in table.fields.values():diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.pyindex dbcfc4971f49..c6af04dec312 100644--- a/posthog/dags/flag_evaluations_backfill.py+++ b/posthog/dags/flag_evaluations_backfill.py@@ -23,6 +23,7 @@ from posthog.dataclasses import frozenfrom posthog.models.event.sql import EVENTS_DATA_TABLEfrom posthog.models.flag_evaluations.sql import (FLAG_EVALUATIONS_DATA_TABLE,+ FLAG_EVALUATIONS_PERSON_PROPERTIES_EXPR,FLAG_EVALUATIONS_SOURCE_EVENT,FLAG_EVALUATIONS_TTL_DAYS,)@@ -47,12 +48,31 @@ _FINISHED_RUN_STATUSES = (dagster.DagsterRunStatus.CANCELED,)-# The nine DEFAULT columns are left out so the shard computes them from properties, the same way+# The nine columns whose DEFAULT reads properties are left out so the shard computes them the same way# it does for rows from Kafka. inserted_at is left out so its DEFAULT stamps the event timestamp:# that keeps every copied row inside the deletion sweep's `inserted_at <= request.created_at` bound,# and it keeps copied rows out of the consumer-lag query below. _partition and _offset are left out# so that both are 0 on a copied row. _COPIED_ROW_FILTER relies on that.-_COPIED_COLUMNS = "uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, _timestamp"+_COPIED_COLUMNS = (+ "uuid",+ "event",+ "properties",+ "timestamp",+ "team_id",+ "distinct_id",+ "created_at",+ "person_id",+ "person_properties",+ "person_created_at",+ "person_mode",+ "_timestamp",+)++_COPIED_COLUMN_LIST = ", ".join(_COPIED_COLUMNS)++_COPIED_VALUES = ", ".join(+ FLAG_EVALUATIONS_PERSON_PROPERTIES_EXPR if column == "person_properties" else column for column in _COPIED_COLUMNS+)# A row from Kafka also has inserted_at = timestamp when its timestamp has no sub-second part and# falls in the second that Kafka received it. Kafka gives offset 0 only to the first message in a@@ -256,7 +276,7 @@ def build_copy_query(*, dry_run: bool, filter_team_ids: bool, chunked: bool) -># still have its fork row in Kafka. Copying it would store the call twice, so the job skips it. Kafka then# delivers its fork row, or a later run copies it.select = f"""-SELECT {"count()" if dry_run else _COPIED_COLUMNS}+SELECT {"count()" if dry_run else _COPIED_VALUES}FROM {EVENTS_DATA_TABLE()}PREWHERE event = %(event)sAND timestamp >= %(day_start)s AND timestamp < %(day_end)s{team_filter}@@ -270,7 +290,7 @@ WHERE _timestamp < %(created_before)s"""if dry_run:return select- return f"INSERT INTO {FLAG_EVALUATIONS_DATA_TABLE} ({_COPIED_COLUMNS}){select}"+ return f"INSERT INTO {FLAG_EVALUATIONS_DATA_TABLE} ({_COPIED_COLUMN_LIST}){select}"@dagster.op(tags=OWNER_TAG)@@ -611,6 +631,9 @@ def flag_evaluations_backfill_job() -> None:"""Copy $feature_flag_called history from events into flag_evaluations, one op per shard.Safe to re-run over the same window: the anti-join inserts only rows that are missing.+ A re-run does not rewrite a stored row. To copy a day again, first delete the rows that an earlier+ run copied, which match _COPIED_ROW_FILTER. Delete a row that the Kafka path wrote only when events+ also holds the call. Events does not hold the calls of an organization on FLAG_EVALUATIONS_ONLY."""plan = plan_flag_evaluations_backfill()shards = get_backfill_shards(plan=plan)diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.pyindex ae06269e0010..121036d16a51 100644--- a/posthog/dags/tests/test_flag_evaluations_backfill.py+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py@@ -38,6 +38,10 @@ from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE, FLATEAM_ONE, TEAM_TWO, TEAM_THREE = 1, 2, 3+# Neither value is the flag_evaluations default. A copy that drops the column stores a different value.+PERSON_CREATED_AT = datetime(2025, 6, 1, 12, 30, 45, tzinfo=UTC)+PERSON_MODE = "propertyless"+@frozenclass SourceEvent:@@ -48,6 +52,7 @@ class SourceEvent:event: str = FLAG_EVALUATIONS_SOURCE_EVENT# The age of the row's Kafka create time (_timestamp), when that differs from the event's age.kafka_time_age: timedelta | None = None+ person_properties: str = json.dumps({"email": "[email protected]"})@propertydef uuid(self) -> UUID:@@ -65,6 +70,9 @@ class StoredRow:response: strsession_id: strperson_id: UUID+ person_properties: str+ person_created_at: datetime+ person_mode: strinserted_at_is_timestamp: bool@@ -88,12 +96,17 @@ def copied(event: SourceEvent) -> StoredRow:response=str(event.properties["$feature_flag_response"]),session_id=str(event.properties["$session_id"]),person_id=uuid5(NAMESPACE_URL, event.distinct_id),+ person_properties=event.person_properties or "{}",+ person_created_at=PERSON_CREATED_AT,+ person_mode=PERSON_MODE,inserted_at_is_timestamp=True,)INSIDE_RECENT = flag_called("inside_recent", TEAM_ONE, timedelta(days=2, hours=12))-INSIDE_TEAM_THREE = flag_called("inside_team_three", TEAM_THREE, timedelta(days=30))+# The events column has no DEFAULT. An events row inserted without person properties holds ''.+# The copy must store '{}' instead, the value that the flag_evaluations DEFAULT and the MV store.+INSIDE_TEAM_THREE = replace(flag_called("inside_team_three", TEAM_THREE, timedelta(days=30)), person_properties="")# The default one-hour lag limit and the five-minute delivery timeout put the cutoff 65 minutes before the check.# A row that ingestion produced two hours ago is older than the cutoff, so the job copies it.INSIDE_OLD = replace(flag_called("inside_old", TEAM_TWO, timedelta(days=60)), kafka_time_age=timedelta(hours=2))@@ -158,6 +171,9 @@ def forked(event: SourceEvent) -> StoredRow:response="",session_id="",person_id=uuid5(NAMESPACE_URL, event.distinct_id),+ person_properties="{}",+ person_created_at=datetime(1970, 1, 1, tzinfo=UTC),+ person_mode="full",inserted_at_is_timestamp=True,)@@ -176,6 +192,9 @@ def seed_source_events(cluster: ClickhouseCluster, now: datetime, events: list[Sevent.distinct_id,now - event.age,uuid5(NAMESPACE_URL, event.distinct_id),+ event.person_properties,+ PERSON_CREATED_AT,+ PERSON_MODE,now - (event.age if event.kafka_time_age is None else event.kafka_time_age),)for event in events@@ -184,7 +203,8 @@ def seed_source_events(cluster: ClickhouseCluster, now: datetime, events: list[Sdef insert(client: Client) -> None:client.execute(f"""INSERT INTO {EVENTS_DATA_TABLE()}- (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, _timestamp)+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id,+ person_properties, person_created_at, person_mode, _timestamp)VALUES""",rows,)@@ -236,9 +256,12 @@ 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]}- def select(client: Client) -> list[tuple[UUID, str, str, str, UUID, int]]:+ 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.+ # toTimeZone names one, so person_created_at compares equal to the aware PERSON_CREATED_AT.return client.execute(- """SELECT uuid, flag_key, response, session_id, person_id, inserted_at = timestamp+ """SELECT uuid, flag_key, response, session_id, person_id, person_properties,+ toTimeZone(person_created_at, 'UTC'), person_mode, inserted_at = timestampFROM flag_evaluationsWHERE uuid != %(kafka_path_row)s""",{"kafka_path_row": KAFKA_PATH_ROW.uuid},@@ -251,11 +274,22 @@ def stored_rows(cluster: ClickhouseCluster) -> Counter[StoredRow]:response=response,session_id=session_id,person_id=person_id,+ person_properties=person_properties,+ person_created_at=person_created_at,+ person_mode=person_mode,inserted_at_is_timestamp=bool(inserted_at_is_timestamp),)- for uuid, flag_key, response, session_id, person_id, inserted_at_is_timestamp in cluster.any_host_by_role(- select, NodeRole.DATA- ).result()+ for (+ uuid,+ flag_key,+ response,+ session_id,+ person_id,+ person_properties,+ person_created_at,+ person_mode,+ inserted_at_is_timestamp,+ ) in cluster.any_host_by_role(select, NodeRole.DATA).result())diff --git a/posthog/models/flag_evaluations/sql.py b/posthog/models/flag_evaluations/sql.pyindex 2081f5a8d395..b913ce3f1443 100644--- a/posthog/models/flag_evaluations/sql.py+++ b/posthog/models/flag_evaluations/sql.py@@ -108,6 +108,10 @@ _FLAG_EVALUATIONS_COLUMNS = _FLAG_EVALUATIONS_COLUMNS_TEMPLATE.format(person_properties_default=" DEFAULT '{}'", ts_default=" DEFAULT timestamp")+# A DEFAULT fills only a column the insert omits. A writer that copies person_properties+# from a source that can hold '' maps it to '{}' with this expression.+FLAG_EVALUATIONS_PERSON_PROPERTIES_EXPR = "if(empty(person_properties), '{}', person_properties)"+# 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,@@ -300,7 +304,7 @@ FLAG_EVALUATIONS_MV_SELECT_SQL = lambda: (created_at,person_id,-- The Kafka engine rejects DEFAULT, so an omitted person_properties arrives as ''.- if(empty(person_properties), '{{}}', person_properties) AS person_properties,+ {FLAG_EVALUATIONS_PERSON_PROPERTIES_EXPR} AS person_properties,person_created_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