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): stop using the cookieless sentinel as a hash key (#110316)

Phill2c1850a432a6
diff --git a/nodejs/src/common/persons/person-utils.ts b/nodejs/src/common/persons/person-utils.ts
index 7170614d81e9..9224307dd9a3 100644
--- a/nodejs/src/common/persons/person-utils.ts
+++ b/nodejs/src/common/persons/person-utils.ts
@@ -44,7 +44,17 @@ const BARE_CASE_INSENSITIVE_ILLEGAL_IDS = [
'false',
]
-const BARE_CASE_SENSITIVE_ILLEGAL_IDS = ['[object Object]', 'NaN', 'None', 'none', 'null', '0', 'undefined']
+// '$posthog_cookieless' is the cookieless mode sentinel. Every cookieless visitor shares it.
+const BARE_CASE_SENSITIVE_ILLEGAL_IDS = [
+ '[object Object]',
+ 'NaN',
+ 'None',
+ 'none',
+ 'null',
+ '0',
+ 'undefined',
+ '$posthog_cookieless',
+]
// we have seen illegal ids received but wrapped in double quotes
// to protect ourselves from this we'll add the single- and double-quoted versions of the illegal ids
diff --git a/nodejs/tests/ingestion/person-state-batch.serial.test.ts b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
index 8391feb69dbd..bee06da96043 100644
--- a/nodejs/tests/ingestion/person-state-batch.serial.test.ts
+++ b/nodejs/tests/ingestion/person-state-batch.serial.test.ts
@@ -3025,7 +3025,16 @@ describe('PersonState.processEvent()', () => {
})
describe('illegal aliasing', () => {
- const illegalIds = ['', ' ', 'null', 'undefined', '"undefined"', '[object Object]', '"[object Object]"']
+ const illegalIds = [
+ '',
+ ' ',
+ 'null',
+ 'undefined',
+ '"undefined"',
+ '[object Object]',
+ '"[object Object]"',
+ '$posthog_cookieless',
+ ]
it.each(illegalIds)('stops $identify if current distinct_id is illegal: `%s`', async (illegalId: string) => {
const mergeService = personMergeService({
event: '$identify',
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index fc6ff61462e8..af85a6854856 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -3259,12 +3259,18 @@ mod tests {
/// distinct_id and ignore the stale override, otherwise every distinct_id of the
/// person keeps bucketing on the old key and resolves to the same stale value.
#[rstest::rstest]
- #[case::continuity_off_ignores_stale_override(Some(false), "logged-in-username")]
- #[case::continuity_unset_ignores_stale_override(None, "logged-in-username")]
- #[case::continuity_on_applies_override(Some(true), "stale-anon-id")]
+ #[case::continuity_off_ignores_stale_override(Some(false), None, "logged-in-username")]
+ #[case::continuity_unset_ignores_stale_override(None, None, "logged-in-username")]
+ #[case::continuity_on_applies_override(Some(true), None, "stale-anon-id")]
+ #[case::continuity_on_stored_override_beats_request_override(
+ Some(true),
+ Some("request-anon-id"),
+ "stale-anon-id"
+ )]
#[tokio::test]
async fn test_hashed_identifier_respects_current_continuity_for_stored_override(
#[case] ensure_experience_continuity: Option<bool>,
+ #[case] request_hash_key_override: Option<&str>,
#[case] expected_identifier: &str,
) {
use crate::utils::test_utils::{mock_group_type_cache, TestContext};
@@ -3293,8 +3299,9 @@ mod tests {
..Default::default()
};
+ let request_override = request_hash_key_override.map(str::to_string);
let identifier = matcher
- .hashed_identifier(&flag, None, Some(&overrides), &None)
+ .hashed_identifier(&flag, None, Some(&overrides), &request_override)
.unwrap();
assert_eq!(identifier, expected_identifier);
diff --git a/rust/feature-flags/src/flags/flag_matching_utils.rs b/rust/feature-flags/src/flags/flag_matching_utils.rs
index f6d7dfd70870..310416f6ac68 100644
--- a/rust/feature-flags/src/flags/flag_matching_utils.rs
+++ b/rust/feature-flags/src/flags/flag_matching_utils.rs
@@ -12,6 +12,7 @@ use tokio_retry::{
use crate::database::{
get_connection_with_metrics, get_writer_connection_with_metrics, pool_names, PostgresRouter,
};
+use common_cookieless::COOKIELESS_SENTINEL_VALUE;
use common_database::{PostgresReader, PostgresWriter};
use common_types::{Person, PersonId, TeamId};
use once_cell::sync::Lazy;
@@ -1104,7 +1105,9 @@ async fn fetch_override_rows(
team_id: TeamId,
distinct_id_and_hash_key_override: &[String],
) -> Result<Vec<PgRow>, FlagError> {
- // Get person data and their hash key overrides in one query
+ // Get person data and their hash key overrides in one query.
+ // Every cookieless visitor shares the sentinel, so a stored sentinel would give all of them
+ // the same variant. The join skips those rows and still keeps the person row.
let hash_override_query = r#"
SELECT
ppd.person_id,
@@ -1115,6 +1118,7 @@ async fn fetch_override_rows(
LEFT JOIN posthog_featureflaghashkeyoverride fhko
ON fhko.person_id = ppd.person_id
AND fhko.team_id = ppd.team_id
+ AND fhko.hash_key <> $3
WHERE ppd.team_id = $1
AND ppd.distinct_id = ANY($2)
AND ppd.is_deleted = false
@@ -1123,11 +1127,29 @@ async fn fetch_override_rows(
sqlx::query(hash_override_query)
.bind(team_id)
.bind(distinct_id_and_hash_key_override)
+ .bind(COOKIELESS_SENTINEL_VALUE)
.fetch_all(&mut *conn)
.await
.map_err(FlagError::from)
}
+/// The write check and the write both run this query, so they agree on which overrides exist.
+/// A stored cookieless sentinel does not count as an override, so the bulk insert replaces it
+/// with a real key.
+const PERSONS_WITH_EXISTING_OVERRIDES_QUERY: &str = r#"
+ SELECT DISTINCT
+ p.person_id,
+ existing.feature_flag_key
+ FROM posthog_persondistinctid p
+ LEFT JOIN posthog_featureflaghashkeyoverride existing
+ ON existing.person_id = p.person_id AND existing.team_id = p.team_id
+ AND existing.hash_key <> $3
+ WHERE p.team_id = $1
+ AND p.distinct_id = ANY($2)
+ AND p.is_deleted = false
+ AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)
+"#;
+
/// Asks the primary whether any override exists for these distinct IDs.
async fn primary_has_override(
persons_writer: &PostgresWriter,
@@ -1216,19 +1238,6 @@ async fn try_set_feature_flag_hash_key_overrides(
.await?;
// Query 1: Get all person data - person_ids + existing overrides + validation (person pool)
- let person_data_query = r#"
- SELECT DISTINCT
- p.person_id,
- p.distinct_id,
- existing.feature_flag_key
- FROM posthog_persondistinctid p
- LEFT JOIN posthog_featureflaghashkeyoverride existing
- ON existing.person_id = p.person_id AND existing.team_id = p.team_id
- WHERE p.team_id = $1
- AND p.distinct_id = ANY($2)
- AND p.is_deleted = false
- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)
- "#;
// Query 2: Get all active feature flags with experience continuity (non-person pool)
let flags_query = r#"
@@ -1242,11 +1251,15 @@ async fn try_set_feature_flag_hash_key_overrides(
"#;
// Query 3: Bulk insert hash key overrides (person pool)
+ // A stored sentinel is not a real continuity key, so this replaces it. Any other stored
+ // key is one the person bucketed on, so it stays.
let bulk_insert_query = r#"
INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)
SELECT $1, person_id, flag_key, $2
FROM UNNEST($3::bigint[], $4::text[]) AS t(person_id, flag_key)
- ON CONFLICT DO NOTHING
+ ON CONFLICT (team_id, person_id, feature_flag_key) DO UPDATE
+ SET hash_key = EXCLUDED.hash_key
+ WHERE posthog_featureflaghashkeyoverride.hash_key = $5
"#;
let result: Result<u64, FlagError> = async {
@@ -1266,9 +1279,10 @@ async fn try_set_feature_flag_hash_key_overrides(
let person_query_start = Instant::now();
let person_query_timer =
common_metrics::timing_guard(FLAG_PERSON_QUERY_TIME, &person_query_labels);
- let person_data_rows = sqlx::query(person_data_query)
+ let person_data_rows = sqlx::query(PERSONS_WITH_EXISTING_OVERRIDES_QUERY)
.bind(team_id)
.bind(distinct_ids)
+ .bind(COOKIELESS_SENTINEL_VALUE)
.fetch_all(&mut *transaction)
.await
.map_err(FlagError::from)?;
@@ -1409,6 +1423,7 @@ async fn try_set_feature_flag_hash_key_overrides(
.bind(hash_key_override)
.bind(&person_ids_to_insert)
.bind(&flag_keys_to_insert)
+ .bind(COOKIELESS_SENTINEL_VALUE)
.execute(&mut *transaction)
.await
.map_err(FlagError::from)?;
@@ -1490,18 +1505,6 @@ async fn try_should_write_hash_key_override(
distinct_ids: &[String],
) -> Result<bool, FlagError> {
// Query 1: Get person_ids and existing overrides from person pool in one shot
- let person_data_query = r#"
- SELECT DISTINCT
- p.person_id,
- existing.feature_flag_key
- FROM posthog_persondistinctid p
- LEFT JOIN posthog_featureflaghashkeyoverride existing
- ON existing.person_id = p.person_id AND existing.team_id = p.team_id
- WHERE p.team_id = $1
- AND p.distinct_id = ANY($2)
- AND p.is_deleted = false
- AND EXISTS (SELECT 1 FROM posthog_person WHERE id = p.person_id AND team_id = p.team_id AND is_deleted = false)
- "#;
// Query 2: Get feature flags from non-person pool
let flags_query = r#"
@@ -1570,9 +1573,10 @@ async fn try_should_write_hash_key_override(
];
let person_query_timer =
common_metrics::timing_guard(FLAG_PERSON_QUERY_TIME, &person_query_labels);
- let person_data_rows = sqlx::query(person_data_query)
+ let person_data_rows = sqlx::query(PERSONS_WITH_EXISTING_OVERRIDES_QUERY)
.bind(team_id)
.bind(distinct_ids)
+ .bind(COOKIELESS_SENTINEL_VALUE)
.fetch_all(&mut *persons_conn)
.await
.map_err(|e| {
@@ -2392,13 +2396,14 @@ mod tests {
}
#[rstest]
- #[case(false, false, false)]
- #[case(true, false, false)]
- #[case(true, true, true)]
+ #[case(false, None, false)]
+ #[case(true, None, false)]
+ #[case(true, Some("replica_check_hash_key"), true)]
+ #[case(true, Some(COOKIELESS_SENTINEL_VALUE), false)]
#[tokio::test]
async fn test_primary_has_override_reports_only_a_real_override(
#[case] person_exists: bool,
- #[case] override_set: bool,
+ #[case] stored_hash_key: Option<&str>,
#[case] expected: bool,
) {
let context = TestContext::new(None).await;
@@ -2412,7 +2417,7 @@ mod tests {
.unwrap();
}
- if override_set {
+ if let Some(stored_hash_key) = stored_hash_key {
let flag = mock!(FeatureFlag,
team_id: team.id,
filters: FlagFilters {
@@ -2429,7 +2434,7 @@ mod tests {
&router,
team.id,
vec![distinct_id.clone()],
- "replica_check_hash_key".to_string(),
+ stored_hash_key.to_string(),
)
.await
.unwrap();
diff --git a/rust/feature-flags/src/flags/flag_request.rs b/rust/feature-flags/src/flags/flag_request.rs
index 0faafa11b7e2..e1193a75add1 100644
--- a/rust/feature-flags/src/flags/flag_request.rs
+++ b/rust/feature-flags/src/flags/flag_request.rs
@@ -2,6 +2,7 @@ use std::collections::HashMap;
use bytes::Bytes;
use chrono::{DateTime, Utc};
+use common_cookieless::COOKIELESS_SENTINEL_VALUE;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
@@ -176,11 +177,12 @@ impl FlagRequest {
}
}
+ fn person_property_str(&self, key: &str) -> Option<&str> {
+ self.person_properties.as_ref()?.get(key)?.as_str()
+ }
+
fn extract_person_property_string(&self, key: &str) -> Option<String> {
- self.person_properties
- .as_ref()
- .and_then(|properties| properties.get(key))
- .and_then(Value::as_str)
+ self.person_property_str(key)
.filter(|value| !value.is_empty())
.map(str::to_string)
}
@@ -244,6 +246,32 @@ impl FlagRequest {
.or_else(|| self.extract_person_property_string("$device_id"))
}
+ /// The `$anon_distinct_id` values the request carried, top level first. Backend SDKs set it
+ /// in person_properties instead of at the top level.
+ fn anon_distinct_id_candidates(&self) -> impl Iterator<Item = &str> {
+ self.anon_distinct_id
+ .as_deref()
+ .into_iter()
+ .chain(self.person_property_str("$anon_distinct_id"))
+ }
+
+ /// Extracts the raw `$anon_distinct_id` the request carried. It can differ from the hash key
+ /// the evaluation uses.
+ pub fn extract_anon_distinct_id(&self) -> Option<String> {
+ self.anon_distinct_id_candidates()
+ .next()
+ .map(str::to_string)
+ }
+
+ /// Extracts the experience continuity hash key. The cookieless sentinel is never a hash key,
+ /// because every cookieless visitor shares it. A sentinel at the top level therefore falls
+ /// back to the person property.
+ pub fn extract_hash_key_override(&self) -> Option<String> {
+ self.anon_distinct_id_candidates()
+ .find(|id| *id != COOKIELESS_SENTINEL_VALUE)
+ .map(str::to_string)
+ }
+
/// Checks if feature flags should be disabled for this request.
/// Returns true if disable_flags is explicitly set to true.
pub fn is_flags_disabled(&self) -> bool {
@@ -268,9 +296,78 @@ mod tests {
};
use bytes::Bytes;
use common_cache::NegativeCache;
+ use rstest::rstest;
use serde_json::json;
use serde_json::Value;
+ #[rstest]
+ #[case::top_level_wins(
+ Some("anon123"),
+ Some(json!({"$anon_distinct_id": "anon456"})),
+ Some("anon123"),
+ Some("anon123")
+ )]
+ #[case::falls_back_to_person_properties(
+ None,
+ Some(json!({"$anon_distinct_id": "anon456"})),
+ Some("anon456"),
+ Some("anon456")
+ )]
+ #[case::not_present(None, None, None, None)]
+ #[case::person_properties_without_the_key(
+ None,
+ Some(json!({"other_property": "value"})),
+ None,
+ None
+ )]
+ #[case::non_string_person_property(
+ None,
+ Some(json!({"$anon_distinct_id": 123})),
+ None,
+ None
+ )]
+ #[case::cookieless_sentinel_top_level(
+ Some("$posthog_cookieless"),
+ None,
+ Some("$posthog_cookieless"),
+ None
+ )]
+ #[case::cookieless_sentinel_person_property(
+ None,
+ Some(json!({"$anon_distinct_id": "$posthog_cookieless"})),
+ Some("$posthog_cookieless"),
+ None
+ )]
+ #[case::cookieless_sentinel_top_level_falls_back_to_person_property(
+ Some("$posthog_cookieless"),
+ Some(json!({"$anon_distinct_id": "anon456"})),
+ Some("$posthog_cookieless"),
+ Some("anon456")
+ )]
+ fn test_hash_key_override(
+ #[case] top_level: Option<&str>,
+ #[case] person_properties: Option<Value>,
+ #[case] expected_raw: Option<&str>,
+ #[case] expected_hash_key: Option<&str>,
+ ) {
+ let request = FlagRequest {
+ anon_distinct_id: top_level.map(str::to_string),
+ person_properties: person_properties.map(|v| {
+ serde_json::from_value(v).expect("person_properties case must be a JSON object")
+ }),
+ ..Default::default()
+ };
+
+ assert_eq!(
+ request.extract_anon_distinct_id(),
+ expected_raw.map(str::to_string)
+ );
+ assert_eq!(
+ request.extract_hash_key_override(),
+ expected_hash_key.map(str::to_string)
+ );
+ }
+
#[test]
fn empty_distinct_id_is_accepted() {
let json = json!({
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 992980f132a8..6ff4be534ae5 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -175,15 +175,7 @@ async fn process_request_inner(
.unwrap_or_else(|| "disabled".to_string());
// Populate canonical log with distinct_id, device_id, and anon_distinct_id
- // anon_distinct_id uses same precedence as hash_key_override: top-level > person_properties
- let anon_distinct_id_for_logging = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
+ let anon_distinct_id_for_logging = request.extract_anon_distinct_id();
let device_id = request.extract_device_id();
with_canonical_log(|log| {
log.distinct_id = Some(distinct_id_for_logging.clone());
diff --git a/rust/feature-flags/src/handler/properties.rs b/rust/feature-flags/src/handler/properties.rs
index eb11e5475f74..d74252ea8d89 100644
--- a/rust/feature-flags/src/handler/properties.rs
+++ b/rust/feature-flags/src/handler/properties.rs
@@ -29,23 +29,11 @@ pub fn prepare_overrides(
let group_property_overrides =
get_group_property_overrides(groups.clone(), request.group_properties.clone());
- // Determine hash key with precedence: top-level anon_distinct_id > person_properties.$anon_distinct_id
- // Frontend SDKs automatically include anon_distinct_id at the top level.
- // Backend SDKs manually override the anon_distinct_id in person_properties if needed.
- let hash_key_override = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
-
Ok(RequestPropertyOverrides {
person_properties: person_property_overrides,
group_properties: group_property_overrides,
groups,
- hash_key: hash_key_override,
+ hash_key: request.extract_hash_key_override(),
})
}
@@ -138,119 +126,3 @@ pub fn get_group_property_overrides(
None => existing_overrides,
}
}
-
-#[cfg(test)]
-mod tests {
- use crate::flags::flag_request::FlagRequest;
- use serde_json::json;
-
- #[test]
- fn test_anon_distinct_id_from_top_level() {
- let request = FlagRequest {
- anon_distinct_id: Some("anon123".to_string()),
- person_properties: Some(
- vec![("$anon_distinct_id".to_string(), json!("anon456"))]
- .into_iter()
- .collect(),
- ),
- ..Default::default()
- };
-
- let hash_key = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
-
- assert_eq!(
- hash_key,
- Some("anon123".to_string()),
- "Top-level anon_distinct_id should take precedence"
- );
- }
-
- #[test]
- fn test_anon_distinct_id_from_person_properties() {
- let request = FlagRequest {
- anon_distinct_id: None,
- person_properties: Some(
- vec![("$anon_distinct_id".to_string(), json!("anon456"))]
- .into_iter()
- .collect(),
- ),
- ..Default::default()
- };
-
- let hash_key = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
-
- assert_eq!(
- hash_key,
- Some("anon456".to_string()),
- "Should fallback to person_properties.$anon_distinct_id"
- );
- }
-
- #[test]
- fn test_anon_distinct_id_not_present() {
- let request = FlagRequest {
- anon_distinct_id: None,
- person_properties: Some(
- vec![("other_property".to_string(), json!("value"))]
- .into_iter()
- .collect(),
- ),
- ..Default::default()
- };
-
- let hash_key = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
-
- assert_eq!(
- hash_key, None,
- "Should be None when anon_distinct_id not present anywhere"
- );
- }
-
- #[test]
- fn test_anon_distinct_id_with_non_string_value() {
- let request = FlagRequest {
- anon_distinct_id: None,
- person_properties: Some(
- vec![("$anon_distinct_id".to_string(), json!(123))]
- .into_iter()
- .collect(),
- ),
- ..Default::default()
- };
-
- let hash_key = request.anon_distinct_id.clone().or_else(|| {
- request
- .person_properties
- .as_ref()
- .and_then(|props| props.get("$anon_distinct_id"))
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- });
-
- assert_eq!(
- hash_key, None,
- "Should be None when anon_distinct_id in person_properties is not a string"
- );
- }
-}
diff --git a/rust/feature-flags/tests/test_experience_continuity.rs b/rust/feature-flags/tests/test_experience_continuity.rs
index 7b0638d3e4f0..e6c4f9e11a19 100644
--- a/rust/feature-flags/tests/test_experience_continuity.rs
+++ b/rust/feature-flags/tests/test_experience_continuity.rs
@@ -657,3 +657,227 @@ async fn test_experience_continuity_without_person_uses_anon_distinct_id() -> Re
Ok(())
}
+
+/// Sends a flags request and returns the variant the server assigned for `flag_key`.
+async fn request_variant(server: &ServerHandle, payload: &Value, flag_key: &str) -> Result<String> {
+ let res = server
+ .send_flags_request(payload.to_string(), Some("2"), None)
+ .await;
+ assert_eq!(res.status(), StatusCode::OK);
+ let body = res.json::<Value>().await?;
+ Ok(body["flags"][flag_key]["variant"]
+ .as_str()
+ .expect("flag should resolve to a variant")
+ .to_string())
+}
+
+/// Finds two distinct ids that bucket into different variants of `flag_key`. If the server used
+/// the sentinel as the hash key, every visitor would land on one variant, so a pair that already
+/// lands on different variants is what lets the assertions below fail.
+async fn two_distinct_ids_in_different_variants(
+ server: &ServerHandle,
+ api_token: &str,
+ flag_key: &str,
+) -> Result<(String, String)> {
+ let mut control: Option<String> = None;
+ let mut test: Option<String> = None;
+
+ for n in 0..20 {
+ let distinct_id = format!("cookieless_visitor_{n}");
+ let payload = json!({ "token": api_token, "distinct_id": distinct_id });
+ let slot = match request_variant(server, &payload, flag_key).await?.as_str() {
+ "control" => &mut control,
+ _ => &mut test,
+ };
+ slot.get_or_insert(distinct_id);
+
+ if let (Some(control), Some(test)) = (&control, &test) {
+ return Ok((control.clone(), test.clone()));
+ }
+ }
+
+ panic!("no two distinct ids bucketed into different variants of {flag_key}");
+}
+
+fn multivariate_continuity_flag(id: i32, team_id: i32, key: &str) -> FeatureFlagRow {
+ FeatureFlagRow {
+ id,
+ team_id,
+ name: Some("Cookieless Sentinel Test".to_string()),
+ key: key.to_string(),
+ filters: json!({
+ "groups": [{"rollout_percentage": 100}],
+ "multivariate": {
+ "variants": [
+ {"key": "control", "rollout_percentage": 50},
+ {"key": "test", "rollout_percentage": 50}
+ ]
+ }
+ }),
+ deleted: false,
+ active: true,
+ ensure_experience_continuity: Some(true),
+ version: Some(1),
+ evaluation_runtime: None,
+ evaluation_tags: None,
+ bucketing_identifier: None,
+ has_experiment: false,
+ }
+}
+
+#[tokio::test]
+async fn test_cookieless_sentinel_anon_distinct_id_does_not_share_a_variant() -> Result<()> {
+ // Every cookieless visitor sends the same sentinel as $anon_distinct_id on identify. If the
+ // service takes it as a hash key, all of them bucket together and an A/A test reports a
+ // skewed split. Each visitor must keep the variant their own distinct id gives them, and no
+ // sentinel row may reach the override table.
+
+ let context = TestContext::new(None).await;
+ let team = context
+ .insert_new_team(None)
+ .await
+ .expect("Failed to insert team");
+
+ let flag_key = "cookieless-sentinel-continuity-test";
+ context
+ .insert_flag(
+ team.id,
+ Some(multivariate_continuity_flag(300, team.id, flag_key)),
+ )
+ .await?;
+
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let server = ServerHandle::for_config_with_mock_redis(
+ config,
+ vec![],
+ vec![(team.api_token.clone(), team.id)],
+ )
+ .await;
+
+ let (control_user, test_user) =
+ two_distinct_ids_in_different_variants(&server, &team.api_token, flag_key).await?;
+
+ for (distinct_id, expected_variant) in [(&control_user, "control"), (&test_user, "test")] {
+ // The person must exist, or the write path has nothing to attach an override row to.
+ context
+ .insert_person(team.id, distinct_id.clone(), None)
+ .await?;
+
+ let payload = json!({
+ "token": team.api_token,
+ "distinct_id": distinct_id,
+ "$anon_distinct_id": "$posthog_cookieless",
+ });
+
+ assert_eq!(
+ request_variant(&server, &payload, flag_key).await?,
+ expected_variant,
+ "{distinct_id} should keep its own variant when the anon id is the cookieless sentinel"
+ );
+ }
+
+ let mut conn = context.get_persons_connection().await?;
+ let sentinel_rows: i64 = sqlx::query_scalar(
+ "SELECT COUNT(*) FROM posthog_featureflaghashkeyoverride WHERE team_id = $1 AND hash_key = $2",
+ )
+ .bind(team.id)
+ .bind("$posthog_cookieless")
+ .fetch_one(&mut *conn)
+ .await?;
+
+ assert_eq!(
+ sentinel_rows, 0,
+ "the cookieless sentinel must never be stored as a hash key override"
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_stored_cookieless_sentinel_override_is_replaced() -> Result<()> {
+ // A person can already hold a sentinel override row. The write path matches existing rows
+ // on the flag key alone, so without the sentinel filter it sees an override for every
+ // continuity flag and writes nothing. The person then has no usable continuity key and
+ // moves variant on each login. The real anon id must replace the stored sentinel.
+
+ let context = TestContext::new(None).await;
+ let team = context
+ .insert_new_team(None)
+ .await
+ .expect("Failed to insert team");
+
+ let flag_key = "stored-sentinel-continuity-test";
+ context
+ .insert_flag(
+ team.id,
+ Some(multivariate_continuity_flag(301, team.id, flag_key)),
+ )
+ .await?;
+
+ let config = DEFAULT_TEST_CONFIG.clone();
+ let server = ServerHandle::for_config_with_mock_redis(
+ config,
+ vec![],
+ vec![(team.api_token.clone(), team.id)],
+ )
+ .await;
+
+ let (control_user, test_user) =
+ two_distinct_ids_in_different_variants(&server, &team.api_token, flag_key).await?;
+
+ let person_id = context
+ .insert_person(team.id, control_user.clone(), None)
+ .await?;
+
+ let mut conn = context.get_persons_connection().await?;
+ sqlx::query(
+ "INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key) VALUES ($1, $2, $3, $4)",
+ )
+ .bind(team.id)
+ .bind(person_id)
+ .bind(flag_key)
+ .bind("$posthog_cookieless")
+ .execute(&mut *conn)
+ .await?;
+
+ // The anon id buckets to "test" and the distinct id to "control". This request reads "test"
+ // whether or not the write replaced the sentinel, because the read skips a stored sentinel
+ // and falls back to the request's anon id.
+ let payload = json!({
+ "token": team.api_token,
+ "distinct_id": control_user,
+ "$anon_distinct_id": test_user,
+ });
+
+ assert_eq!(
+ request_variant(&server, &payload, flag_key).await?,
+ "test",
+ "the request's anon id should drive bucketing"
+ );
+
+ // Without an anon id, only the stored row can steer bucketing. A replaced row reads "test",
+ // and a leftover sentinel falls back to the distinct id and reads "control".
+ let follow_up = json!({ "token": team.api_token, "distinct_id": control_user });
+
+ assert_eq!(
+ request_variant(&server, &follow_up, flag_key).await?,
+ "test",
+ "the replaced override should drive bucketing without an anon id"
+ );
+
+ let stored_hash_key: String = sqlx::query_scalar(
+ "SELECT hash_key FROM posthog_featureflaghashkeyoverride WHERE team_id = $1 AND person_id = $2 AND feature_flag_key = $3",
+ )
+ .bind(team.id)
+ .bind(person_id)
+ .bind(flag_key)
+ .fetch_one(&mut *conn)
+ .await?;
+
+ assert_eq!(
+ stored_hash_key, test_user,
+ "the stored cookieless sentinel should have been replaced by the real anon id"
+ );
+
+ Ok(())
+}
diff --git a/rust/personhog-identity/src/lifecycle/validation.rs b/rust/personhog-identity/src/lifecycle/validation.rs
index 35456204f328..e2453f513a69 100644
--- a/rust/personhog-identity/src/lifecycle/validation.rs
+++ b/rust/personhog-identity/src/lifecycle/validation.rs
@@ -46,6 +46,7 @@ const BARE_CASE_INSENSITIVE_ILLEGAL_IDS: &[&str] = &[
"true",
"false",
];
+// '$posthog_cookieless' is the cookieless mode sentinel. Every cookieless visitor shares it.
const BARE_CASE_SENSITIVE_ILLEGAL_IDS: &[&str] = &[
"[object Object]",
"NaN",
@@ -54,6 +55,7 @@ const BARE_CASE_SENSITIVE_ILLEGAL_IDS: &[&str] = &[
"null",
"0",
"undefined",
+ "$posthog_cookieless",
];
fn with_quoted(ids: &[&str]) -> HashSet<String> {
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 9e047836243f..fc0b89033fac 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -3249,7 +3249,12 @@ async fn settled_sources_stay_out_of_the_resolution_query() {
.merge_persons(Request::new(rpc_request(
h.ctx.team_id,
"resq-target",
- &["resq-source", "anonymous", &oversized],
+ &[
+ "resq-source",
+ "anonymous",
+ "$posthog_cookieless",
+ &oversized,
+ ],
Uuid::now_v7(),
)))
.await
@@ -3261,6 +3266,10 @@ async fn settled_sources_stay_out_of_the_resolution_query() {
vec![
("resq-source".to_string(), MergeSourceOutcome::Merged),
("anonymous".to_string(), MergeSourceOutcome::SkippedIllegal),
+ (
+ "$posthog_cookieless".to_string(),
+ MergeSourceOutcome::SkippedIllegal
+ ),
(oversized.clone(), MergeSourceOutcome::SkippedIllegal),
]
);
@@ -3277,7 +3286,9 @@ async fn settled_sources_stay_out_of_the_resolution_query() {
"the live pair still resolves"
);
assert!(
- !resolved.contains(&"anonymous".to_string()) && !resolved.contains(&oversized),
+ !resolved.contains(&"anonymous".to_string())
+ && !resolved.contains(&"$posthog_cookieless".to_string())
+ && !resolved.contains(&oversized),
"settled sources must not reach the resolution query: {resolved:?}"
);