: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): ignore stored cookieless sentinels in personhog-replica (#112935)
Phil Haack81bcae3f4c92
diff --git a/rust/personhog-replica/.sqlx/query-3f9ce28fe309e1d448f06edbb11ccf6288d6151ee629163c9631b79bd4dc6602.json b/rust/personhog-replica/.sqlx/query-3f9ce28fe309e1d448f06edbb11ccf6288d6151ee629163c9631b79bd4dc6602.jsonnew file mode 100644index 000000000000..1bc957284467--- /dev/null+++ b/rust/personhog-replica/.sqlx/query-3f9ce28fe309e1d448f06edbb11ccf6288d6151ee629163c9631b79bd4dc6602.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT DISTINCT $1::integer, p.person_id, f.flag_key, $2::text\n FROM posthog_persondistinctid p\n CROSS JOIN UNNEST($4::text[]) AS f(flag_key)\n WHERE p.team_id = $1 AND p.distinct_id = ANY($3) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n AND NOT EXISTS (\n SELECT 1 FROM posthog_featureflaghashkeyoverride o\n WHERE o.team_id = p.team_id AND o.person_id = p.person_id\n AND o.feature_flag_key = f.flag_key AND o.hash_key <> $5\n )\n ORDER BY p.person_id, f.flag_key\n ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE\n SET hash_key = EXCLUDED.hash_key\n WHERE posthog_featureflaghashkeyoverride.hash_key = $5\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Int4",+ "Text",+ "TextArray",+ "TextArray",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "3f9ce28fe309e1d448f06edbb11ccf6288d6151ee629163c9631b79bd4dc6602"+}diff --git a/rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.json b/rust/personhog-replica/.sqlx/query-4e8b4f81cd27015e126b884d8e490991048df0301a0c801292315e1e7304746d.jsonsimilarity index 77%rename from rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.jsonrename to rust/personhog-replica/.sqlx/query-4e8b4f81cd27015e126b884d8e490991048df0301a0c801292315e1e7304746d.jsonindex 96ef95655de5..a73db30d08f0 100644--- a/rust/personhog-replica/.sqlx/query-1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2.json+++ b/rust/personhog-replica/.sqlx/query-4e8b4f81cd27015e126b884d8e490991048df0301a0c801292315e1e7304746d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT ppd.person_id, ppd.distinct_id,\n fhko.feature_flag_key as \"feature_flag_key?\",\n fhko.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid ppd\n LEFT JOIN posthog_featureflaghashkeyoverride fhko\n ON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id\n WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2) AND ppd.is_deleted = false\n ",+ "query": "\n SELECT ppd.person_id, ppd.distinct_id,\n fhko.feature_flag_key as \"feature_flag_key?\",\n fhko.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid ppd\n LEFT JOIN posthog_featureflaghashkeyoverride fhko\n ON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id\n AND fhko.hash_key <> $3\n WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2) AND ppd.is_deleted = false\n ","describe": {"columns": [{@@ -27,7 +27,8 @@"parameters": {"Left": ["Int4",- "TextArray"+ "TextArray",+ "Text"]},"nullable": [@@ -37,5 +38,5 @@false]},- "hash": "1f1bd42fc1a6d1933df4b31d4683aa78a31c395cc6d80499eed52b9a678130b2"+ "hash": "4e8b4f81cd27015e126b884d8e490991048df0301a0c801292315e1e7304746d"}diff --git a/rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.json b/rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.jsondeleted file mode 100644index 10b59685da4f..000000000000--- a/rust/personhog-replica/.sqlx/query-85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09.json+++ /dev/null@@ -1,17 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)\n SELECT $1, p.person_id, f.flag_key, $2\n FROM posthog_persondistinctid p\n CROSS JOIN UNNEST($4::text[]) AS f(flag_key)\n WHERE p.team_id = $1 AND p.distinct_id = ANY($3) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n ON CONFLICT DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Int4",- "Varchar",- "TextArray",- "TextArray"- ]- },- "nullable": []- },- "hash": "85355184c06b84608ab43b73558e9c772bbf6abbbd1af4c260a6eb8d7d528b09"-}diff --git a/rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.json b/rust/personhog-replica/.sqlx/query-91b5e570539a804b17c041822958f36330b2ce1dda96331f7bccca398926b080.jsonsimilarity index 69%rename from rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.jsonrename to rust/personhog-replica/.sqlx/query-91b5e570539a804b17c041822958f36330b2ce1dda96331f7bccca398926b080.jsonindex 1ef200cec894..7b3fee184fe5 100644--- a/rust/personhog-replica/.sqlx/query-aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a.json+++ b/rust/personhog-replica/.sqlx/query-91b5e570539a804b17c041822958f36330b2ce1dda96331f7bccca398926b080.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT DISTINCT p.person_id, p.distinct_id,\n existing.feature_flag_key as \"feature_flag_key?\",\n existing.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid p\n LEFT JOIN posthog_featureflaghashkeyoverride existing\n ON existing.person_id = p.person_id AND existing.team_id = p.team_id\n WHERE p.team_id = $1 AND p.distinct_id = ANY($2) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n ",+ "query": "\n SELECT DISTINCT p.person_id, p.distinct_id,\n existing.feature_flag_key as \"feature_flag_key?\",\n existing.hash_key as \"hash_key?\"\n FROM posthog_persondistinctid p\n LEFT JOIN posthog_featureflaghashkeyoverride existing\n ON existing.person_id = p.person_id AND existing.team_id = p.team_id\n AND existing.hash_key <> $3\n WHERE p.team_id = $1 AND p.distinct_id = ANY($2) AND p.is_deleted = false\n AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)\n ","describe": {"columns": [{@@ -27,7 +27,8 @@"parameters": {"Left": ["Int4",- "TextArray"+ "TextArray",+ "Text"]},"nullable": [@@ -37,5 +38,5 @@false]},- "hash": "aab61726604c6044de1725bf1e375eabb163cccccac82ffbd86d863485fb371a"+ "hash": "91b5e570539a804b17c041822958f36330b2ce1dda96331f7bccca398926b080"}diff --git a/rust/personhog-replica/src/service/mod.rs b/rust/personhog-replica/src/service/mod.rsindex b8d4b64d2962..449ebecbad1f 100644--- a/rust/personhog-replica/src/service/mod.rs+++ b/rust/personhog-replica/src/service/mod.rs@@ -50,6 +50,7 @@ use personhog_proto::personhog::types::v1::{use tonic::{Request, Response, Status};use uuid::Uuid;+use crate::storage::types::COOKIELESS_SENTINEL_VALUE;use crate::storage::{self, FullStorage};const MAX_BATCH_LOOKUP_SIZE: usize = 250;@@ -683,6 +684,12 @@ impl PersonHogReplica for PersonHogReplicaService {) -> Result<Response<UpsertHashKeyOverridesResponse>, Status> {let req = request.into_inner();+ if req.hash_key == COOKIELESS_SENTINEL_VALUE {+ return Err(Status::invalid_argument(format!(+ "hash_key must not be {COOKIELESS_SENTINEL_VALUE}"+ )));+ }+let inserted_count = self.storage.upsert_hash_key_overrides(diff --git a/rust/personhog-replica/src/service/tests/mod.rs b/rust/personhog-replica/src/service/tests/mod.rsindex 601c3f4e3864..ee35f6e3db1c 100644--- a/rust/personhog-replica/src/service/tests/mod.rs+++ b/rust/personhog-replica/src/service/tests/mod.rs@@ -12,7 +12,7 @@ use personhog_proto::personhog::types::v1::{DeletePersonsBatchForTeamRequest, DeletePersonsRequest, DeleteTombstonedPersonsRequest,GetGroupRequest, GetPersonRequest, GetPersonsByDistinctIdsInTeamRequest,InsertCohortMembersRequest, ListCohortMemberIdsRequest, UpdateGroupRequest,- UpdateGroupTypeMappingRequest,+ UpdateGroupTypeMappingRequest, UpsertHashKeyOverridesRequest,};use rstest::rstest;use tonic::Request;@@ -1059,3 +1059,25 @@ async fn test_delete_group_type_mappings_batch_for_team_success() {assert!(result.is_ok());}++// ============================================================+// UpsertHashKeyOverrides tests+// ============================================================++#[tokio::test]+async fn test_upsert_hash_key_overrides_rejects_the_cookieless_sentinel() {+ let service = PersonHogReplicaService::new(Arc::new(mocks::SuccessStorage));++ let status = service+ .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {+ team_id: 1,+ distinct_ids: vec!["user".to_string()],+ hash_key: "$posthog_cookieless".to_string(),+ feature_flag_keys: vec!["flag".to_string()],+ }))+ .await+ .unwrap_err();++ assert_eq!(status.code(), tonic::Code::InvalidArgument);+ assert!(status.message().contains("hash_key"));+}diff --git a/rust/personhog-replica/src/storage/postgres/feature_flag.rs b/rust/personhog-replica/src/storage/postgres/feature_flag.rsindex da6230408476..bd18b6167aa3 100644--- a/rust/personhog-replica/src/storage/postgres/feature_flag.rs+++ b/rust/personhog-replica/src/storage/postgres/feature_flag.rs@@ -8,7 +8,7 @@ use personhog_common::grpc::{current_client_name, current_method_name};use super::{ConsistencyLevel, PostgresStorage, DB_QUERY_DURATION, DB_ROWS_RETURNED};use crate::storage::error::StorageResult;use crate::storage::traits::FeatureFlagStorage;-use crate::storage::types::{HashKeyOverride, HashKeyOverrideContext};+use crate::storage::types::{HashKeyOverride, HashKeyOverrideContext, COOKIELESS_SENTINEL_VALUE};// Kept as an intermediate struct because the rows are aggregated into// HashKeyOverrideContext via HashMap grouping logic. All field types already@@ -21,6 +21,8 @@ struct HashKeyOverrideContextRow {hash_key: Option<String>,}+// The override queries in this impl apply the same sentinel rules as the hash key override SQL+// in `rust/feature-flags/src/flags/flag_matching_utils.rs`. Keep the two in sync.#[async_trait]impl FeatureFlagStorage for PostgresStorage {async fn get_hash_key_override_context(@@ -61,6 +63,8 @@ impl FeatureFlagStorage for PostgresStorage {let pool = self.pool_for_consistency(consistency);let mut conn = PostgresStorage::acquire_timed(pool, pool_label).await?;+ // Every cookieless visitor shares the sentinel, so a stored sentinel would give all of+ // them the same variant.let rows = if check_person_exists {sqlx::query_as!(HashKeyOverrideContextRow,@@ -71,11 +75,13 @@ impl FeatureFlagStorage for PostgresStorage {FROM posthog_persondistinctid pLEFT JOIN posthog_featureflaghashkeyoverride existingON existing.person_id = p.person_id AND existing.team_id = p.team_id+ AND existing.hash_key <> $3WHERE p.team_id = $1 AND p.distinct_id = ANY($2) AND p.is_deleted = falseAND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)"#,team_id as i32,- distinct_ids+ distinct_ids,+ COOKIELESS_SENTINEL_VALUE).fetch_all(&mut *conn).await?@@ -89,10 +95,12 @@ impl FeatureFlagStorage for PostgresStorage {FROM posthog_persondistinctid ppdLEFT JOIN posthog_featureflaghashkeyoverride fhkoON fhko.person_id = ppd.person_id AND fhko.team_id = ppd.team_id+ AND fhko.hash_key <> $3WHERE ppd.team_id = $1 AND ppd.distinct_id = ANY($2) AND ppd.is_deleted = false"#,team_id as i32,- distinct_ids+ distinct_ids,+ COOKIELESS_SENTINEL_VALUE).fetch_all(&mut *conn).await?@@ -168,20 +176,34 @@ impl FeatureFlagStorage for PostgresStorage {let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;+ // DO UPDATE locks each conflicting row even when its WHERE is false, so NOT EXISTS+ // skips the pairs that already hold a real key. The WHERE still keeps a real key that a+ // concurrent write commits after NOT EXISTS reads its snapshot. DO UPDATE also fails+ // when two distinct ids of one person produce the same row twice, so DISTINCT removes+ // the duplicates. ORDER BY makes concurrent upserts lock rows in the same order.let result = sqlx::query!(r#"INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)- SELECT $1, p.person_id, f.flag_key, $2+ SELECT DISTINCT $1::integer, p.person_id, f.flag_key, $2::textFROM posthog_persondistinctid pCROSS JOIN UNNEST($4::text[]) AS f(flag_key)WHERE p.team_id = $1 AND p.distinct_id = ANY($3) AND p.is_deleted = falseAND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)- ON CONFLICT DO NOTHING+ AND NOT EXISTS (+ SELECT 1 FROM posthog_featureflaghashkeyoverride o+ WHERE o.team_id = p.team_id AND o.person_id = p.person_id+ AND o.feature_flag_key = f.flag_key AND o.hash_key <> $5+ )+ ORDER BY p.person_id, f.flag_key+ ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE+ SET hash_key = EXCLUDED.hash_key+ WHERE posthog_featureflaghashkeyoverride.hash_key = $5"#,team_id as i32,hash_key,distinct_ids,- feature_flag_keys+ feature_flag_keys,+ COOKIELESS_SENTINEL_VALUE).execute(&mut *conn).await?;diff --git a/rust/personhog-replica/src/storage/traits/feature_flag.rs b/rust/personhog-replica/src/storage/traits/feature_flag.rsindex d783cded490b..cd738b5c5e4d 100644--- a/rust/personhog-replica/src/storage/traits/feature_flag.rs+++ b/rust/personhog-replica/src/storage/traits/feature_flag.rs@@ -10,7 +10,8 @@ pub trait FeatureFlagStorage: Send + Sync {/// Gets the context needed for hash key override decisions.////// This resolves distinct IDs to person IDs and returns existing hash key- /// override information for each person.+ /// override information for each person. A stored override whose hash key is+ /// the cookieless sentinel counts as no override.////// When `check_person_exists` is true, only returns results for persons that/// exist in the posthog_person table. This uses an EXISTS subquery against@@ -40,7 +41,8 @@ pub trait FeatureFlagStorage: Send + Sync {////// Resolves all `distinct_ids` to person_ids via `posthog_persondistinctid`,/// cross-joins with `feature_flag_keys`, and inserts overrides with the given- /// `hash_key`. Returns the number of inserted records.+ /// `hash_key`, replacing only a stored cookieless sentinel. Returns the number+ /// of rows inserted or replaced.async fn upsert_hash_key_overrides(&self,team_id: i64,diff --git a/rust/personhog-replica/src/storage/types/feature_flag.rs b/rust/personhog-replica/src/storage/types/feature_flag.rsindex ab2f76b0dd55..54253d1f35f2 100644--- a/rust/personhog-replica/src/storage/types/feature_flag.rs+++ b/rust/personhog-replica/src/storage/types/feature_flag.rs@@ -1,3 +1,7 @@+/// Every cookieless visitor shares this hash key, so a stored override with it is no override.+/// Mirrors `COOKIELESS_SENTINEL_VALUE` in `common-cookieless`, which pulls in redis and moka.+pub const COOKIELESS_SENTINEL_VALUE: &str = "$posthog_cookieless";+#[derive(Debug, Clone)]pub struct HashKeyOverride {pub feature_flag_key: String,diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex d09f4851eaf7..48660e9063d7 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -1306,8 +1306,15 @@ async fn test_get_hash_key_override_context_with_overrides() {ctx.cleanup().await.ok();}+#[rstest]+#[case::nothing_stored(None, false)]+#[case::cookieless_sentinel_stored(Some("$posthog_cookieless"), false)]+#[case::cookieless_sentinel_stored_with_person_check(Some("$posthog_cookieless"), true)]#[tokio::test]-async fn test_get_hash_key_override_context_no_overrides() {+async fn test_get_hash_key_override_context_no_overrides(+ #[case] stored_hash_key: Option<&str>,+ #[case] check_person_exists: bool,+) {let ctx = TestContext::new().await;let person = ctx@@ -1315,12 +1322,18 @@ async fn test_get_hash_key_override_context_no_overrides() {.await.expect("Failed to insert person");+ if let Some(stored_hash_key) = stored_hash_key {+ ctx.insert_hash_key_override(person.id, "stored-flag", stored_hash_key)+ .await+ .expect("Failed to insert override");+ }+let result = ctx.storage.get_hash_key_override_context(ctx.team_id,&["user_no_overrides".to_string()],- false,+ check_person_exists,ConsistencyLevel::Eventual,).await@@ -1433,14 +1446,18 @@ async fn test_upsert_hash_key_overrides_multiple_distinct_ids_and_flags() {.insert_person("upsert_multi_user2", None).await.expect("Failed to insert person 2");+ ctx.add_distinct_id_to_person(person1.id, "upsert_multi_user1_alias")+ .await+ .expect("Failed to add distinct id to person 1");- // Two distinct_ids × two flag keys = 4 overrides+ // Two persons × two flag keys = 4 overrides. The alias resolves to person 1 again.let inserted_count = ctx.storage.upsert_hash_key_overrides(ctx.team_id,&["upsert_multi_user1".to_string(),+ "upsert_multi_user1_alias".to_string(),"upsert_multi_user2".to_string(),],&["flag-a".to_string(), "flag-b".to_string()],@@ -1525,38 +1542,40 @@ async fn test_upsert_hash_key_overrides_empty_flag_keys_returns_zero() {ctx.cleanup().await.ok();}+#[rstest]+#[case::keeps_a_real_key("conflict-flag", "first_hash", 0, "first_hash")]+#[case::replaces_the_cookieless_sentinel("conflict-flag", "$posthog_cookieless", 1, "second_hash")]+#[case::writes_past_a_real_key_on_another_flag("other-flag", "first_hash", 1, "second_hash")]#[tokio::test]-async fn test_upsert_hash_key_overrides_on_conflict_do_nothing() {+async fn test_upsert_hash_key_overrides_replaces_only_a_stored_cookieless_sentinel(+ #[case] stored_flag_key: &str,+ #[case] stored_hash_key: &str,+ #[case] expected_count: i64,+ #[case] expected_hash_key: &str,+) {let ctx = TestContext::new().await;- ctx.insert_person("upsert_conflict_user", None)+ let person = ctx+ .insert_person("upsert_conflict_user", None).await.expect("Failed to insert person");-- let distinct_ids = ["upsert_conflict_user".to_string()];- let flag_keys = ["conflict-flag".to_string()];-- // First insert- let first_count = ctx- .storage- .upsert_hash_key_overrides(ctx.team_id, &distinct_ids, &flag_keys, "first_hash")+ ctx.insert_hash_key_override(person.id, stored_flag_key, stored_hash_key).await- .expect("Failed to upsert hash key overrides");-- assert_eq!(first_count, 1);+ .expect("Failed to insert override");- // Second insert with same distinct_id and feature_flag_key should do nothing- // (ON CONFLICT DO NOTHING)- let second_count = ctx+ let written_count = ctx.storage- .upsert_hash_key_overrides(ctx.team_id, &distinct_ids, &flag_keys, "second_hash")+ .upsert_hash_key_overrides(+ ctx.team_id,+ &["upsert_conflict_user".to_string()],+ &["conflict-flag".to_string()],+ "second_hash",+ ).await.expect("Failed to upsert hash key overrides");- // No new rows inserted due to conflict- assert_eq!(second_count, 0);+ assert_eq!(written_count, expected_count);- // Verify the original hash_key is preserved (not updated)let result = ctx.storage.get_hash_key_override_context(@@ -1569,8 +1588,12 @@ async fn test_upsert_hash_key_overrides_on_conflict_do_nothing() {.expect("Failed to get hash key override context");assert_eq!(result.len(), 1);- assert_eq!(result[0].overrides.len(), 1);- assert_eq!(result[0].overrides[0].hash_key, "first_hash");+ let conflict_flag_override = result[0]+ .overrides+ .iter()+ .find(|o| o.feature_flag_key == "conflict-flag")+ .expect("Missing conflict-flag override");+ assert_eq!(conflict_flag_override.hash_key, expected_hash_key);ctx.cleanup().await.ok();}