: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(propdefs): skip eventproperty join for feature flag queries (#61259)
Eli Reismanb4569177f0c1
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex 36ab960a2dc6..165badce6f2d 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -3662,7 +3662,7 @@ export type PropertyDefinitionsListParams = {*/excluded_properties?: string/**- * Whether to return only properties for events in `event_names`+ * Whether to return only properties for events in `event_names`. Note: this event scoping does not apply to feature flag properties ($feature/*), which are global and not tracked per-event; to retrieve feature flags use is_feature_flag=true instead.* @nullable*/filter_by_event_names?: boolean | null@@ -3671,7 +3671,7 @@ export type PropertyDefinitionsListParams = {*/group_type_index?: number/**- * Whether to return only (or excluding) feature flag properties+ * Whether to return only (or excluding) feature flag properties ($feature/*). Flags are global, not per-event, so they can't be scoped by event_names/filter_by_event_names — pass is_feature_flag=true to list them all.* @nullable*/is_feature_flag?: boolean | nulldiff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.pyindex 74928fe865a1..dafe1c53cb17 100644--- a/posthog/api/test/test_property_definition.py+++ b/posthog/api/test/test_property_definition.py@@ -580,6 +580,21 @@ class TestPropertyDefinitionAPI(APIBaseTest):if expected_names:assert [r["name"] for r in response.json()["results"]] == expected_names+ def test_feature_flag_filter_with_event_names_does_not_require_eventproperty_rows(self) -> None:+ PropertyDefinition.objects.create(team=self.team, name="$feature/my-flag", property_type="Boolean")+ PropertyDefinition.objects.create(team=self.team, name="$feature/other-flag", property_type="Boolean")+ # No EventProperty rows for $feature/* — this is the post-fix state++ response = self.client.get(+ f"/api/projects/{self.team.pk}/property_definitions/"+ f"?is_feature_flag=true&event_names=%5B%22%24pageview%22%5D&filter_by_event_names=true"+ )+ assert response.status_code == status.HTTP_200_OK+ names = [r["name"] for r in response.json()["results"]]+ assert "$feature/my-flag" in names+ assert "$feature/other-flag" in names+ assert all(r["is_seen_on_filtered_events"] is None for r in response.json()["results"])+@patch("posthoganalytics.capture")def test_delete_property_definition(self, mock_capture):property_definition = PropertyDefinition.objects.create(diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex bacd966f4f8b..50fd52fe430d 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -72,7 +72,11 @@ class PropertyDefinitionQuerySerializer(serializers.Serializer):)# :TODO: Move this under `type`is_feature_flag = serializers.BooleanField(- help_text="Whether to return only (or excluding) feature flag properties",+ help_text=(+ "Whether to return only (or excluding) feature flag properties ($feature/*). "+ "Flags are global, not per-event, so they can't be scoped by event_names/filter_by_event_names — "+ "pass is_feature_flag=true to list them all."+ ),required=False,allow_null=True,default=None,@@ -82,7 +86,11 @@ class PropertyDefinitionQuerySerializer(serializers.Serializer):required=False,)filter_by_event_names = serializers.BooleanField(- help_text="Whether to return only properties for events in `event_names`",+ help_text=(+ "Whether to return only properties for events in `event_names`. "+ "Note: this event scoping does not apply to feature flag properties ($feature/*), which are "+ "global and not tracked per-event; to retrieve feature flags use is_feature_flag=true instead."+ ),required=False,allow_null=True,default=None,@@ -196,8 +204,11 @@ class QueryContext:if is_feature_flag is None:return selfelif is_feature_flag:+ # Paired with property-defs-rs skip of $feature/* writes to eventproperty.+ # Do not revert without restoring those writes, or the flag picker empties.return dataclasses.replace(self,+ should_join_event_property=False,is_feature_flag_filter="AND (name LIKE %(is_feature_flag_like)s)",params={**self.params, "is_feature_flag_like": "$feature/%"},)@@ -259,7 +270,7 @@ class QueryContext:if event_names:event_names = json.loads(event_names)- if event_names and len(event_names) > 0:+ if event_names and len(event_names) > 0 and self.should_join_event_property:event_property_field = f"{self.posthog_eventproperty_table_join_alias}.property IS NOT NULL"event_name_join_filter = "AND event = ANY(%(event_names)s)"diff --git a/rust/property-defs-rs/src/api/v1/query.rs b/rust/property-defs-rs/src/api/v1/query.rsindex 6523f9d14920..fec68147aace 100644--- a/rust/property-defs-rs/src/api/v1/query.rs+++ b/rust/property-defs-rs/src/api/v1/query.rs@@ -66,6 +66,7 @@ impl Manager {project_id,params.parent_type,¶ms.event_names,+ ¶ms.is_feature_flag,);// begin the WHERE clause@@ -137,11 +138,12 @@ impl Manager {self.gen_prop_defs_select_clause(qb, params.use_enterprise_taxonomy);// append event_property_field clause to SELECT clause- let is_seen_resolved = if self.is_parent_type_event(params.parent_type) {- format!("{EVENT_PROPERTY_TABLE_ALIAS}.\"property\"")- } else {- "NULL".to_string()- };+ let is_seen_resolved =+ if self.should_join_event_property(params.parent_type, ¶ms.is_feature_flag) {+ format!("{EVENT_PROPERTY_TABLE_ALIAS}.\"property\"")+ } else {+ "NULL".to_string()+ };qb.push(format!(", {is_seen_resolved} IS NOT NULL AS is_seen_on_filtered_events "));@@ -152,6 +154,7 @@ impl Manager {project_id,params.parent_type,¶ms.event_names,+ ¶ms.is_feature_flag,);// begin the WHERE clause@@ -243,33 +246,34 @@ impl Manager {project_id: i32,parent_type: PropertyParentType,event_names: &'args [String],+ is_feature_flag: &Option<bool>,) {- // conditionally join on event properties table- // this join is only applied if the query is scoped to type "event"- if self.is_parent_type_event(parent_type) {- let filter_by_event_names = !event_names.is_empty();+ if !self.should_join_event_property(parent_type, is_feature_flag) {+ return;+ }- // if a list of event_names was supplied, we want this join to narrow- // to only those events. otherwise it's a LEFT JOIN for enrichment only- qb.push(self.event_property_join_type(filter_by_event_names));- qb.push(format!(- " (SELECT DISTINCT property FROM {EVENT_PROPERTY_TABLE} WHERE COALESCE(project_id, team_id) = "- ));- qb.push_bind(project_id);- qb.push(" ");-- // conditionally apply filter if event_names list was supplied- if filter_by_event_names {- qb.push(" AND event = ANY(");- qb.push_bind(event_names);- qb.push(") ");- }+ let filter_by_event_names = !event_names.is_empty();- // close the JOIN clause and add the JOIN condition- qb.push(format!(- ") AS {EVENT_PROPERTY_TABLE_ALIAS} ON {EVENT_PROPERTY_TABLE_ALIAS}.\"property\" = {PROPERTY_DEFS_TABLE}.\"name\" "- ));+ // if a list of event_names was supplied, we want this join to narrow+ // to only those events. otherwise it's a LEFT JOIN for enrichment only+ qb.push(self.event_property_join_type(filter_by_event_names));+ qb.push(format!(+ " (SELECT DISTINCT property FROM {EVENT_PROPERTY_TABLE} WHERE COALESCE(project_id, team_id) = "+ ));+ qb.push_bind(project_id);+ qb.push(" ");++ // conditionally apply filter if event_names list was supplied+ if filter_by_event_names {+ qb.push(" AND event = ANY(");+ qb.push_bind(event_names);+ qb.push(") ");}++ // close the JOIN clause and add the JOIN condition+ qb.push(format!(+ ") AS {EVENT_PROPERTY_TABLE_ALIAS} ON {EVENT_PROPERTY_TABLE_ALIAS}.\"property\" = {PROPERTY_DEFS_TABLE}.\"name\" "+ ));}fn init_where_clause(&self, qb: &mut QueryBuilder<Postgres>, project_id: i32) {@@ -471,6 +475,16 @@ impl Manager {}}+ // Should the query JOIN on posthog_eventproperty? False for non-event types+ // and for feature flag queries (flags are global, not per-event).+ fn should_join_event_property(+ &self,+ parent_type: PropertyParentType,+ is_feature_flag: &Option<bool>,+ ) -> bool {+ self.is_parent_type_event(parent_type) && !matches!(is_feature_flag, Some(true))+ }+// is the "parent type" of this request (and prop defs query) the default "event" type?// this controls whether the base query should include a JOIN on posthog_eventpropertyfn is_parent_type_event(&self, parent_type: PropertyParentType) -> bool {diff --git a/rust/property-defs-rs/tests/queries.rs b/rust/property-defs-rs/tests/queries.rsindex 81be97f5c054..d6c0b5f77182 100644--- a/rust/property-defs-rs/tests/queries.rs+++ b/rust/property-defs-rs/tests/queries.rs@@ -25,6 +25,7 @@ async fn test_event_property_definitions_queries(test_pool: PgPool) {query_type_event_is_numerical_filter(&qmgr, project_id).await;query_type_event_is_feature_flag_filter(&qmgr, project_id).await;query_type_event_is_not_feature_flag_filter(&qmgr, project_id).await;+ query_feature_flag_with_event_names_skips_eventproperty_join(&qmgr, project_id).await;query_event_with_group_type_index_fails().await;query_non_event_type_with_event_names_param().await;}@@ -273,7 +274,88 @@ async fn query_type_event_is_not_feature_flag_filter(qmgr: &Manager, project_id:}}-// only PropertyParentType::Event query can include an event_names filter parameter+// Regression test: is_feature_flag=true + event_names must skip the eventproperty INNER JOIN.+// The seed data has $feature/foo-bar-baz WITH a matching eventproperty row (id 109). This test+// adds a second flag WITHOUT any eventproperty row and asserts both are returned — proving the+// join is skipped. Without the join-skip fix, the second flag would be filtered out by the+// INNER JOIN.+async fn query_feature_flag_with_event_names_skips_eventproperty_join(+ qmgr: &Manager,+ project_id: i32,+) {+ // Insert a propertydefinition row for a flag that has NO posthog_eventproperty row+ let mut args = PgArguments::default();+ args.add(Uuid::now_v7()).unwrap();+ args.add("$feature/no-ep-row").unwrap();+ args.add(1_i32).unwrap(); // project_id+ args.add(1_i32).unwrap(); // team_id+ args.add(false).unwrap(); // is_numerical+ args.add(1_i32).unwrap(); // type = Event+ args.add("Boolean").unwrap(); // property_type+ args.add(-1_i32).unwrap(); // group_type_index++ sqlx::query_with(+ r#"+ INSERT INTO posthog_propertydefinition+ (id, name, project_id, team_id, is_numerical, "type", property_type, group_type_index)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ "#,+ args,+ )+ .execute(&qmgr.pool)+ .await+ .expect("failed to insert $feature/no-ep-row propertydefinition");++ let mut qb = sqlx::QueryBuilder::new("");+ let params = Params {+ is_feature_flag: Some(true),+ event_names: vec!["$pageview".to_string()],+ ..Default::default()+ };++ let query = qmgr.property_definitions_query(&mut qb, project_id, ¶ms);+ let results = qmgr+ .pool+ .fetch_all(query)+ .await+ .expect("feature flag query with event_names failed");++ let names: Vec<String> = results.iter().map(|r| r.get("name")).collect();++ // Both flags must be returned — the one with an eventproperty row AND the one without+ assert!(+ names.contains(&"$feature/foo-bar-baz".to_string()),+ "expected $feature/foo-bar-baz (has eventproperty row): {names:?}"+ );+ assert!(+ names.contains(&"$feature/no-ep-row".to_string()),+ "expected $feature/no-ep-row (NO eventproperty row) — join-skip regression: {names:?}"+ );++ // is_seen_on_filtered_events must be NULL (false) for both since join is skipped+ for row in &results {+ let is_seen: Option<bool> = row.get("is_seen_on_filtered_events");+ assert!(+ is_seen.is_none() || is_seen == Some(false),+ "is_seen_on_filtered_events should be NULL when join is skipped"+ );+ }++ // count query must also work+ let mut qb = sqlx::QueryBuilder::new("");+ let count_query = qmgr.count_query(&mut qb, project_id, ¶ms);+ let count_result = qmgr+ .pool+ .fetch_one(count_query)+ .await+ .expect("count query failed");+ let total_count: i64 = count_result.get(0);+ assert!(+ total_count >= 2,+ "expected at least 2 feature flag rows, got {total_count}"+ );+}+async fn query_non_event_type_with_event_names_param() {let params_invalid_event_names = Params {parent_type: PropertyParentType::Session,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 86faea2fdc4b..4b769c56100e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49702,7 +49702,7 @@ export namespace Schemas {*/excluded_properties?: string;/**- * Whether to return only properties for events in `event_names`+ * Whether to return only properties for events in `event_names`. Note: this event scoping does not apply to feature flag properties ($feature/*), which are global and not tracked per-event; to retrieve feature flags use is_feature_flag=true instead.* @nullable*/filter_by_event_names?: boolean | null;@@ -49711,7 +49711,7 @@ export namespace Schemas {*/group_type_index?: number;/**- * Whether to return only (or excluding) feature flag properties+ * Whether to return only (or excluding) feature flag properties ($feature/*). Flags are global, not per-event, so they can't be scoped by event_names/filter_by_event_names — pass is_feature_flag=true to list them all.* @nullable*/is_feature_flag?: boolean | null;