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): tolerate numeric flag dependency keys (#71802)

posthog[bot]09130e65b621
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index da858a7f5b5a..05ac01a30c16 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1355,8 +1355,18 @@ class FeatureFlagSerializer(
raise serializers.ValidationError(
"Filters are not valid (person-aggregated conditions can only use person, cohort, and flag properties)"
)
- if prop.type == "flag" and prop_dict.get("operator") != "flag_evaluates_to":
- raise serializers.ValidationError("Flag properties must use the 'flag_evaluates_to' operator")
+ if prop.type == "flag":
+ if prop_dict.get("operator") != "flag_evaluates_to":
+ raise serializers.ValidationError(
+ "Flag properties must use the 'flag_evaluates_to' operator"
+ )
+ # Flag dependency keys are flag IDs. The Rust flags service declares
+ # PropertyFilter.key as a string and serde won't coerce a JSON number,
+ # so a numeric key fails deserialization of the entire team's cached
+ # flag payload. Persist it as a string so it round-trips cleanly.
+ dependency_key = prop_dict.get("key")
+ if dependency_key is not None:
+ prop_dict["key"] = str(dependency_key)
else:
# Group-aggregated condition: only allow group properties matching the
# condition's group type
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index c710ade94b75..64b9c14736fa 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -420,6 +420,42 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ def test_flag_dependency_numeric_key_is_coerced_to_string(self) -> None:
+ # A numeric dependency key persisted as a raw JSON number fails deserialization
+ # in the Rust flags service (key is typed as String), taking down flag evaluation
+ # for the whole project. Ensure it's stored as a string regardless of input type.
+ base_flag = FeatureFlag.objects.create(
+ team=self.team,
+ created_by=self.user,
+ key="base-flag",
+ filters={"groups": [{"rollout_percentage": 100, "properties": []}]},
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags",
+ {
+ "name": "Dependent flag",
+ "key": "dependent-flag",
+ "filters": {
+ "groups": [
+ {
+ "rollout_percentage": 100,
+ "properties": [
+ {
+ "key": base_flag.id, # numeric, as stored by some migrations
+ "type": "flag",
+ "value": "true",
+ "operator": "flag_evaluates_to",
+ }
+ ],
+ }
+ ]
+ },
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ stored_key = response.json()["filters"]["groups"][0]["properties"][0]["key"]
+ self.assertEqual(stored_key, str(base_flag.id))
+
@parameterized.expand(
[
("in",),
diff --git a/rust/feature-flags/src/properties/property_models.rs b/rust/feature-flags/src/properties/property_models.rs
index eee53e2b2e50..43c0c4d29c5f 100644
--- a/rust/feature-flags/src/properties/property_models.rs
+++ b/rust/feature-flags/src/properties/property_models.rs
@@ -73,8 +73,35 @@ impl std::fmt::Debug for CompiledRegex {
}
}
+/// Deserializes `PropertyFilter.key` from either a JSON string or a JSON number.
+///
+/// Flag-dependency keys are flag IDs, and the API has persisted them as raw JSON
+/// numbers in some cases (e.g. a flag migration that stored dependency IDs as
+/// integers). serde will not coerce a number into a `String`, so without this a
+/// single numeric key fails deserialization of the whole team's cached flag
+/// payload — taking down flag evaluation for the entire project rather than just
+/// the malformed flag. Accept both forms and normalize to a string; the evaluator
+/// parses it back to an id at match time (`get_feature_flag_id`).
+fn deserialize_key<'de, D>(deserializer: D) -> Result<String, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum StringOrNumber {
+ String(String),
+ Number(serde_json::Number),
+ }
+
+ Ok(match StringOrNumber::deserialize(deserializer)? {
+ StringOrNumber::String(s) => s,
+ StringOrNumber::Number(n) => n.to_string(),
+ })
+}
+
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct PropertyFilter {
+ #[serde(deserialize_with = "deserialize_key")]
pub key: String,
// NB: if a property filter is of type is_set or is_not_set, the value isn't used, and if it's a filter made by the API, the value is None.
pub value: Option<serde_json::Value>,
@@ -118,3 +145,38 @@ mod mock_impls {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn deserializes_numeric_key_as_string() {
+ // A flag dependency persisted with a numeric `key` (e.g. after a migration
+ // that stored dependency IDs as integers) must not fail deserialization —
+ // otherwise one bad flag takes down the whole team's cached payload.
+ let filter: PropertyFilter = serde_json::from_value(serde_json::json!({
+ "key": 226357,
+ "value": true,
+ "type": "flag",
+ "operator": "flag_evaluates_to",
+ }))
+ .expect("numeric key should deserialize as a string");
+
+ assert_eq!(filter.key, "226357");
+ assert_eq!(filter.get_feature_flag_id(), Some(226357));
+ }
+
+ #[test]
+ fn deserializes_string_key() {
+ let filter: PropertyFilter = serde_json::from_value(serde_json::json!({
+ "key": "email",
+ "value": "[email protected]",
+ "type": "person",
+ "operator": "exact",
+ }))
+ .expect("string key should deserialize");
+
+ assert_eq!(filter.key, "email");
+ }
+}