: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(hogql): resolve flag_evaluations.person_id through person merges (#98900)
Phil Haack2ce15703b9a2
diff --git a/posthog/hogql/database/schema/flag_evaluations.py b/posthog/hogql/database/schema/flag_evaluations.pyindex 3e1a9422a28a..1fdfc3675de9 100644--- a/posthog/hogql/database/schema/flag_evaluations.py+++ b/posthog/hogql/database/schema/flag_evaluations.py@@ -1,14 +1,19 @@+from posthog.hogql.database.lazy_join_tags import PERSON_DISTINCT_ID_OVERRIDESfrom posthog.hogql.database.models import (DateTimeDatabaseField,+ ExpressionField,FieldOrTable,FieldTraverser,IntegerDatabaseField,+ LazyJoin,StringDatabaseField,StringJSONDatabaseField,Table,UUIDDatabaseField,VirtualTable,)+from posthog.hogql.database.schema.person_distinct_id_overrides import PersonDistinctIdOverridesTable+from posthog.hogql.parser import parse_expr# The physical read table is the Distributed `flag_evaluations` on the DATA nodes, defined in# posthog/models/flag_evaluations/sql.py. That module imports django.conf, and@@ -17,8 +22,28 @@ from posthog.hogql.database.models import (FLAG_EVALUATIONS_CLICKHOUSE_TABLE = "flag_evaluations"+# The expression the events table uses under the persons-on-events modes that apply overrides. This table+# applies it for every team instead of following the mode, because the mode decides where person properties+# come from and this table stores none. A team on `PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS` therefore+# reads a merge-aware person here, and from `events` the write-time person until the squash rewrites it.+# The table and its `poe` subtable each take their own copy. The tests in test_flag_evaluations.py select+# `person_id` and `person.id` together, so the two drifting apart fails there.+def _person_id() -> ExpressionField:+ return ExpressionField(+ name="person_id",+ expr=parse_expr(+ # NOTE: assumes `join_use_nulls = 0` (the default), as ``override.distinct_id`` is not Nullable+ "if(not(empty(override.distinct_id)), override.person_id, flag_evaluation_person_id)",+ start=None,+ ),+ isolate_scope=True,+ description="The person the evaluation is attributed to, corrected for any later identify or merge, so "+ "`uniq(person_id)` counts a merged person once.",+ )++class FlagEvaluationsPersonSubTable(VirtualTable):- """The person column carried on the flag-evaluation row itself.+ """The person the flag-evaluation row resolves to, corrected by `person_distinct_id_overrides`.Narrower than EventsPersonSubTable, which also declares `person_created_at` and `properties` --columns this table does not store, so reusing it would let `person.created_at`,@@ -26,7 +51,7 @@ class FlagEvaluationsPersonSubTable(VirtualTable):"""fields: dict[str, FieldOrTable] = {- "id": UUIDDatabaseField(name="person_id", nullable=False),+ "id": _person_id(),}def to_printed_clickhouse(self, context):@@ -74,12 +99,25 @@ class FlagEvaluationsTable(Table):nullable=False,description="When the row was written to ClickHouse; later than `created_at` by the ingestion lag.",),- "person_id": UUIDDatabaseField(+ # Left visible because it is the only person filter the `person_id_idx` bloom filter can serve,+ # and a hidden field reaches neither the schema browser nor `system.information_schema.columns`.+ "flag_evaluation_person_id": UUIDDatabaseField(name="person_id",nullable=False,- description="The person the evaluation was attributed to when it happened. A later identify or merge "- "does not rewrite it, so it can differ from the person `events` resolves for the same `distinct_id`.",+ description="The person written onto the row at ingestion time, before any later identify or "+ "merge. Unlike `person_id` it is a stored column, so filtering on it can use the table's index; "+ "it stays stale until the person-overrides squash rewrites it.",+ ),+ # Joined only when a query reads `person_id`, so every other query pays nothing for it. Hidden+ # because it is an implementation detail of that correction: it carries person columns the row+ # does not store, and `person` is the documented way to reach the person.+ "override": LazyJoin(+ from_field=["distinct_id"],+ join_table=PersonDistinctIdOverridesTable(),+ resolver=PERSON_DISTINCT_ID_OVERRIDES,+ hidden=True,),+ "person_id": _person_id(),"flag_key": StringDatabaseField(name="flag_key",nullable=False,@@ -99,12 +137,13 @@ class FlagEvaluationsTable(Table):nullable=False,description="Identifier of the flag-evaluation request, shared by every flag evaluated in it.",),- # The person column on the row itself. Should not be used directly; reached via `person`.+ # Should not be used directly; reached via `person`."poe": FlagEvaluationsPersonSubTable(),"person": FieldTraverser(chain=["poe"],- description="The person the evaluation was attributed to when it happened. Carries the id alone: the "- "row stores no person properties, so join to `persons` to read them.",+ description="The person the evaluation is attributed to, corrected for any later identify or merge, so "+ "`uniq(person.id)` counts a merged person once. Carries the id alone: the row stores no person "+ "properties, so join to `persons` to read them.",),# Group keys only. The row carries no group properties, so there is nothing to traverse to:# join to `groups` on one of these keys to read a group's current properties.@@ -120,6 +159,11 @@ class FlagEvaluationsTable(Table):"$group_4": StringDatabaseField(name="$group_4", nullable=False, description="Key of the type-4 group."),}+ def avoid_asterisk_fields(self) -> list[str]:+ # The stored person is a filtering escape hatch, not a second person column in `SELECT *`. Only the+ # asterisk reads this list, so the column stays in the schema browser and in `information_schema`.+ return ["flag_evaluation_person_id"]+def to_printed_clickhouse(self, context):return FLAG_EVALUATIONS_CLICKHOUSE_TABLEdiff --git a/posthog/hogql/database/schema/test/test_flag_evaluations.py b/posthog/hogql/database/schema/test/test_flag_evaluations.pyindex 1067d7fce0bf..336a2c7c1bb5 100644--- a/posthog/hogql/database/schema/test/test_flag_evaluations.py+++ b/posthog/hogql/database/schema/test/test_flag_evaluations.py@@ -62,7 +62,7 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):],)- def _select(self, columns: str, where: str = ""):+ def _execute(self, columns: str, where: str = ""):# settings.DEBUG is False under the test runner, so the org gate fail-closes and prunes the# table. test_database.py covers the gate itself; here it only has to be out of the way.context = HogQLContext(team_id=self.team.pk, team=self.team, user=self.user, enable_select_queries=True)@@ -75,7 +75,16 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):team=self.team,context=context,pretty=False,- ).results+ )++ def _select(self, columns: str, where: str = ""):+ return self._execute(columns, where).results++ def _override(self, person_id: uuid.UUID, version: int, is_deleted: bool = False) -> None:+ sync_execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted) VALUES",+ [(self.team.pk, "probe-distinct-id", str(person_id), version, int(is_deleted))],+ )def _restrict(self, name: str, property_type, group_type_index: int | None = None) -> None:self.organization.available_product_features = [@@ -113,6 +122,52 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):)]+ def test_person_id_follows_a_later_merge(self):+ # Ingestion never rewrites the person on the row, so only the read can correct it. Drop the+ # override join and `uniq(person_id)` counts the pre-merge and the post-merge person as two+ # humans. The case where no override exists is covered by the test above, which runs with no+ # rows in the overrides table.+ merged_person_id = uuid.uuid4()+ self._override(merged_person_id, version=1)++ assert self._select("person_id, person.id") == [(merged_person_id, merged_person_id)]++ def test_person_id_follows_the_latest_override_version(self):+ # A distinct_id collects one override row per merge, so the read has to pick the highest version.+ # Point the join at `raw_person_distinct_id_overrides` instead of the deduplicating view and the+ # row comes back once per override, which is also how a fan-out in the join would show up.+ merged_person_id = uuid.uuid4()+ self._override(uuid.uuid4(), version=1)+ self._override(merged_person_id, version=2)++ assert self._select("person_id, person.id") == [(merged_person_id, merged_person_id)]++ def test_deleted_override_falls_back_to_the_stored_person(self):+ # A merge that is undone writes a tombstone rather than removing the row. Drop the `is_deleted`+ # handling from the read and the evaluation stays attributed to a person it no longer belongs to.+ self._override(uuid.uuid4(), version=1)+ self._override(uuid.uuid4(), version=2, is_deleted=True)++ assert self._select("person_id, person.id") == [(self.person_id, self.person_id)]++ def test_overrides_are_joined_only_when_person_id_is_read(self):+ # The join is the expensive half of the correction; a query that never names the person must+ # not pay for it.+ assert "person_distinct_id_overrides" not in self._execute("flag_key").clickhouse+ assert "person_distinct_id_overrides" in self._execute("person_id").clickhouse++ def test_asterisk_carries_the_corrected_person_and_no_second_person_column(self):+ # Let the stored column into the expansion and it takes the slot `person_id` held, so the SQL+ # editor's default query shifts every later column and shows two person ids that disagree.+ merged_person_id = uuid.uuid4()+ self._override(merged_person_id, version=1)++ response = self._execute("*")+ columns = response.columns or []++ assert "flag_evaluation_person_id" not in columns+ assert response.results[0][columns.index("person_id")] == merged_person_id+def test_numeric_property_compares_as_a_number(self):# Drop this table from any of the property-type dispatches and the read stays a String, so# the comparison no longer answers the numeric question.