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.

fix(flags): evaluate postgres fallback flags in dependency stages (#109636)

Phil Haack4cf7a234d086
diff --git a/docs/internal/feature-flags/flag-evaluation-engine.md b/docs/internal/feature-flags/flag-evaluation-engine.md
index 50871c0a4592..6e42460f1fbe 100644
--- a/docs/internal/feature-flags/flag-evaluation-engine.md
+++ b/docs/internal/feature-flags/flag-evaluation-engine.md
@@ -437,7 +437,7 @@ Rust deserializes `EvaluationMetadata` and maps pre-grouped stages directly to `
#### Fallback path (PostgreSQL)
-When `evaluation_metadata` is absent (PG fallback, old cache entries), the service builds a DAG using `petgraph`:
+On a hypercache miss or a hypercache infrastructure error (anything other than a JSON or pickle parse error, which fails the request), the service loads flags from Postgres and computes the same metadata with `compute_flag_dependencies_or_single_stage()` in `cache_builder.rs`, which builds a DAG using `petgraph`:
1. Extract dependencies from all flag property filters
2. Build a directed graph (edges from dependent -> dependency)
@@ -445,13 +445,7 @@ When `evaluation_metadata` is absent (PG fallback, old cache entries), the servi
4. Track missing dependencies (flags depending on non-existent flags)
5. Compute topological evaluation stages using Kahn's algorithm
-#### Backwards compatibility
-
-The two paths are fully compatible via `#[serde(default)]` on `evaluation_metadata`:
-
-- **Old Rust + new cache**: `evaluation_metadata` is an unknown field, ignored. Falls back to petgraph.
-- **New Rust + old cache**: `evaluation_metadata` absent → `None` → falls back to petgraph.
-- **New Rust + new cache**: `evaluation_metadata` present → fast pre-computed path.
+If `compute_flag_dependencies()` returns an error, every flag goes in one stage.
### Evaluation stages
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index 3e40ec395270..0815fb820947 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -49,10 +49,10 @@ use crate::{
api::{errors::FlagError, types::FlagsResponse},
database::{get_connection_with_metrics, PostgresRouter},
flags::{
- cache_builder::compute_flag_dependencies,
+ cache_builder::compute_flag_dependencies_or_single_stage,
feature_flag_list::PreparedFlags,
flag_matching::FeatureFlagMatcher,
- flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagList},
+ flag_models::{FeatureFlag, FeatureFlagList},
},
handler::authentication::is_internal_request_inner,
metrics::consts::{
@@ -524,15 +524,8 @@ async fn handle_batch_flag_evaluation(
.map(|f| f.id)
.collect();
- // Real dependency stages (like the hypercache path) rather than the PG fallback's
- // single stage, so flag-dependency conditions on the target flag evaluate correctly.
- let evaluation_metadata = compute_flag_dependencies(&flags_vec).unwrap_or_else(|e| {
- warn!(
- team_id = request.team_id,
- "Batch eval falling back to single-stage flag metadata: {e}"
- );
- EvaluationMetadata::single_stage(&flags_vec)
- });
+ let evaluation_metadata =
+ compute_flag_dependencies_or_single_stage(request.team_id, &flags_vec);
let flag_list = FeatureFlagList {
flags: PreparedFlags::seal(flags_vec),
diff --git a/rust/feature-flags/src/flags/cache_builder.rs b/rust/feature-flags/src/flags/cache_builder.rs
index 151f4776ac7d..c72e820c0a73 100644
--- a/rust/feature-flags/src/flags/cache_builder.rs
+++ b/rust/feature-flags/src/flags/cache_builder.rs
@@ -189,6 +189,22 @@ pub fn extract_cohort_ids_from_flag_filters(flags: &[FeatureFlag]) -> HashSet<Co
.collect()
}
+/// Computes evaluation metadata for flags read straight from Postgres. On a graph error, it
+/// places every flag in one stage so that the flags still evaluate.
+///
+/// `compute_flag_dependencies` returns no error for flag input, because `remove_all_cycles`
+/// removes every cycle before the stage computation runs. The fallback guards against a later
+/// change to the graph code.
+pub(crate) fn compute_flag_dependencies_or_single_stage(
+ team_id: TeamId,
+ flags: &[FeatureFlag],
+) -> EvaluationMetadata {
+ compute_flag_dependencies(flags).unwrap_or_else(|e| {
+ tracing::warn!(team_id, "Falling back to single-stage flag metadata: {e}");
+ EvaluationMetadata::single_stage(flags)
+ })
+}
+
/// Compute flag dependency metadata via the shared `DependencyGraph` framework.
///
/// Produces output identical to Python's `_compute_flag_dependencies()`:
diff --git a/rust/feature-flags/src/flags/feature_flag_list.rs b/rust/feature-flags/src/flags/feature_flag_list.rs
index fe273dae5f40..73db38d9959f 100644
--- a/rust/feature-flags/src/flags/feature_flag_list.rs
+++ b/rust/feature-flags/src/flags/feature_flag_list.rs
@@ -117,16 +117,24 @@ impl FeatureFlagList {
);
let evaluation_metadata = wrapper.evaluation_metadata;
- if evaluation_metadata.dependency_stages.is_empty() && !wrapper.flags.is_empty() {
- tracing::error!(
- "evaluation_metadata.dependency_stages is empty but {} flags present for team {}",
- wrapper.flags.len(),
- team_id
+ // A team whose every flag is in or depends on a dependency cycle has no stage. Its
+ // metadata lists every flag in `flags_with_missing_deps`.
+ let flag_without_stage = if evaluation_metadata.dependency_stages.is_empty() {
+ wrapper.flags.iter().find(|flag| {
+ !evaluation_metadata
+ .flags_with_missing_deps
+ .contains(&flag.id)
+ })
+ } else {
+ None
+ };
+ if let Some(flag) = flag_without_stage {
+ let message = format!(
+ "evaluation_metadata.dependency_stages is empty but flag {} for team {team_id} is not in flags_with_missing_deps",
+ flag.id
);
- return Err(FlagError::flag_data_parsing(format!(
- "evaluation_metadata.dependency_stages is empty but {} flags present for team {team_id}",
- wrapper.flags.len()
- )));
+ tracing::error!("{message}");
+ return Err(FlagError::flag_data_parsing(message));
}
Ok((wrapper.flags, evaluation_metadata, wrapper.cohorts))
@@ -1224,21 +1232,33 @@ mod tests {
assert!(cohorts.is_none());
}
- #[test]
- fn test_from_wrapper_empty_stages_with_flags_is_error() {
- let wrapper: HypercacheFlagsWrapper = serde_json::from_value(json!({
+ fn wrapper_with_empty_stages(
+ flags_with_missing_deps: serde_json::Value,
+ ) -> HypercacheFlagsWrapper {
+ serde_json::from_value(json!({
"flags": [
{"id": 10, "key": "a", "team_id": 1, "active": true, "deleted": false, "filters": {"groups": []}},
{"id": 20, "key": "b", "team_id": 1, "active": true, "deleted": false, "filters": {"groups": []}}
],
"evaluation_metadata": {
"dependency_stages": [],
- "flags_with_missing_deps": [],
+ "flags_with_missing_deps": flags_with_missing_deps,
"transitive_deps": {}
}
}))
- .unwrap();
- let result = FeatureFlagList::from_wrapper(Some(wrapper), 1);
+ .unwrap()
+ }
+
+ #[rstest::rstest]
+ #[case::no_flag_has_missing_deps(json!([]))]
+ #[case::one_flag_unaccounted(json!([10]))]
+ fn test_from_wrapper_empty_stages_with_unaccounted_flags_is_error(
+ #[case] flags_with_missing_deps: serde_json::Value,
+ ) {
+ let result = FeatureFlagList::from_wrapper(
+ Some(wrapper_with_empty_stages(flags_with_missing_deps)),
+ 1,
+ );
assert!(matches!(
result,
Err(FlagError::InternalError {
@@ -1248,6 +1268,14 @@ mod tests {
));
}
+ #[test]
+ fn test_from_wrapper_accepts_empty_stages_when_every_flag_has_missing_deps() {
+ let (flags, _, _) =
+ FeatureFlagList::from_wrapper(Some(wrapper_with_empty_stages(json!([10, 20]))), 1)
+ .expect("metadata listing every flag as missing a dependency should parse");
+ assert_eq!(flags.len(), 2);
+ }
+
#[test]
fn test_single_stage_places_all_flag_ids_in_one_stage() {
let flags: Vec<FeatureFlag> = serde_json::from_value(json!([
diff --git a/rust/feature-flags/src/flags/flag_definitions_cache.rs b/rust/feature-flags/src/flags/flag_definitions_cache.rs
index 1ed3a34f2518..61cf7391c8fa 100644
--- a/rust/feature-flags/src/flags/flag_definitions_cache.rs
+++ b/rust/feature-flags/src/flags/flag_definitions_cache.rs
@@ -65,9 +65,9 @@ impl LoadOutcome {
///
/// PG-source data (`CacheSource::Fallback`) is never inserted: when the etag
/// GET succeeds but the payload load falls through to PG, caching would seed
-/// the entry with single-stage `EvaluationMetadata` for the rest of the TTL
-/// window even though Django's full transitive-dep payload is still indexed
-/// under the same etag.
+/// the entry with PG data, which carries no preloaded cohorts, for the rest of
+/// the TTL window even though Django's full payload is still indexed under the
+/// same etag.
///
/// Concurrent first-misses don't coalesce: `try_get_with` requires `E: Clone`
/// and `FlagError` carries non-`Clone` payloads. Each task compiles its own
@@ -539,8 +539,8 @@ mod tests {
/// When the etag GET succeeds but the loader returns `Fallback` (e.g.
/// payload evicted before the etag key), the value must not land in
- /// the cache under the still-fresh etag — otherwise single-stage PG
- /// data would be served for the rest of the TTL window.
+ /// the cache under the still-fresh etag. Otherwise the service serves PG
+ /// data without preloaded cohorts for the rest of the TTL window.
#[tokio::test]
async fn test_pg_fallback_with_etag_present_does_not_cache() {
let cache = FlagDefinitionsCache::new(None, None);
diff --git a/rust/feature-flags/src/flags/flag_models.rs b/rust/feature-flags/src/flags/flag_models.rs
index 4bf783f2e6d5..22493bfe15b4 100644
--- a/rust/feature-flags/src/flags/flag_models.rs
+++ b/rust/feature-flags/src/flags/flag_models.rs
@@ -84,7 +84,7 @@ pub struct EvaluationMetadata {
impl EvaluationMetadata {
/// Builds metadata that places all flags in a single evaluation stage
- /// with no dependency ordering. Used by the PG fallback path.
+ /// with no dependency ordering. Used when `compute_flag_dependencies` returns an error.
pub fn single_stage(flags: &[FeatureFlag]) -> Self {
Self {
dependency_stages: vec![flags.iter().map(|f| f.id).collect()],
@@ -98,8 +98,8 @@ impl EvaluationMetadata {
/// `{"flags": [...], "evaluation_metadata": {...}, "cohorts": [...] | null}`.
///
/// `evaluation_metadata` is always present in cache entries (written by Django).
-/// The PG fallback path constructs this struct with `EvaluationMetadata::single_stage()`,
-/// which places all flags in one evaluation stage with empty transitive deps.
+/// The PG fallback path computes it from the loaded flags with
+/// `compute_flag_dependencies_or_single_stage()`.
///
/// HYPERCACHE CONTRACT: These fields must match the top-level keys returned by
/// `_get_feature_flags_for_service()` in products/feature_flags/backend/flags_cache.py.
diff --git a/rust/feature-flags/src/flags/flag_service.rs b/rust/feature-flags/src/flags/flag_service.rs
index c48c8ca1bd40..fd49e632004c 100644
--- a/rust/feature-flags/src/flags/flag_service.rs
+++ b/rust/feature-flags/src/flags/flag_service.rs
@@ -180,7 +180,7 @@ impl FlagService {
/// Fetches flags from the hypercache (Redis → S3), falling back to PostgreSQL
/// on cache miss or infra errors. Parse errors (`Json`/`Pickle`) hard-fail with
- /// a tombstone rather than serving degraded single-stage PG data.
+ /// a tombstone rather than silently serving PG data.
///
/// On the hot path the in-memory `FlagDefinitionsCache` is keyed on the etag
/// Django writes alongside the payload (`enable_etag=True`), so an in-memory
@@ -236,8 +236,7 @@ impl FlagService {
/// invoke it lazily inside `get_or_load`. Returns `None` for the
/// `__missing__` sentinel (team has no flags), `Some(wrapper)` otherwise.
/// `Json`/`Pickle` parse errors hard-fail with a tombstone — we never want
- /// to silently degrade to PG (which lacks dependency metadata) on data
- /// corruption.
+ /// to silently degrade to PG on data corruption.
async fn fetch_wrapper_or_pg(
&self,
team_id: TeamId,
@@ -281,14 +280,15 @@ impl FlagService {
1,
);
- // PG has no dependency metadata, so all flags go in a single stage.
let flags = crate::flags::cache_builder::load_supported_flags(
self.pg_client.clone(),
team_id,
)
.await?;
let evaluation_metadata =
- crate::flags::flag_models::EvaluationMetadata::single_stage(&flags);
+ crate::flags::cache_builder::compute_flag_dependencies_or_single_stage(
+ team_id, &flags,
+ );
let wrapper = HypercacheFlagsWrapper {
flags,
cohorts: None,
@@ -311,8 +311,8 @@ mod tests {
feature_flag_list::PreparedFlags,
flag_definitions_cache::FlagDefinitionsCache,
flag_models::{
- EvaluationMetadata, FeatureFlag, FeatureFlagList, FlagFilters, FlagPropertyGroup,
- HypercacheFlagsWrapper,
+ EvaluationMetadata, FeatureFlag, FeatureFlagList, FeatureFlagRow, FlagFilters,
+ FlagPropertyGroup, HypercacheFlagsWrapper,
},
test_helpers::{hypercache_test_key, update_flags_in_hypercache},
},
@@ -760,6 +760,31 @@ mod tests {
.insert_new_team(None)
.await
.expect("Failed to insert team");
+ let dependency = context
+ .insert_flag(team.id, None)
+ .await
+ .expect("Failed to insert flag");
+ let dependent = context
+ .insert_flag(
+ team.id,
+ Some(crate::mock!(FeatureFlagRow,
+ team_id: team.id,
+ key: "dependent_flag".to_string(),
+ filters: json!({
+ "groups": [{
+ "properties": [{
+ "key": dependency.id.to_string(),
+ "type": "flag",
+ "value": true,
+ "operator": "flag_evaluates_to",
+ }],
+ "rollout_percentage": 100,
+ }],
+ }),
+ )),
+ )
+ .await
+ .expect("Failed to insert dependent flag");
// Don't populate hypercache - should fall back to PG
@@ -773,14 +798,18 @@ mod tests {
false,
);
- // Should fall back to PostgreSQL and succeed (returns empty list for new team)
- let result = flag_service.get_flags_from_cache_or_pg(team.id).await;
- assert!(result.is_ok());
- let flag_result = result.unwrap();
+ let flag_result = flag_service
+ .get_flags_from_cache_or_pg(team.id)
+ .await
+ .expect("PG fallback should succeed");
assert!(matches!(
flag_result.cache_source,
common_hypercache::CacheSource::Fallback
));
+ assert_eq!(
+ flag_result.prepared.evaluation_metadata.dependency_stages,
+ vec![vec![dependency.id], vec![dependent.id]]
+ );
}
#[tokio::test]
@@ -941,7 +970,7 @@ mod tests {
}
/// Corrupt Redis payload must hard-fail under `flag_data_parsing_error` rather
- /// than silently fall back to PG (which would serve single-stage data).
+ /// than silently fall back to PG.
#[tokio::test]
async fn test_get_flags_hard_fails_on_hypercache_parse_error() {
use common_redis::MockRedisClient;
diff --git a/rust/feature-flags/src/utils/graph_utils.rs b/rust/feature-flags/src/utils/graph_utils.rs
index 1b9ecd7e6a5f..dc2e8a41d8cd 100644
--- a/rust/feature-flags/src/utils/graph_utils.rs
+++ b/rust/feature-flags/src/utils/graph_utils.rs
@@ -593,9 +593,8 @@ impl PrecomputedDependencyGraph {
let id_to_flag: HashMap<i32, &FeatureFlag> = flags.iter().map(|f| (f.id, f)).collect();
// When flag_keys is specified, compute the set of needed flag IDs upfront so we
- // only clone flags that will actually be evaluated. On the PG fallback path,
- // single_stage() populates per-flag empty dep sets so independent-flag filtering
- // still works. If transitive_deps is truly empty, we can't filter at all.
+ // only clone flags that will actually be evaluated. If transitive_deps is truly empty,
+ // we can't filter at all.
let needed_ids: Option<HashSet<i32>> = if evaluation_metadata.transitive_deps.is_empty() {
None
} else {
diff --git a/rust/feature-flags/src/utils/test_graph_utils.rs b/rust/feature-flags/src/utils/test_graph_utils.rs
index 572b7e592716..e8a00379b62c 100644
--- a/rust/feature-flags/src/utils/test_graph_utils.rs
+++ b/rust/feature-flags/src/utils/test_graph_utils.rs
@@ -1751,8 +1751,9 @@ mod precomputed_dependency_graph_tests {
}
#[test]
- fn test_build_with_flag_keys_filters_independent_flags_on_pg_fallback() {
- // Simulates PG fallback: single_stage metadata has per-flag empty transitive_deps.
+ fn test_build_with_flag_keys_filters_independent_flags_on_single_stage_metadata() {
+ // single_stage metadata, used when compute_flag_dependencies() fails, has per-flag
+ // empty transitive_deps.
// flag_keys filtering should work for independent flags since each flag maps to
// an empty dep set, allowing unrelated flags to be skipped.
let flags = vec![