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.

28.3 KB
Raw Blame
use anyhow::Result;
use reqwest::StatusCode;
use serde_json::{json, Value};

pub mod common;
use crate::common::ServerHandle;
use feature_flags::config::DEFAULT_TEST_CONFIG;
use feature_flags::flags::flag_models::FeatureFlagRow;
use feature_flags::utils::test_utils::TestContext;

#[tokio::test]
async fn test_experience_continuity_matches_python() -> Result<()> {
    // 1. Create a user that evaluates to false
    // 2. Find an ID that evaluates to true
    // 3. Set hash key override via $anon_distinct_id
    // 4. Call WITHOUT $anon_distinct_id - should maintain the override

    // Insert a new team
    let context = TestContext::new(None).await;
    let team = context
        .insert_new_team(None)
        .await
        .expect("Failed to insert team");

    // Create a flag with experience continuity (50% rollout like the real experience-flag)
    let flag_row = FeatureFlagRow {
        id: 100,
        team_id: team.id,
        name: Some("Experience Flag".to_string()),
        key: "experience-flag-test".to_string(),
        filters: json!({
            "groups": [{"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,
    };
    context.insert_flag(team.id, Some(flag_row)).await?;

    // Create a person with false_eval_user (this ID evaluates to false for 50% rollout)
    let user_id = "false_eval_user";
    context
        .insert_person(
            team.id,
            user_id.to_string(),
            Some(json!({"email": "[email protected]", "name": "Test User"})),
        )
        .await?;

    // Start test server
    let config = DEFAULT_TEST_CONFIG.clone();
    let server = ServerHandle::for_config_with_mock_redis(
        config,
        vec![],
        vec![(team.api_token.clone(), team.id)],
    )
    .await;

    // Step 1: Check initial evaluation (should be false)
    let payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
    });

    let res = server
        .send_flags_request(payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(res.status(), StatusCode::OK);
    let json = res.json::<Value>().await?;

    assert_eq!(
        json["flags"]["experience-flag-test"]["enabled"],
        json!(false),
        "false_eval_user should initially evaluate to false"
    );

    // Step 2: Use an ID that evaluates to true
    let anon_id = "true_eval_user";
    let anon_payload = json!({
        "token": team.api_token,
        "distinct_id": anon_id,
    });

    let anon_res = server
        .send_flags_request(anon_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(anon_res.status(), StatusCode::OK);
    let anon_json = anon_res.json::<Value>().await?;

    assert_eq!(
        anon_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "true_eval_user should evaluate to true"
    );

    // Step 3: Set the hash key override by calling with $anon_distinct_id
    let override_payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
        "$anon_distinct_id": anon_id,
    });

    let override_res = server
        .send_flags_request(override_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(override_res.status(), StatusCode::OK);
    let override_json = override_res.json::<Value>().await?;

    assert_eq!(
        override_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "With $anon_distinct_id, should now evaluate to true"
    );

    // Step 4: Call WITHOUT $anon_distinct_id
    let final_payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
        // NO $anon_distinct_id
    });

    let final_res = server
        .send_flags_request(final_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(final_res.status(), StatusCode::OK);
    let final_json = final_res.json::<Value>().await?;

    assert_eq!(
        final_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "WITHOUT $anon_distinct_id, should STILL return true due to existing override (matching Python)"
    );

    Ok(())
}

#[tokio::test]
async fn test_experience_continuity_with_merge() -> Result<()> {
    // Test that merged persons also maintain overrides without $anon_distinct_id

    let context = TestContext::new(None).await;
    let team = context
        .insert_new_team(None)
        .await
        .expect("Failed to insert team");

    // Create flag
    let flag_row = FeatureFlagRow {
        id: 101,
        team_id: team.id,
        name: Some("Merge Test Flag".to_string()),
        key: "merge-test-flag".to_string(),
        filters: json!({
            "groups": [{"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,
    };
    context.insert_flag(team.id, Some(flag_row)).await?;

    // Create initial person with an ID that evaluates to false
    let initial_id = "false_eval_initial";
    let person_id = context
        .insert_person(
            team.id,
            initial_id.to_string(),
            Some(json!({"email": "[email protected]"})),
        )
        .await?;

    // Start server
    let config = DEFAULT_TEST_CONFIG.clone();
    let server = ServerHandle::for_config_with_mock_redis(
        config,
        vec![],
        vec![(team.api_token.clone(), team.id)],
    )
    .await;

    // Step 1: Verify initial_id evaluates to false
    let initial_check = json!({
        "token": team.api_token,
        "distinct_id": initial_id,
    });

    let initial_res = server
        .send_flags_request(initial_check.to_string(), Some("2"), None)
        .await;
    assert_eq!(initial_res.status(), StatusCode::OK);
    let initial_json = initial_res.json::<Value>().await?;

    assert_eq!(
        initial_json["flags"]["merge-test-flag"]["enabled"],
        json!(false),
        "Initial user should evaluate to false"
    );

    // Step 2: Use an anonymous ID that evaluates to true
    let anon_id = "true_eval_anon";
    let anon_check = json!({
        "token": team.api_token,
        "distinct_id": anon_id,
    });

    let anon_res = server
        .send_flags_request(anon_check.to_string(), Some("2"), None)
        .await;
    assert_eq!(anon_res.status(), StatusCode::OK);
    let anon_json = anon_res.json::<Value>().await?;

    assert_eq!(
        anon_json["flags"]["merge-test-flag"]["enabled"],
        json!(true),
        "Anonymous ID should evaluate to true"
    );

    // Step 3: Set override via $anon_distinct_id
    let override_payload = json!({
        "token": team.api_token,
        "distinct_id": initial_id,
        "$anon_distinct_id": anon_id,
    });

    let override_res = server
        .send_flags_request(override_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(override_res.status(), StatusCode::OK);
    let override_json = override_res.json::<Value>().await?;

    assert_eq!(
        override_json["flags"]["merge-test-flag"]["enabled"],
        json!(true),
        "After setting override, should evaluate to true"
    );

    // Step 4: First verify that the merged_id would naturally evaluate to false
    let merged_id = "false_eval_merged_user";

    // Test that this ID naturally evaluates to false (before any association)
    let natural_check = json!({
        "token": team.api_token,
        "distinct_id": merged_id,
    });

    let natural_res = server
        .send_flags_request(natural_check.to_string(), Some("2"), None)
        .await;
    assert_eq!(natural_res.status(), StatusCode::OK);
    let natural_json = natural_res.json::<Value>().await?;

    assert_eq!(
        natural_json["flags"]["merge-test-flag"]["enabled"],
        json!(false),
        "merged_id should naturally evaluate to false before association"
    );

    // Step 5: Simulate a person merge (this would normally happen via $identify event)
    // Use an ID that would naturally evaluate to false to prove the override is working
    let mut conn = context.get_persons_connection().await?;
    sqlx::query(
        "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version)
         VALUES ($1, $2, $3, 0)",
    )
    .bind(team.id)
    .bind(person_id)
    .bind(merged_id)
    .execute(&mut *conn)
    .await?;

    // Step 6: Call with merged ID without $anon_distinct_id
    // This is the key test - the merged ID should inherit the override
    let merged_payload = json!({
        "token": team.api_token,
        "distinct_id": merged_id,
        // NO $anon_distinct_id
    });

    let res = server
        .send_flags_request(merged_payload.to_string(), Some("2"), None)
        .await;

    assert_eq!(res.status(), StatusCode::OK);
    let json = res.json::<Value>().await?;

    assert_eq!(
        json["flags"]["merge-test-flag"]["enabled"],
        json!(true),
        "Merged distinct_id should use existing override without $anon_distinct_id (inherits from the person's existing override)"
    );

    Ok(())
}

#[tokio::test]
async fn test_anon_distinct_id_from_person_properties() -> Result<()> {
    let context = TestContext::new(None).await;
    let team = context
        .insert_new_team(None)
        .await
        .expect("Failed to insert team");

    // Create flag with experience continuity
    let flag_row = FeatureFlagRow {
        id: 102,
        team_id: team.id,
        name: Some("Experience Flag".to_string()),
        key: "experience-flag-test".to_string(),
        filters: json!({
            "groups": [{"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,
    };
    context.insert_flag(team.id, Some(flag_row)).await?;

    // Create person with an ID that evaluates to false
    let user_id = "false_eval_user";
    context
        .insert_person(
            team.id,
            user_id.to_string(),
            Some(json!({"email": "[email protected]"})),
        )
        .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;

    // Step 1: Verify user evaluates to false
    let initial_payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
    });

    let res = server
        .send_flags_request(initial_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(res.status(), StatusCode::OK);
    let json_response = res.json::<Value>().await?;

    assert_eq!(
        json_response["flags"]["experience-flag-test"]["enabled"],
        json!(false),
        "User should initially evaluate to false"
    );

    // Step 2: Verify the anon ID evaluates to true
    let anon_id = "true_eval_user";
    let anon_payload = json!({
        "token": team.api_token,
        "distinct_id": anon_id,
    });

    let anon_res = server
        .send_flags_request(anon_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(anon_res.status(), StatusCode::OK);
    let anon_json = anon_res.json::<Value>().await?;

    assert_eq!(
        anon_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "true_eval_user should evaluate to true"
    );

    // Step 3: Set override using $anon_distinct_id in person_properties
    let override_payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
        "person_properties": {
            "$anon_distinct_id": anon_id,
            "other_prop": "some_value"
        }
    });

    let override_res = server
        .send_flags_request(override_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(override_res.status(), StatusCode::OK);
    let override_json = override_res.json::<Value>().await?;

    assert_eq!(
        override_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "With $anon_distinct_id in person_properties, should evaluate to true"
    );

    // Step 4: Verify override persists without $anon_distinct_id
    let final_payload = json!({
        "token": team.api_token,
        "distinct_id": user_id,
    });

    let final_res = server
        .send_flags_request(final_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(final_res.status(), StatusCode::OK);
    let final_json = final_res.json::<Value>().await?;

    assert_eq!(
        final_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "Override should persist even without $anon_distinct_id"
    );

    Ok(())
}

#[tokio::test]
async fn test_top_level_anon_distinct_id_takes_precedence() -> Result<()> {
    let context = TestContext::new(None).await;
    let team = context
        .insert_new_team(None)
        .await
        .expect("Failed to insert team");

    // Create flag
    let flag_row = FeatureFlagRow {
        id: 103,
        team_id: team.id,
        name: Some("Experience Flag".to_string()),
        key: "experience-flag-test".to_string(),
        filters: json!({
            "groups": [{"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,
    };
    context.insert_flag(team.id, Some(flag_row)).await?;

    // Create person
    let user_id = "precedence_test_user";
    context
        .insert_person(
            team.id,
            user_id.to_string(),
            Some(json!({"email": "[email protected]"})),
        )
        .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;

    // Use two different IDs that evaluate differently
    let true_eval_id = "true_eval_user";
    let false_eval_id = "false_eval_user";

    // Verify the true_eval_id evaluates to true
    let true_check = json!({
        "token": team.api_token,
        "distinct_id": true_eval_id,
    });

    let true_res = server
        .send_flags_request(true_check.to_string(), Some("2"), None)
        .await;
    assert_eq!(true_res.status(), StatusCode::OK);
    let true_json = true_res.json::<Value>().await?;

    assert_eq!(
        true_json["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "true_eval_id should evaluate to true"
    );

    // Verify the false_eval_id evaluates to false
    let false_check = json!({
        "token": team.api_token,
        "distinct_id": false_eval_id,
    });

    let false_res = server
        .send_flags_request(false_check.to_string(), Some("2"), None)
        .await;
    assert_eq!(false_res.status(), StatusCode::OK);
    let false_json = false_res.json::<Value>().await?;

    assert_eq!(
        false_json["flags"]["experience-flag-test"]["enabled"],
        json!(false),
        "false_eval_id should evaluate to false"
    );

    // Test with BOTH top-level and person_properties $anon_distinct_id
    // Top-level should win
    let payload_with_both = json!({
        "token": team.api_token,
        "distinct_id": user_id,
        "$anon_distinct_id": true_eval_id,  // Top level - evaluates to TRUE
        "person_properties": {
            "$anon_distinct_id": false_eval_id,  // In person_properties - evaluates to FALSE
        }
    });

    let res = server
        .send_flags_request(payload_with_both.to_string(), Some("2"), None)
        .await;
    assert_eq!(res.status(), StatusCode::OK);
    let json_response = res.json::<Value>().await?;

    assert_eq!(
        json_response["flags"]["experience-flag-test"]["enabled"],
        json!(true),
        "Top-level $anon_distinct_id should take precedence (evaluates to true)"
    );

    Ok(())
}

#[tokio::test]
async fn test_experience_continuity_without_person_uses_anon_distinct_id() -> Result<()> {
    // This test verifies that when:
    // 1. No person record exists (common during anonymous->identified transition)
    // 2. The SDK sends both distinct_id and $anon_distinct_id
    // 3. The flag is multivariate (has variants)
    // The server should use $anon_distinct_id for variant computation immediately,
    // ensuring the user sees the same variant they saw while anonymous.

    let context = TestContext::new(None).await;
    let team = context
        .insert_new_team(None)
        .await
        .expect("Failed to insert team");

    // Create multivariate flag with experience continuity (50/50 split)
    let flag_row = FeatureFlagRow {
        id: 105,
        team_id: team.id,
        name: Some("No Person EEC Multivariate Test".to_string()),
        key: "no-person-eec-multivariate-test".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,
    };
    context.insert_flag(team.id, Some(flag_row)).await?;

    // IMPORTANT: Do NOT create any person record
    // This simulates the race condition where identify event hasn't been processed yet

    let config = DEFAULT_TEST_CONFIG.clone();
    let server = ServerHandle::for_config_with_mock_redis(
        config,
        vec![],
        vec![(team.api_token.clone(), team.id)],
    )
    .await;

    // Step 1: Get the variant that "anon_user_123" would see
    let anon_payload = json!({
        "token": team.api_token,
        "distinct_id": "anon_user_123",
    });

    let anon_res = server
        .send_flags_request(anon_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(anon_res.status(), StatusCode::OK);
    let anon_json = anon_res.json::<Value>().await?;

    let expected_variant = anon_json["flags"]["no-person-eec-multivariate-test"]["variant"]
        .as_str()
        .expect("Should have a variant");

    // Step 2: Verify a different distinct_id gets a different or same variant (doesn't matter)
    // but record what it naturally evaluates to
    let identified_payload = json!({
        "token": team.api_token,
        "distinct_id": "identified_user_456",
    });

    let identified_res = server
        .send_flags_request(identified_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(identified_res.status(), StatusCode::OK);
    let identified_json = identified_res.json::<Value>().await?;

    let identified_natural_variant = identified_json["flags"]["no-person-eec-multivariate-test"]
        ["variant"]
        .as_str()
        .expect("Should have a variant");

    // Step 3: Now call with identified_user_456 as distinct_id but with $anon_distinct_id
    // pointing to anon_user_123. Without a person record, the server should use
    // anon_user_123 for variant computation (matching what the anon user saw).
    let transition_payload = json!({
        "token": team.api_token,
        "distinct_id": "identified_user_456",
        "$anon_distinct_id": "anon_user_123",
    });

    let transition_res = server
        .send_flags_request(transition_payload.to_string(), Some("2"), None)
        .await;
    assert_eq!(transition_res.status(), StatusCode::OK);
    let transition_json = transition_res.json::<Value>().await?;

    let transition_variant = transition_json["flags"]["no-person-eec-multivariate-test"]["variant"]
        .as_str()
        .expect("Should have a variant");

    // The key assertion: when $anon_distinct_id is provided with no person record,
    // the variant should match what the anon_distinct_id user saw, NOT what the
    // distinct_id would naturally evaluate to.
    assert_eq!(
        transition_variant, expected_variant,
        "With $anon_distinct_id provided but no person record, should use $anon_distinct_id for variant hashing. \
         Expected variant '{expected_variant}' (from anon_user_123), but got '{transition_variant}'. \
         For reference, identified_user_456 naturally evaluates to '{identified_natural_variant}'."
    );

    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(())
}