Skip to content

: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.

feat(flags): compute has_experiment in the flags PG fallback query (#65938)

Phil Haackfa763a70269b
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index b0df769a33e7..f2c4f36af7ae 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -2,8 +2,8 @@ use crate::api::errors::FlagError;
use crate::cohorts::cohort_models::Cohort;
use crate::database::get_connection_with_metrics;
use crate::flags::flag_models::{
- default_has_experiment, EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow,
- FlagPropertyGroup, HypercacheFlagsWrapper,
+ EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, FlagPropertyGroup,
+ HypercacheFlagsWrapper,
};
use crate::metrics::consts::TOMBSTONE_COUNTER;
use common_database::PostgresReader;
@@ -150,7 +150,13 @@ impl FeatureFlagList {
ARRAY_AGG(ctx.name) FILTER (WHERE ctx.name IS NOT NULL),
'{}'::text[]
) AS evaluation_tags,
- bucketing_identifier
+ bucketing_identifier,
+ -- Mirror the canonical Django cache writer (products/feature_flags/backend/flags_cache.py,
+ -- Experiment.objects.filter(deleted=False)). Keep this predicate in lockstep with it.
+ EXISTS (
+ SELECT 1 FROM posthog_experiment e
+ WHERE e.feature_flag_id = f.id AND e.deleted = false
+ ) AS has_experiment
FROM posthog_featureflag AS f
JOIN posthog_team AS t ON (f.team_id = t.id)
LEFT JOIN posthog_featureflagevaluationcontext AS ec ON (f.id = ec.feature_flag_id)
@@ -194,9 +200,7 @@ impl FeatureFlagList {
evaluation_runtime: row.evaluation_runtime,
evaluation_tags: row.evaluation_tags,
bucketing_identifier: row.bucketing_identifier,
- // The PG fallback query doesn't compute experiment linkage, so fall back
- // to the shared default (true) for this rare, transient cache-miss path.
- has_experiment: default_has_experiment(),
+ has_experiment: row.has_experiment,
}),
Err(e) => {
// This is highly unlikely to happen, but if it does, we skip the flag.
@@ -314,6 +318,63 @@ mod tests {
assert_eq!(flag.filters.groups[0].properties.as_ref().unwrap().len(), 1);
}
+ #[tokio::test]
+ async fn test_from_pg_computes_has_experiment() {
+ let context = TestContext::new(None).await;
+ let team = context
+ .insert_new_team(None)
+ .await
+ .expect("Failed to insert team");
+
+ let make_row = |key: &str| FeatureFlagRow {
+ team_id: team.id,
+ name: Some(key.to_string()),
+ key: key.to_string(),
+ filters: serde_json::json!({"groups": [{"properties": [], "rollout_percentage": 100}]}),
+ active: true,
+ ..Default::default()
+ };
+
+ let live = context
+ .insert_flag(team.id, Some(make_row("flag_with_live_experiment")))
+ .await
+ .expect("Failed to insert flag");
+ let deleted_only = context
+ .insert_flag(team.id, Some(make_row("flag_with_deleted_experiment")))
+ .await
+ .expect("Failed to insert flag");
+ context
+ .insert_flag(team.id, Some(make_row("flag_without_experiment")))
+ .await
+ .expect("Failed to insert flag");
+
+ context
+ .insert_experiment(live.id, team.id, false)
+ .await
+ .expect("Failed to insert live experiment");
+ // A deleted experiment must not count as linkage.
+ context
+ .insert_experiment(deleted_only.id, team.id, true)
+ .await
+ .expect("Failed to insert deleted experiment");
+
+ let flags = FeatureFlagList::from_pg(context.non_persons_reader.clone(), team.id)
+ .await
+ .expect("Failed to fetch flags from pg");
+
+ let by_key = |key: &str| {
+ flags
+ .iter()
+ .find(|f| f.key == key)
+ .unwrap_or_else(|| panic!("missing flag {key}"))
+ .has_experiment
+ };
+
+ assert!(by_key("flag_with_live_experiment"));
+ assert!(!by_key("flag_with_deleted_experiment"));
+ assert!(!by_key("flag_without_experiment"));
+ }
+
#[tokio::test]
async fn test_fetch_empty_team_from_pg() {
let context = TestContext::new(None).await;
@@ -369,6 +430,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
let flag2 = FeatureFlagRow {
@@ -384,6 +446,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
// Insert multiple flags for the team
diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rs
index 5a282cb31903..87933f724336 100644
--- a/rust/feature-flags/src/flags/flag_matching_utils.rs
+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs
@@ -1660,6 +1660,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context
.insert_flag(team.id, Some(flag_row))
@@ -1776,6 +1777,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context
.insert_flag(team.id, Some(flag_row))
@@ -1897,6 +1899,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
let inactive_flag = FeatureFlagRow {
@@ -1912,6 +1915,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
let deleted_flag = FeatureFlagRow {
@@ -1927,6 +1931,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
let no_continuity_flag = FeatureFlagRow {
@@ -1942,6 +1947,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context
@@ -2034,6 +2040,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context
.insert_flag(team.id, Some(flag_row))
@@ -2116,6 +2123,7 @@ mod tests {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context
.insert_flag(team.id, Some(flag_row))
diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rs
index 39ed2d4863ee..67cfecc8d11c 100644
--- a/rust/feature-flags/src/flags/flag_models.rs
+++ b/rust/feature-flags/src/flags/flag_models.rs
@@ -287,14 +287,14 @@ pub struct FeatureFlag {
/// Defaults to `true` (rather than the usual `#[serde(default)]` bool false) so cache
/// entries written by older Django without the field over-preserve properties instead of
/// stripping them. A spurious `true` only wastes bytes; a spurious `false` would strip
- /// unrecoverable experiment-exposure data. The fallback query paths share this default via
- /// `default_has_experiment()`.
+ /// unrecoverable experiment-exposure data. The panic fallback shares this default via
+ /// `default_has_experiment()`; the PG fallback query computes the real value.
#[serde(default = "default_has_experiment")]
pub has_experiment: bool,
}
/// Default for `FeatureFlag::has_experiment` when experiment linkage is unknowable — an
-/// older-Django cache payload missing the field, or a fallback query path that can't compute
+/// older-Django cache payload missing the field, or the panic fallback that can't compute
/// it. See the field doc for why this is `true` rather than `false`.
pub(crate) fn default_has_experiment() -> bool {
true
@@ -330,6 +330,9 @@ pub struct FeatureFlagRow {
pub evaluation_tags: Option<Vec<String>>,
#[serde(default)]
pub bucketing_identifier: Option<String>,
+ /// Populated by the from_pg fallback query via a correlated EXISTS over posthog_experiment.
+ #[serde(default)]
+ pub has_experiment: bool,
}
/// Request-scoped view of flag definitions plus the per-request filter set.
diff --git a/rust/feature-flags/src/flags/flag_operations.rs b/rust/feature-flags/src/flags/flag_operations.rs
index 1e700b5388ed..7dd15a6979ff 100644
--- a/rust/feature-flags/src/flags/flag_operations.rs
+++ b/rust/feature-flags/src/flags/flag_operations.rs
@@ -355,6 +355,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -456,6 +457,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -595,6 +597,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -673,6 +676,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -768,6 +772,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -850,6 +855,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -943,6 +949,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -1026,6 +1033,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
@@ -1143,6 +1151,7 @@ mod tests {
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}),
)
.await
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index 0c3f11fab467..e59f95e947e6 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -631,6 +631,7 @@ pub async fn insert_flag_for_team_in_pg(
evaluation_runtime: Some("all".to_string()),
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
},
};
@@ -692,6 +693,30 @@ pub async fn insert_evaluation_tags_for_flag_in_pg(
Ok(())
}
+pub async fn insert_experiment_for_flag_in_pg(
+ client: Arc<dyn Client + Send + Sync>,
+ flag_id: i32,
+ team_id: i32,
+ deleted: bool,
+) -> Result<(), Error> {
+ let mut conn = client.get_connection().await?;
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_experiment
+ (name, filters, feature_flag_id, team_id, deleted, archived,
+ only_count_matured_users, created_at, updated_at)
+ VALUES ('test experiment', '{}'::jsonb, $1, $2, $3, false, false, NOW(), NOW())
+ "#,
+ )
+ .bind(flag_id)
+ .bind(team_id)
+ .bind(deleted)
+ .execute(&mut *conn)
+ .await?;
+
+ Ok(())
+}
+
pub async fn insert_person_for_team_in_pg(
client: Arc<dyn Client + Send + Sync>,
team_id: i32,
@@ -1165,6 +1190,16 @@ impl TestContext {
insert_flag_for_team_in_pg(self.non_persons_writer.clone(), team_id, flag).await
}
+ pub async fn insert_experiment(
+ &self,
+ flag_id: i32,
+ team_id: i32,
+ deleted: bool,
+ ) -> Result<(), Error> {
+ insert_experiment_for_flag_in_pg(self.non_persons_writer.clone(), flag_id, team_id, deleted)
+ .await
+ }
+
pub async fn insert_person(
&self,
team_id: i32,
diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
index a2c1c2c7ba4b..67cb17e5cba4 100644
--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs
+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
@@ -62,6 +62,7 @@ fn flag_row(team_id: i32, key: &str, filters: Value) -> FeatureFlagRow {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
}
}
diff --git a/rust/feature-flags/tests/test_experience_continuity.rs b/rust/feature-flags/tests/test_experience_continuity.rs
index 7eb12807220e..7b0638d3e4f0 100644
--- a/rust/feature-flags/tests/test_experience_continuity.rs
+++ b/rust/feature-flags/tests/test_experience_continuity.rs
@@ -38,6 +38,7 @@ async fn test_experience_continuity_matches_python() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
@@ -164,6 +165,7 @@ async fn test_experience_continuity_with_merge() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
@@ -324,6 +326,7 @@ async fn test_anon_distinct_id_from_person_properties() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
@@ -449,6 +452,7 @@ async fn test_top_level_anon_distinct_id_takes_precedence() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
@@ -573,6 +577,7 @@ async fn test_experience_continuity_without_person_uses_anon_distinct_id() -> Re
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
diff --git a/rust/feature-flags/tests/test_skip_writes.rs b/rust/feature-flags/tests/test_skip_writes.rs
index d1d8e6b91bda..0c8b19935bb1 100644
--- a/rust/feature-flags/tests/test_skip_writes.rs
+++ b/rust/feature-flags/tests/test_skip_writes.rs
@@ -35,6 +35,7 @@ async fn test_skip_writes_prevents_hash_key_override_write() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;
@@ -144,6 +145,7 @@ async fn test_skip_writes_still_evaluates_flags_correctly() -> Result<()> {
evaluation_runtime: None,
evaluation_tags: None,
bucketing_identifier: None,
+ has_experiment: false,
};
context.insert_flag(team.id, Some(flag_row)).await?;