: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): mark lifecycle flag calls new by person or group creation (#118127)
Phil Haacka8935d312025
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.tsindex e30b0d926635..6febaa9b2772 100644--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts@@ -1844,7 +1844,7 @@ describe('insightNavLogic', () => {table_name: 'posthog.flag_evaluations',timestamp_field: 'timestamp',aggregation_target_field: 'person_id',- created_at_field: 'timestamp',+ created_at_field: 'person.created_at',},],},@@ -1861,7 +1861,7 @@ describe('insightNavLogic', () => {table_name: 'posthog.flag_evaluations',timestamp_field: 'timestamp',aggregation_target_field: 'person_id',- created_at_field: 'timestamp',+ created_at_field: 'person.created_at',},],},diff --git a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.tsindex 780d541cbb2c..da38b87790f8 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts@@ -41,8 +41,9 @@ export const FLAG_EVALUATIONS_SERIES_FIELDS: Required<distinct_id_field: 'distinct_id',// person_id is the merge-corrected person. A flag calls step counts the same person as an events step.aggregation_target_field: 'person_id',- // The table stores no person creation time. Lifecycle takes the earliest flag call it reads instead.- created_at_field: 'timestamp',+ // Lifecycle calls a person new in the period the person was created, as it does on events.+ // withFlagCallsAggregationTarget swaps in the group's creation time when the query counts groups.+ created_at_field: 'person.created_at',}/** Trends computes these maths from events for every series. On a flag calls series they would count events, not flag calls. */@@ -65,19 +66,33 @@ export function readsFlagCalls(query: InsightQueryNode): boolean {return nodes.some((node) => (node as { table_name?: string } | undefined)?.table_name === FLAG_EVALUATIONS_TABLE)}-/** Sets the actor column of each flag calls series to the query's aggregation: a group key, the funnel's SQL expression, or the person. */+/** Sets the actor columns of each flag calls series to the query's aggregation.+ * The actor is a group key, the funnel's SQL expression, or the person.+ * A lifecycle series also gets the creation time of that group or person. */export function withFlagCallsAggregationTarget<Q extends InsightQueryNode>(query: Q): Q {const groupTypeIndex = 'aggregation_group_type_index' in query ? query.aggregation_group_type_index : null// The flag_evaluations row carries the event's properties.// An expression such as properties.$session_id reads the same value there as on events.const aggregateByHogQL = query.kind === NodeKind.FunnelsQuery ? query.funnelsFilter?.funnelAggregateByHogQL : nullconst target = getHogQLValue(groupTypeIndex, aggregateByHogQL)+ const createdAtField =+ groupTypeIndex != null ? `group_${groupTypeIndex}.created_at` : FLAG_EVALUATIONS_SERIES_FIELDS.created_at_fieldconst retarget = <T>(node: T): T => {- const fields = node as { table_name?: string; aggregation_target_field?: string } | null | undefined- return fields?.table_name === FLAG_EVALUATIONS_TABLE &&- fields.aggregation_target_field != null &&- fields.aggregation_target_field !== target- ? { ...node, aggregation_target_field: target }+ const fields = node as+ | { table_name?: string; aggregation_target_field?: string; created_at_field?: string }+ | null+ | undefined+ if (fields?.table_name !== FLAG_EVALUATIONS_TABLE) {+ return node+ }+ const retargetsActor = fields.aggregation_target_field != null && fields.aggregation_target_field !== target+ const retargetsCreatedAt = fields.created_at_field != null && fields.created_at_field !== createdAtField+ return retargetsActor || retargetsCreatedAt+ ? {+ ...node,+ ...(retargetsActor ? { aggregation_target_field: target } : {}),+ ...(retargetsCreatedAt ? { created_at_field: createdAtField } : {}),+ }: node}diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.tsindex b89df9113f3d..30c04e4fb3e7 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts@@ -511,12 +511,30 @@ describe('insightVizDataLogic', () => {{kind: NodeKind.FunnelsQuery,flagCalls: { series: [{ ...flagCallsNode, kind: NodeKind.FunnelsDataWarehouseNode }] },- targets: (source: any) => [source.series[0].aggregation_target_field],+ targets: (source: any) => [+ source.series[0].aggregation_target_field,+ source.series[0].created_at_field,+ ],+ byGroup: ['$group_1', undefined],+ byPerson: ['person_id', undefined],},{kind: NodeKind.LifecycleQuery,- flagCalls: { series: [{ ...flagCallsNode, kind: NodeKind.LifecycleDataWarehouseNode }] },- targets: (source: any) => [source.series[0].aggregation_target_field],+ flagCalls: {+ series: [+ {+ ...flagCallsNode,+ kind: NodeKind.LifecycleDataWarehouseNode,+ created_at_field: 'person.created_at',+ },+ ],+ },+ targets: (source: any) => [+ source.series[0].aggregation_target_field,+ source.series[0].created_at_field,+ ],+ byGroup: ['$group_1', 'group_1.created_at'],+ byPerson: ['person_id', 'person.created_at'],},{kind: NodeKind.RetentionQuery,@@ -524,18 +542,22 @@ describe('insightVizDataLogic', () => {targets: (source: any) => [source.retentionFilter.targetEntity.aggregation_target_field,source.retentionFilter.returningEntity.aggregation_target_field,+ source.retentionFilter.targetEntity.created_at_field,+ source.retentionFilter.returningEntity.created_at_field,],+ byGroup: ['$group_1', '$group_1', undefined, undefined],+ byPerson: ['person_id', 'person_id', undefined, undefined],},- ])('counts $kind flag calls by the aggregation group', ({ kind, flagCalls, targets }) => {+ ])('counts $kind flag calls by the aggregation group', ({ kind, flagCalls, targets, byGroup, byPerson }) => {const update = (source: Record<string, unknown>): void =>builtInsightVizDataLogic.actions.updateQuerySource({ kind, ...source } as QuerySourceUpdate)update({ aggregation_group_type_index: 1 })update(flagCalls)- expect(new Set(targets(builtInsightVizDataLogic.values.querySource))).toEqual(new Set(['$group_1']))+ expect(targets(builtInsightVizDataLogic.values.querySource)).toEqual(byGroup)update({ aggregation_group_type_index: undefined })- expect(new Set(targets(builtInsightVizDataLogic.values.querySource))).toEqual(new Set(['person_id']))+ expect(targets(builtInsightVizDataLogic.values.querySource)).toEqual(byPerson)})it('counts funnel flag calls by the funnel aggregation expression', () => {diff --git a/posthog/test/base.py b/posthog/test/base.pyindex dc1f847e5dc4..3107db13a76a 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -122,7 +122,7 @@ from posthog.models.event.sql import (WRITABLE_EVENTS_JSON_TABLE_SQL,WRITABLE_EVENTS_TABLE_SQL,)-from posthog.models.event.util import _resolve_person_for_bulk_event, bulk_create_events+from posthog.models.event.util import ZERO_DATE, _resolve_person_for_bulk_event, bulk_create_eventsfrom posthog.models.exchange_rate.sql import (DROP_EXCHANGE_RATE_DICTIONARY_SQL,DROP_EXCHANGE_RATE_TABLE_SQL,@@ -1812,18 +1812,20 @@ def _create_flag_evaluations(*,distinct_id: str = "evaluator",person_id: uuid.UUID | str | None = None,+ person_created_at: dt.datetime | None = None,response: str | bool = True,properties: dict[str, Any] | None = None,) -> None:"""Insert `count` $feature_flag_called rows for flag_key into flag_evaluations. Unlike _create_event, it writes- the rows immediately. Each row gets a new random person_id unless the caller passes one."""+ the rows immediately. Each row gets a new random person_id unless the caller passes one. Without a+ person_created_at, a row stores the Unix epoch, as a production row written without person columns does."""timestamp = timestamp or dt.datetime.now(dt.UTC)properties_json = json.dumps({**(properties or {}), "$feature_flag": flag_key, "$feature_flag_response": response})# writable_flag_evaluations does not declare flag_key. The shard computes it from properties.$feature_flag.sync_execute("""INSERT INTO writable_flag_evaluations- (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id)+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, person_created_at)VALUES""",[@@ -1836,6 +1838,7 @@ def _create_flag_evaluations(distinct_id,timestamp,str(person_id or uuid.uuid4()),+ person_created_at or ZERO_DATE,)for _ in range(count)],diff --git a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.pyindex 57afd1c8f163..f0e63b649b64 100644--- a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py+++ b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py@@ -1,4 +1,3 @@-import uuidfrom datetime import UTC, datetimefrom typing import Any@@ -27,9 +26,11 @@ from posthog.schema import (FunnelsDataWarehouseNode,FunnelsFilter,FunnelsQuery,+ HogQLQueryModifiers,IntervalType,LifecycleDataWarehouseNode,LifecycleQuery,+ PersonsOnEventsMode,PropertyOperator,RetentionQuery,StickinessQuery,@@ -38,6 +39,9 @@ from posthog.schema import (from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_HOGQL_TABLE+from posthog.models.group.util import create_group+from posthog.models.person import Person+from products.product_analytics.backend.facade.queries import (FunnelsQueryRunner,LifecycleQueryRunner,@@ -49,6 +53,8 @@ from products.product_analytics.backend.facade.queries import (TABLE = FLAG_EVALUATIONS_HOGQL_TABLENOW = datetime(2025, 1, 10, 12, 0, tzinfo=UTC)DATE_RANGE = DateRange(date_from="2025-01-08", date_to="2025-01-10")+IN_DATE_RANGE = datetime(2025, 1, 8, 8, 0, tzinfo=UTC)+BEFORE_DATE_RANGE = datetime(2024, 12, 1, tzinfo=UTC)PROBE_FLAG = DataWarehousePropertyFilter(key="flag_key", operator=PropertyOperator.EXACT, value="probe-flag")@@ -67,6 +73,14 @@ def _aggregation_target(aggregation_group_type_index: int | None) -> str:return "person_id" if aggregation_group_type_index is None else f"$group_{aggregation_group_type_index}"+def _created_at_field(aggregation_group_type_index: int | None) -> str:+ return (+ "person.created_at"+ if aggregation_group_type_index is None+ else f"group_{aggregation_group_type_index}.created_at"+ )++def _retention_entity(aggregation_target_field: str) -> dict[str, Any]:return {"id": TABLE,@@ -87,13 +101,13 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):)table_gate.start()self.addCleanup(table_gate.stop)- person_created_at = datetime(2025, 1, 8, 8, 0, tzinfo=UTC)- alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=person_created_at)- bob = _create_person(team_id=self.team.pk, distinct_ids=["bob"], created_at=person_created_at)- for distinct_id, person_id, flag_key, response, occurred_at, properties in [+ alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=IN_DATE_RANGE)+ bob = _create_person(team_id=self.team.pk, distinct_ids=["bob"], created_at=IN_DATE_RANGE)+ alice_2 = _create_person(team_id=self.team.pk, distinct_ids=["alice-2"], created_at=IN_DATE_RANGE)+ for distinct_id, person, flag_key, response, occurred_at, properties in [("alice",- alice.uuid,+ alice,"probe-flag","test",datetime(2025, 1, 8, 10, tzinfo=UTC),@@ -101,7 +115,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):),("alice",- alice.uuid,+ alice,"probe-flag","test",datetime(2025, 1, 8, 11, tzinfo=UTC),@@ -109,32 +123,24 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):),("bob",- bob.uuid,+ bob,"probe-flag","control",datetime(2025, 1, 8, 12, tzinfo=UTC),{"$session_id": "s-bob", "$group_0": "org-b"},),- ("bob", bob.uuid, "other-flag", "true", datetime(2025, 1, 9, 9, tzinfo=UTC), {}),+ ("bob", bob, "other-flag", "true", datetime(2025, 1, 9, 9, tzinfo=UTC), {}),# The row stores the person alice-2 had before the merge. Only the override makes it alice's call.("alice-2",- uuid.uuid4(),+ alice_2,"probe-flag","test",datetime(2025, 1, 8, 13, tzinfo=UTC),{"$session_id": "s-alice-2"},),]:- _create_flag_evaluations(- self.team.pk,- flag_key,- timestamp=occurred_at,- distinct_id=distinct_id,- person_id=person_id,- response=response,- properties=properties,- )+ self._create_flag_call(distinct_id, person, flag_key, response, occurred_at, properties)_create_event(team=self.team,event="$pageview",@@ -145,6 +151,33 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):flush_persons_and_events()create_person_id_override_by_distinct_id("alice-2", "alice", self.team.pk, version=1)+ def _create_flag_call(+ self,+ distinct_id: str,+ person: Person,+ flag_key: str,+ response: str,+ occurred_at: datetime,+ properties: dict[str, str],+ ) -> None:+ _create_flag_evaluations(+ self.team.pk,+ flag_key,+ timestamp=occurred_at,+ distinct_id=distinct_id,+ person_id=person.uuid,+ person_created_at=person.created_at,+ response=response,+ properties=properties,+ )+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp=occurred_at,+ properties={**properties, "$feature_flag": flag_key, "$feature_flag_response": response},+ )+@parameterized.expand([("total_calls", BaseMathType.TOTAL, {"test": 3, "control": 1}),@@ -246,22 +279,39 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):("by_person",None,- {"new": [2, 0, 0], "returning": [0, 1, 0], "resurrecting": [0, 0, 0], "dormant": [0, -1, -1]},+ {"new": [2, 0, 0], "returning": [0, 1, 0], "resurrecting": [0, 1, 0], "dormant": [0, -1, -2]},),("by_group",0,- {"new": [2, 0, 0], "returning": [0, 0, 0], "resurrecting": [0, 0, 0], "dormant": [0, -2, 0]},+ {"new": [1, 0, 0], "returning": [0, 0, 0], "resurrecting": [1, 1, 0], "dormant": [0, -2, -1]},),])- def test_lifecycle(+ def test_lifecycle_matches_events(self,_name: str,aggregation_group_type_index: int | None,expected: dict[str, list[int]],):- # Lifecycle excludes this personless call. Counting it would add a third new user or group on 2025-01-08.+ for group_key, group_created_at in [+ ("org-a", IN_DATE_RANGE),+ ("org-b", BEFORE_DATE_RANGE),+ ("org-c", BEFORE_DATE_RANGE),+ ]:+ create_group(team_id=self.team.pk, group_type_index=0, group_key=group_key, timestamp=group_created_at)+ # Carol, org-b and org-c predate the date range, so their first call in it makes them resurrecting, not new.+ # Bob, org-b's only caller, was created in the range, so org-b reads new if by_group uses person creation time.+ carol = _create_person(team_id=self.team.pk, distinct_ids=["carol"], created_at=BEFORE_DATE_RANGE)+ self._create_flag_call(+ "carol",+ carol,+ "other-flag",+ "true",+ datetime(2025, 1, 9, 12, tzinfo=UTC),+ {"$group_0": "org-c"},+ )+ # Lifecycle excludes this personless call. Counting it would add an active user or group on 2025-01-08._create_flag_evaluations(self.team.pk,"probe-flag",@@ -273,17 +323,26 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):dateRange=DATE_RANGE,interval=IntervalType.DAY,aggregation_group_type_index=aggregation_group_type_index,+ # This mode reads the person creation time stored on the row and the merge-corrected person, as+ # flag_evaluations does.+ modifiers=HogQLQueryModifiers(+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS+ ),series=[LifecycleDataWarehouseNode(id=TABLE,table_name=TABLE,timestamp_field="timestamp",aggregation_target_field=_aggregation_target(aggregation_group_type_index),- created_at_field="timestamp",+ created_at_field=_created_at_field(aggregation_group_type_index),)],)+ events_query = query.model_copy(update={"series": [EventsNode(event="$feature_flag_called")]})results = LifecycleQueryRunner(query=query, team=self.team).calculate().results+ events_results = LifecycleQueryRunner(query=events_query, team=self.team).calculate().results- assert {r["status"]: r["data"] for r in results} == expected+ lifecycle = {r["status"]: r["data"] for r in results}+ assert lifecycle == expected+ assert lifecycle == {r["status"]: r["data"] for r in events_results}