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.

68.1 KB
Raw Blame
mod common;

use common::{TestContext, TestPerson};
use personhog_proto::personhog::replica::v1::person_hog_replica_server::PersonHogReplica;
use personhog_proto::personhog::types::v1::{
    CheckCohortMembershipRequest, ConsistencyLevel, CountGroupTypeMappingsRequest,
    DeleteHashKeyOverridesByTeamsRequest, DeletePersonsBatchForTeamRequest, DeletePersonsMode,
    DeletePersonsRequest, DeleteTombstonedPersonsRequest, DeleteTombstonedPersonsResponse,
    DistinctIdWrite, DistinctIdWriteAction, DistinctIdWriteOutcome,
    EnsurePersonVersionFloorsRequest, GetDistinctIdRowsRequest, GetDistinctIdsForPersonRequest,
    GetDistinctIdsForPersonsRequest, GetGroupRequest, GetGroupTypeMappingsByProjectIdRequest,
    GetGroupTypeMappingsByProjectIdsRequest, GetGroupTypeMappingsByTeamIdRequest,
    GetGroupTypeMappingsByTeamIdsRequest, GetGroupsBatchRequest, GetGroupsRequest,
    GetHashKeyOverrideContextRequest, GetPersonByDistinctIdRequest, GetPersonByUuidRequest,
    GetPersonRequest, GetPersonsByDistinctIdsInTeamRequest, GetPersonsByDistinctIdsRequest,
    GetPersonsByUuidsRequest, GetPersonsRequest, GroupIdentifier, GroupKey,
    ListPersonsForTeamRequest, PersonVersionFloor, PersonVersionFloorResult, RaiseOutcome,
    RaisePersonVersionFloorsRequest, ReadOptions, RestoreOutcome, RestorePersonsRequest,
    RestoredDistinctId, RestoredPerson, SetPersonDistinctIdVersionFloorRequest,
    SetPersonVersionFloorRequest, SplitPersonRequest, TeamDistinctId,
    UpsertHashKeyOverridesRequest, VersionBoundedPerson, VersionFloorOutcome,
    WriteDistinctIdsRequest,
};
use personhog_replica::service::PersonHogReplicaService;
use rstest::rstest;
use tonic::Request;
use uuid::Uuid;

/// Test context that wraps TestContext and adds a service instance.
pub struct ServiceTestContext {
    ctx: TestContext,
    pub service: PersonHogReplicaService,
}

impl std::ops::Deref for ServiceTestContext {
    type Target = TestContext;
    fn deref(&self) -> &Self::Target {
        &self.ctx
    }
}

impl ServiceTestContext {
    pub async fn new() -> Self {
        let ctx = TestContext::new().await;
        let service = PersonHogReplicaService::new(ctx.storage.clone());
        Self { ctx, service }
    }

    pub async fn cleanup(&self) -> Result<(), sqlx::Error> {
        self.ctx.cleanup().await
    }
}

// ============================================================
// Person lookup tests
// ============================================================

#[tokio::test]
async fn test_get_person_returns_person_when_found() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("[email protected]", None).await.unwrap();

    let response = ctx
        .service
        .get_person(Request::new(GetPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let proto_person = response
        .into_inner()
        .person
        .expect("Person should be present");
    assert_eq!(proto_person.id, person.id);
    assert_eq!(proto_person.uuid, person.uuid.to_string());
    assert_eq!(proto_person.team_id, ctx.team_id);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_person_returns_none_when_not_found() {
    let ctx = ServiceTestContext::new().await;

    let response = ctx
        .service
        .get_person(Request::new(GetPersonRequest {
            team_id: ctx.team_id,
            person_id: 999999999,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    assert!(response.into_inner().person.is_none());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_person_by_uuid_returns_person() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("[email protected]", None)
        .await
        .unwrap();

    let response = ctx
        .service
        .get_person_by_uuid(Request::new(GetPersonByUuidRequest {
            team_id: ctx.team_id,
            uuid: person.uuid.to_string(),
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let proto_person = response
        .into_inner()
        .person
        .expect("Person should be present");
    assert_eq!(proto_person.id, person.id);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_person_by_uuid_invalid_uuid_returns_error() {
    let ctx = ServiceTestContext::new().await;

    let result = ctx
        .service
        .get_person_by_uuid(Request::new(GetPersonByUuidRequest {
            team_id: ctx.team_id,
            uuid: "not-a-valid-uuid".to_string(),
            read_options: None,
        }))
        .await;

    assert!(result.is_err());
    let status = result.unwrap_err();
    assert_eq!(status.code(), tonic::Code::InvalidArgument);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_persons_returns_found_and_missing() {
    let ctx = ServiceTestContext::new().await;
    let person1 = ctx.insert_person("[email protected]", None).await.unwrap();
    let person2 = ctx.insert_person("[email protected]", None).await.unwrap();
    let missing_id = 999999999i64;

    let response = ctx
        .service
        .get_persons(Request::new(GetPersonsRequest {
            team_id: ctx.team_id,
            person_ids: vec![person1.id, person2.id, missing_id],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let inner = response.into_inner();
    assert_eq!(inner.persons.len(), 2);
    assert_eq!(inner.missing_ids, vec![missing_id]);

    ctx.cleanup().await.ok();
}

// ============================================================
// Distinct ID lookup tests
// ============================================================

#[tokio::test]
async fn test_get_person_by_distinct_id_returns_person() {
    let ctx = ServiceTestContext::new().await;
    let distinct_id = "unique_distinct_id_123";
    let person = ctx.insert_person(distinct_id, None).await.unwrap();

    let response = ctx
        .service
        .get_person_by_distinct_id(Request::new(GetPersonByDistinctIdRequest {
            team_id: ctx.team_id,
            distinct_id: distinct_id.to_string(),
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let proto_person = response
        .into_inner()
        .person
        .expect("Person should be present");
    assert_eq!(proto_person.id, person.id);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_persons_by_distinct_ids_in_team() {
    let ctx = ServiceTestContext::new().await;
    let person1 = ctx.insert_person("did_1", None).await.unwrap();
    let person2 = ctx.insert_person("did_2", None).await.unwrap();

    let response = ctx
        .service
        .get_persons_by_distinct_ids_in_team(Request::new(GetPersonsByDistinctIdsInTeamRequest {
            team_id: ctx.team_id,
            distinct_ids: vec![
                "did_1".to_string(),
                "did_2".to_string(),
                "did_missing".to_string(),
            ],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 3);

    let found_ids: Vec<i64> = results
        .iter()
        .filter_map(|r| r.person.as_ref().map(|p| p.id))
        .collect();
    assert!(found_ids.contains(&person1.id));
    assert!(found_ids.contains(&person2.id));

    let missing = results
        .iter()
        .find(|r| r.distinct_id == "did_missing")
        .unwrap();
    assert!(missing.person.is_none());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_persons_by_distinct_ids_cross_team() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("cross_team_did", None).await.unwrap();

    let response = ctx
        .service
        .get_persons_by_distinct_ids(Request::new(GetPersonsByDistinctIdsRequest {
            team_distinct_ids: vec![
                TeamDistinctId {
                    team_id: ctx.team_id,
                    distinct_id: "cross_team_did".to_string(),
                },
                TeamDistinctId {
                    team_id: ctx.team_id,
                    distinct_id: "nonexistent".to_string(),
                },
            ],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 2);

    let found = results
        .iter()
        .find(|r| r.key.as_ref().map(|k| k.distinct_id.as_str()) == Some("cross_team_did"))
        .unwrap();
    assert_eq!(found.person.as_ref().unwrap().id, person.id);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_distinct_ids_for_person() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("primary_did", None).await.unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit: None,
            cursor_id: None,
        }))
        .await
        .expect("RPC failed");

    let distinct_ids = response.into_inner().distinct_ids;
    assert_eq!(distinct_ids.len(), 1);
    assert_eq!(distinct_ids[0].distinct_id, "primary_did");

    ctx.cleanup().await.ok();
}

#[rstest]
#[case(Some(2), 2)]
#[case(Some(0), 3)]
#[tokio::test]
async fn test_get_distinct_ids_for_person_with_limit(
    #[case] limit: Option<i64>,
    #[case] expected_count: usize,
) {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("did_1", None).await.unwrap();
    ctx.add_distinct_id_to_person(person.id, "did_2")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "did_3")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit,
            cursor_id: None,
        }))
        .await
        .expect("RPC failed");
    assert_eq!(response.into_inner().distinct_ids.len(), expected_count);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_distinct_ids_for_person_cursor_pagination() {
    let ctx = ServiceTestContext::new().await;
    // Mix of anonymous-format UUIDs and identified strings. The anonymous-
    // deprioritizing sort would reorder these differently than ORDER BY id ASC.
    let person = ctx
        .insert_person("0190f8e1-1234-7abc-89de-f0123456789a", None)
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "[email protected]")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "another_identified")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "01234567-abcd-efab-cdef-0123456789ab")
        .await
        .unwrap();

    let resp1 = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit: Some(2),
            cursor_id: Some(0),
        }))
        .await
        .expect("page 1 failed");
    let page1 = resp1.into_inner();
    assert_eq!(page1.distinct_ids.len(), 2);
    assert!(
        page1.next_cursor_id.is_some(),
        "page was full, next_cursor_id should be present"
    );

    let cursor1 = page1.next_cursor_id.unwrap();
    let resp2 = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit: Some(2),
            cursor_id: Some(cursor1),
        }))
        .await
        .expect("page 2 failed");
    let page2 = resp2.into_inner();
    assert_eq!(page2.distinct_ids.len(), 2);
    assert!(page2.next_cursor_id.is_some());

    let cursor2 = page2.next_cursor_id.unwrap();
    let resp3 = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit: Some(2),
            cursor_id: Some(cursor2),
        }))
        .await
        .expect("page 3 failed");
    let page3 = resp3.into_inner();
    assert_eq!(page3.distinct_ids.len(), 1);
    assert!(
        page3.next_cursor_id.is_none(),
        "last page should have no cursor"
    );

    let mut all_dids: Vec<String> = page1
        .distinct_ids
        .iter()
        .chain(page2.distinct_ids.iter())
        .chain(page3.distinct_ids.iter())
        .map(|d| d.distinct_id.clone())
        .collect();
    all_dids.sort();
    let mut expected = vec![
        "0190f8e1-1234-7abc-89de-f0123456789a",
        "01234567-abcd-efab-cdef-0123456789ab",
        "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
        "another_identified",
        "[email protected]",
    ];
    expected.sort();
    assert_eq!(all_dids, expected);

    for page in [&page1.distinct_ids, &page2.distinct_ids] {
        for pair in page.windows(2) {
            assert!(
                pair[0].id.unwrap() < pair[1].id.unwrap(),
                "rows within a page should be in ascending id order"
            );
        }
    }

    ctx.cleanup().await.ok();
}

// ============================================================
// Group tests
// ============================================================

#[tokio::test]
async fn test_get_group_returns_group_when_found() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group(0, "company_abc", None).await.unwrap();

    let response = ctx
        .service
        .get_group(Request::new(GetGroupRequest {
            team_id: ctx.team_id,
            group_type_index: 0,
            group_key: "company_abc".to_string(),
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let group = response
        .into_inner()
        .group
        .expect("Group should be present");
    assert_eq!(group.group_key, "company_abc");
    assert_eq!(group.group_type_index, 0);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_group_returns_none_when_not_found() {
    let ctx = ServiceTestContext::new().await;

    let response = ctx
        .service
        .get_group(Request::new(GetGroupRequest {
            team_id: ctx.team_id,
            group_type_index: 0,
            group_key: "nonexistent".to_string(),
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    assert!(response.into_inner().group.is_none());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_groups_returns_found_and_missing() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group(0, "group_a", None).await.unwrap();
    ctx.insert_group(1, "group_b", None).await.unwrap();

    let response = ctx
        .service
        .get_groups(Request::new(GetGroupsRequest {
            team_id: ctx.team_id,
            group_identifiers: vec![
                GroupIdentifier {
                    group_type_index: 0,
                    group_key: "group_a".to_string(),
                },
                GroupIdentifier {
                    group_type_index: 1,
                    group_key: "group_b".to_string(),
                },
                GroupIdentifier {
                    group_type_index: 2,
                    group_key: "missing".to_string(),
                },
            ],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let inner = response.into_inner();
    assert_eq!(inner.groups.len(), 2);
    assert_eq!(inner.missing_groups.len(), 1);
    assert_eq!(inner.missing_groups[0].group_key, "missing");

    ctx.cleanup().await.ok();
}

// ============================================================
// Group type mapping tests
// ============================================================

#[tokio::test]
async fn test_get_group_type_mappings_by_team_id() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group_type_mapping("organization", 0)
        .await
        .unwrap();
    ctx.insert_group_type_mapping("project", 1).await.unwrap();

    let response = ctx
        .service
        .get_group_type_mappings_by_team_id(Request::new(GetGroupTypeMappingsByTeamIdRequest {
            team_id: ctx.team_id,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let mappings = response.into_inner().mappings;
    assert_eq!(mappings.len(), 2);

    let group_types: Vec<&str> = mappings.iter().map(|m| m.group_type.as_str()).collect();
    assert!(group_types.contains(&"organization"));
    assert!(group_types.contains(&"project"));

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::no_mappings(&[], None)]
#[case::two_mappings(&[("organization", 0), ("project", 1)], Some(2))]
#[tokio::test]
async fn test_count_group_type_mappings(
    #[case] mappings: &[(&str, i32)],
    #[case] expected_count: Option<i64>,
) {
    let ctx = ServiceTestContext::new().await;

    for (group_type, index) in mappings {
        ctx.insert_group_type_mapping(group_type, *index)
            .await
            .unwrap();
    }

    let response = ctx
        .service
        .count_group_type_mappings(Request::new(CountGroupTypeMappingsRequest {
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let counts = response.into_inner().counts;
    let entry = counts.iter().find(|c| c.team_id == ctx.team_id);
    match expected_count {
        Some(count) => assert_eq!(entry.unwrap().count, count),
        None => assert!(entry.is_none()),
    }

    ctx.cleanup().await.ok();
}

// ============================================================
// Cohort membership tests
// ============================================================

#[tokio::test]
async fn test_check_cohort_membership() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("cohort_user", None).await.unwrap();

    let cohort_member = 1001i64;
    let cohort_not_member = 1002i64;
    ctx.add_person_to_cohort(person.id, cohort_member)
        .await
        .unwrap();

    let response = ctx
        .service
        .check_cohort_membership(Request::new(CheckCohortMembershipRequest {
            person_id: person.id,
            cohort_ids: vec![cohort_member, cohort_not_member],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let memberships = response.into_inner().memberships;
    assert_eq!(memberships.len(), 2);

    let member = memberships
        .iter()
        .find(|m| m.cohort_id == cohort_member)
        .unwrap();
    let not_member = memberships
        .iter()
        .find(|m| m.cohort_id == cohort_not_member)
        .unwrap();

    assert!(member.is_member);
    assert!(!not_member.is_member);

    ctx.cleanup().await.ok();
}

// ============================================================
// Proto conversion tests
// ============================================================

#[tokio::test]
async fn test_person_properties_are_serialized_correctly() {
    let ctx = ServiceTestContext::new().await;
    let props = serde_json::json!({
        "email": "[email protected]",
        "plan": "enterprise",
        "nested": {"key": "value"}
    });
    let person = ctx
        .insert_person("props_user", Some(props.clone()))
        .await
        .unwrap();

    let response = ctx
        .service
        .get_person(Request::new(GetPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let proto_person = response.into_inner().person.unwrap();
    let deserialized: serde_json::Value =
        serde_json::from_slice(&proto_person.properties).expect("Properties should be valid JSON");

    assert_eq!(deserialized["email"], "[email protected]");
    assert_eq!(deserialized["plan"], "enterprise");
    assert_eq!(deserialized["nested"]["key"], "value");

    ctx.cleanup().await.ok();
}

// ============================================================
// Additional person lookup tests
// ============================================================

#[tokio::test]
async fn test_get_persons_by_uuids() {
    let ctx = ServiceTestContext::new().await;
    let person1 = ctx.insert_person("[email protected]", None).await.unwrap();
    let person2 = ctx.insert_person("[email protected]", None).await.unwrap();
    let nonexistent_uuid = uuid::Uuid::now_v7().to_string();

    let response = ctx
        .service
        .get_persons_by_uuids(Request::new(GetPersonsByUuidsRequest {
            team_id: ctx.team_id,
            uuids: vec![
                person1.uuid.to_string(),
                person2.uuid.to_string(),
                nonexistent_uuid,
            ],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let inner = response.into_inner();
    assert_eq!(inner.persons.len(), 2);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_distinct_ids_for_persons() {
    let ctx = ServiceTestContext::new().await;
    let person1 = ctx.insert_person("person1_did", None).await.unwrap();
    let person2 = ctx.insert_person("person2_did", None).await.unwrap();

    // Add an extra distinct ID to person1
    ctx.add_distinct_id_to_person(person1.id, "person1_did_extra")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
            team_id: ctx.team_id,
            person_ids: vec![person1.id, person2.id],
            read_options: None,
            limit_per_person: None,
        }))
        .await
        .expect("RPC failed");

    let person_distinct_ids = response.into_inner().person_distinct_ids;
    assert_eq!(person_distinct_ids.len(), 2);

    let person1_entry = person_distinct_ids
        .iter()
        .find(|p| p.person_id == person1.id)
        .expect("Person1 should be present");
    assert_eq!(person1_entry.distinct_ids.len(), 2);

    let person2_entry = person_distinct_ids
        .iter()
        .find(|p| p.person_id == person2.id)
        .expect("Person2 should be present");
    assert_eq!(person2_entry.distinct_ids.len(), 1);

    ctx.cleanup().await.ok();
}

#[rstest]
#[case(Some(1), 1, 1)]
#[case(Some(0), 3, 2)]
#[tokio::test]
async fn test_get_distinct_ids_for_persons_with_limit(
    #[case] limit_per_person: Option<i64>,
    #[case] expected_p1: usize,
    #[case] expected_p2: usize,
) {
    let ctx = ServiceTestContext::new().await;
    let person1 = ctx.insert_person("p1_did_1", None).await.unwrap();
    let person2 = ctx.insert_person("p2_did_1", None).await.unwrap();

    ctx.add_distinct_id_to_person(person1.id, "p1_did_2")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person1.id, "p1_did_3")
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person2.id, "p2_did_2")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
            team_id: ctx.team_id,
            person_ids: vec![person1.id, person2.id],
            read_options: None,
            limit_per_person,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().person_distinct_ids;
    let p1 = results.iter().find(|p| p.person_id == person1.id).unwrap();
    let p2 = results.iter().find(|p| p.person_id == person2.id).unwrap();
    assert_eq!(p1.distinct_ids.len(), expected_p1);
    assert_eq!(p2.distinct_ids.len(), expected_p2);

    ctx.cleanup().await.ok();
}

// The anonymous-shaped id is inserted first, so insertion order alone would return it;
// the limited queries must order identified ids first so they survive the LIMIT.
#[tokio::test]
async fn test_get_distinct_ids_for_person_limit_keeps_identified() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("0190f8e1-1234-7abc-89de-f0123456789a", None)
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "[email protected]")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_person(Request::new(GetDistinctIdsForPersonRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            read_options: None,
            limit: Some(1),
            cursor_id: None,
        }))
        .await
        .expect("RPC failed");

    let distinct_ids = response.into_inner().distinct_ids;
    assert_eq!(distinct_ids.len(), 1);
    assert_eq!(distinct_ids[0].distinct_id, "[email protected]");

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_distinct_ids_for_persons_limit_keeps_identified() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("0190f8e1-1234-7abc-89de-f0123456789a", None)
        .await
        .unwrap();
    ctx.add_distinct_id_to_person(person.id, "[email protected]")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_distinct_ids_for_persons(Request::new(GetDistinctIdsForPersonsRequest {
            team_id: ctx.team_id,
            person_ids: vec![person.id],
            read_options: None,
            limit_per_person: Some(1),
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().person_distinct_ids;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].distinct_ids.len(), 1);
    assert_eq!(results[0].distinct_ids[0].distinct_id, "[email protected]");

    ctx.cleanup().await.ok();
}

// ============================================================
// Additional group tests
// ============================================================

#[tokio::test]
async fn test_get_groups_batch() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group(0, "company_x", None).await.unwrap();
    ctx.insert_group(1, "org_y", None).await.unwrap();

    let response = ctx
        .service
        .get_groups_batch(Request::new(GetGroupsBatchRequest {
            keys: vec![
                GroupKey {
                    team_id: ctx.team_id,
                    group_type_index: 0,
                    group_key: "company_x".to_string(),
                },
                GroupKey {
                    team_id: ctx.team_id,
                    group_type_index: 1,
                    group_key: "org_y".to_string(),
                },
                GroupKey {
                    team_id: ctx.team_id,
                    group_type_index: 2,
                    group_key: "missing".to_string(),
                },
            ],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 3);

    let found_count = results.iter().filter(|r| r.group.is_some()).count();
    assert_eq!(found_count, 2);

    let missing = results
        .iter()
        .find(|r| r.key.as_ref().map(|k| k.group_key.as_str()) == Some("missing"))
        .unwrap();
    assert!(missing.group.is_none());

    ctx.cleanup().await.ok();
}

// ============================================================
// Additional group type mapping tests
// ============================================================

#[tokio::test]
async fn test_get_group_type_mappings_by_team_ids() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group_type_mapping("company", 0).await.unwrap();
    ctx.insert_group_type_mapping("project", 1).await.unwrap();

    let response = ctx
        .service
        .get_group_type_mappings_by_team_ids(Request::new(GetGroupTypeMappingsByTeamIdsRequest {
            team_ids: vec![ctx.team_id],
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].key, ctx.team_id);
    assert_eq!(results[0].mappings.len(), 2);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_group_type_mappings_by_project_id() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group_type_mapping("workspace", 0).await.unwrap();

    let response = ctx
        .service
        .get_group_type_mappings_by_project_id(Request::new(
            GetGroupTypeMappingsByProjectIdRequest {
                project_id: ctx.team_id, // insert_group_type_mapping uses team_id as project_id
                read_options: None,
            },
        ))
        .await
        .expect("RPC failed");

    let mappings = response.into_inner().mappings;
    assert_eq!(mappings.len(), 1);
    assert_eq!(mappings[0].group_type, "workspace");

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_group_type_mappings_by_project_ids() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_group_type_mapping("team", 0).await.unwrap();
    ctx.insert_group_type_mapping("department", 1)
        .await
        .unwrap();

    let response = ctx
        .service
        .get_group_type_mappings_by_project_ids(Request::new(
            GetGroupTypeMappingsByProjectIdsRequest {
                project_ids: vec![ctx.team_id],
                read_options: None,
            },
        ))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].key, ctx.team_id);
    assert_eq!(results[0].mappings.len(), 2);

    ctx.cleanup().await.ok();
}

// ============================================================
// Feature flag hash key override context tests
// ============================================================

#[tokio::test]
async fn test_get_hash_key_override_context_with_overrides() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("hash_override_user", None).await.unwrap();

    ctx.insert_hash_key_override(person.id, "beta-feature", "custom_hash_1")
        .await
        .unwrap();
    ctx.insert_hash_key_override(person.id, "new-ui", "custom_hash_2")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["hash_override_user".to_string(), "nonexistent".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 1);

    let person_result = &results[0];
    assert_eq!(person_result.person_id, person.id);
    assert_eq!(person_result.distinct_id, "hash_override_user");
    assert_eq!(person_result.overrides.len(), 2);
    assert_eq!(person_result.existing_feature_flag_keys.len(), 2);

    let override_keys: Vec<&str> = person_result
        .overrides
        .iter()
        .map(|o| o.feature_flag_key.as_str())
        .collect();
    assert!(override_keys.contains(&"beta-feature"));
    assert!(override_keys.contains(&"new-ui"));

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_hash_key_override_context_no_overrides() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("user_without_overrides", None)
        .await
        .unwrap();

    let response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["user_without_overrides".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].person_id, person.id);
    assert!(results[0].overrides.is_empty());
    assert!(results[0].existing_feature_flag_keys.is_empty());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_hash_key_override_context_with_check_person_exists() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("existing_person_user", None)
        .await
        .unwrap();

    ctx.insert_hash_key_override(person.id, "feature-a", "hash_a")
        .await
        .unwrap();

    let response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["existing_person_user".to_string()],
            check_person_exists: true,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = response.into_inner().results;
    assert_eq!(results.len(), 1);

    let person_result = &results[0];
    assert_eq!(person_result.person_id, person.id);
    assert_eq!(person_result.existing_feature_flag_keys.len(), 1);
    assert!(person_result
        .existing_feature_flag_keys
        .contains(&"feature-a".to_string()));

    ctx.cleanup().await.ok();
}

// ============================================================
// Upsert hash key overrides tests
// ============================================================

#[tokio::test]
async fn test_upsert_hash_key_overrides_single_override() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_person("upsert_user_1", None).await.unwrap();

    let response = ctx
        .service
        .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_user_1".to_string()],
            hash_key: "my_hash_key".to_string(),
            feature_flag_keys: vec!["test-flag".to_string()],
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().inserted_count, 1);

    // Verify the override was created by reading it back
    let context_response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_user_1".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = context_response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].overrides.len(), 1);
    assert_eq!(results[0].overrides[0].feature_flag_key, "test-flag");
    assert_eq!(results[0].overrides[0].hash_key, "my_hash_key");

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_upsert_hash_key_overrides_multiple_flags_same_hash_key() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_person("upsert_user_2", None).await.unwrap();

    let response = ctx
        .service
        .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_user_2".to_string()],
            hash_key: "shared_hash".to_string(),
            feature_flag_keys: vec![
                "flag-a".to_string(),
                "flag-b".to_string(),
                "flag-c".to_string(),
            ],
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().inserted_count, 3);

    // Verify all overrides share the same hash_key
    let context_response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_user_2".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = context_response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].overrides.len(), 3);

    for override_entry in &results[0].overrides {
        assert_eq!(override_entry.hash_key, "shared_hash");
    }

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_upsert_hash_key_overrides_empty_returns_zero() {
    let ctx = ServiceTestContext::new().await;

    let response = ctx
        .service
        .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {
            team_id: ctx.team_id,
            distinct_ids: vec![],
            hash_key: "unused".to_string(),
            feature_flag_keys: vec!["some-flag".to_string()],
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().inserted_count, 0);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_upsert_hash_key_overrides_on_conflict_do_nothing() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx
        .insert_person("upsert_conflict_user", None)
        .await
        .unwrap();

    // Insert initial override
    ctx.insert_hash_key_override(person.id, "existing-flag", "original_hash")
        .await
        .unwrap();

    // Try to upsert with a different hash_key - should be ignored due to ON CONFLICT DO NOTHING
    let response = ctx
        .service
        .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_conflict_user".to_string()],
            hash_key: "different_hash".to_string(),
            feature_flag_keys: vec!["existing-flag".to_string()],
        }))
        .await
        .expect("RPC failed");

    // No rows inserted due to conflict
    assert_eq!(response.into_inner().inserted_count, 0);

    // Verify the original hash_key is preserved
    let context_response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["upsert_conflict_user".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = context_response.into_inner().results;
    assert_eq!(results[0].overrides.len(), 1);
    assert_eq!(results[0].overrides[0].hash_key, "original_hash");

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_upsert_hash_key_overrides_multiple_distinct_ids() {
    let ctx = ServiceTestContext::new().await;
    ctx.insert_person("multi_person_1", None).await.unwrap();
    ctx.insert_person("multi_person_2", None).await.unwrap();

    let response = ctx
        .service
        .upsert_hash_key_overrides(Request::new(UpsertHashKeyOverridesRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["multi_person_1".to_string(), "multi_person_2".to_string()],
            hash_key: "common_hash".to_string(),
            feature_flag_keys: vec!["shared-flag".to_string()],
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().inserted_count, 2);

    // Verify both persons have the override
    let context_response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["multi_person_1".to_string(), "multi_person_2".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = context_response.into_inner().results;
    assert_eq!(results.len(), 2);

    for result in &results {
        assert_eq!(result.overrides.len(), 1);
        assert_eq!(result.overrides[0].feature_flag_key, "shared-flag");
        assert_eq!(result.overrides[0].hash_key, "common_hash");
    }

    ctx.cleanup().await.ok();
}

// ============================================================
// Delete hash key overrides by teams tests
// ============================================================

#[tokio::test]
async fn test_delete_hash_key_overrides_by_teams_single_team() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("delete_svc_user", None).await.unwrap();

    // Insert overrides
    ctx.insert_hash_key_override(person.id, "flag-to-delete", "hash_val")
        .await
        .unwrap();

    let response = ctx
        .service
        .delete_hash_key_overrides_by_teams(Request::new(DeleteHashKeyOverridesByTeamsRequest {
            team_ids: vec![ctx.team_id],
            batch_size: 1000,
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().deleted_count, 1);

    // Verify deletion
    let context_response = ctx
        .service
        .get_hash_key_override_context(Request::new(GetHashKeyOverrideContextRequest {
            team_id: ctx.team_id,
            distinct_ids: vec!["delete_svc_user".to_string()],
            check_person_exists: false,
            read_options: None,
        }))
        .await
        .expect("RPC failed");

    let results = context_response.into_inner().results;
    assert_eq!(results.len(), 1);
    assert!(results[0].overrides.is_empty());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_delete_hash_key_overrides_by_teams_empty_returns_zero() {
    let ctx = ServiceTestContext::new().await;

    let response = ctx
        .service
        .delete_hash_key_overrides_by_teams(Request::new(DeleteHashKeyOverridesByTeamsRequest {
            team_ids: vec![],
            batch_size: 1000,
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().deleted_count, 0);

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::zero(0)]
#[case::negative(-1)]
#[case::exceeds_max(50001)]
#[tokio::test]
async fn test_delete_hash_key_overrides_by_teams_invalid_batch_size(#[case] batch_size: i64) {
    let ctx = ServiceTestContext::new().await;

    let result = ctx
        .service
        .delete_hash_key_overrides_by_teams(Request::new(DeleteHashKeyOverridesByTeamsRequest {
            team_ids: vec![ctx.team_id],
            batch_size,
        }))
        .await;

    let status = result.unwrap_err();
    assert_eq!(status.code(), tonic::Code::InvalidArgument);
    assert!(status.message().contains("batch_size"));

    ctx.cleanup().await.ok();
}

// ============================================================
// Delete tombstoned persons tests
// ============================================================

#[rstest]
#[case::server_default(0, 10)]
#[case::caller_budget(5, 3)]
#[tokio::test]
async fn test_delete_tombstoned_persons_reports_each_outcome(
    #[case] max_rows: i64,
    #[case] expected_trimmed: i64,
) {
    // The test storage clamps max_rows to 12. The gone and blocked persons take 2 rows of the
    // budget; the 20-row person is trimmed with what is left and comes back pending.
    let ctx = ServiceTestContext::new().await;
    let gone = ctx.insert_person("svc_tomb_gone", None).await.unwrap();
    ctx.tombstone_person(gone.id, None).await.unwrap();
    let live = ctx.insert_person("svc_tomb_live", None).await.unwrap();
    let blocked = ctx.insert_person("svc_tomb_blocked", None).await.unwrap();
    ctx.tombstone_person(blocked.id, Some("svc_tomb_blocked"))
        .await
        .unwrap();
    let big = ctx.insert_person("svc_tomb_big", None).await.unwrap();
    for i in 0..19 {
        ctx.add_distinct_id_to_person(big.id, &format!("svc_tomb_big_{i}"))
            .await
            .unwrap();
    }
    ctx.tombstone_person(big.id, None).await.unwrap();

    let response = ctx
        .service
        .delete_tombstoned_persons(Request::new(DeleteTombstonedPersonsRequest {
            team_id: ctx.team_id,
            person_uuids: vec![
                gone.uuid.to_string(),
                live.uuid.to_string(),
                blocked.uuid.to_string(),
                big.uuid.to_string(),
                Uuid::now_v7().to_string(),
            ],
            max_rows,
            bounded_persons: vec![],
        }))
        .await
        .expect("RPC failed")
        .into_inner();

    assert_eq!(response.deleted_count, 1);
    assert_eq!(response.skipped_live_count, 1);
    assert!(!response.version_guard_applied);
    assert_eq!(response.skipped_version_count, 0);
    assert_eq!(
        response.blocked_person_uuids,
        vec![blocked.uuid.to_string()]
    );
    assert_eq!(response.pending_person_uuids, vec![big.uuid.to_string()]);
    assert_eq!(response.rows_deleted, 1 + expected_trimmed);
    assert!(!ctx.person_row_exists(gone.id).await.unwrap());
    assert!(ctx.person_row_exists(live.id).await.unwrap());
    assert!(ctx.person_row_exists(blocked.id).await.unwrap());
    assert!(ctx.person_row_exists(big.id).await.unwrap());
    assert_eq!(
        ctx.distinct_id_row_count(big.id).await.unwrap(),
        20 - expected_trimmed
    );

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_delete_tombstoned_persons_applies_version_bounds() {
    // Every person is tombstoned once (version 1). `again` is tombstoned a second time
    // (version 2), and `duplicate` is sent twice, so its lower bound must win.
    let ctx = ServiceTestContext::new().await;
    let at_bound = ctx.insert_person("svc_bound_at", None).await.unwrap();
    let again = ctx.insert_person("svc_bound_again", None).await.unwrap();
    let duplicate = ctx.insert_person("svc_bound_dup", None).await.unwrap();
    for person in [&at_bound, &again, &duplicate] {
        ctx.tombstone_person(person.id, None).await.unwrap();
    }
    ctx.tombstone_person(again.id, None).await.unwrap();
    let live = ctx.insert_person("svc_bound_live", None).await.unwrap();
    let bound = |person: &TestPerson, max_version: i64| VersionBoundedPerson {
        person_uuid: person.uuid.to_string(),
        max_version,
    };

    let response = ctx
        .service
        .delete_tombstoned_persons(Request::new(DeleteTombstonedPersonsRequest {
            team_id: ctx.team_id,
            person_uuids: vec![],
            max_rows: 0,
            bounded_persons: vec![
                bound(&at_bound, 1),
                bound(&again, 1),
                bound(&duplicate, 5),
                bound(&duplicate, 0),
                bound(&live, 5),
            ],
        }))
        .await
        .expect("RPC failed")
        .into_inner();

    assert_eq!(
        response,
        DeleteTombstonedPersonsResponse {
            deleted_count: 1,
            skipped_live_count: 1,
            rows_deleted: 1,
            version_guard_applied: true,
            skipped_version_count: 2,
            ..Default::default()
        }
    );
    assert!(!ctx.person_row_exists(at_bound.id).await.unwrap());
    for person in [&again, &duplicate, &live] {
        assert!(ctx.person_row_exists(person.id).await.unwrap());
    }

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::unspecified(DeletePersonsMode::Unspecified as i32)]
#[case::tombstone(DeletePersonsMode::Tombstone as i32)]
#[tokio::test]
async fn test_delete_persons_tombstone_mode_reports_versions(#[case] mode: i32) {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_tomb_mode", None).await.unwrap();

    let response = ctx
        .service
        .delete_persons(Request::new(DeletePersonsRequest {
            team_id: ctx.team_id,
            person_uuids: vec![person.uuid.to_string()],
            mode,
        }))
        .await
        .expect("RPC failed")
        .into_inner();

    assert_eq!(response.deleted_count, 1);
    assert!(response.tombstoned);
    assert_eq!(response.tombstones.len(), 1);
    assert_eq!(response.tombstones[0].person_uuid, person.uuid.to_string());
    assert_eq!(response.tombstones[0].version, 1);
    assert_eq!(response.tombstones[0].distinct_ids.len(), 1);
    assert_eq!(
        response.tombstones[0].distinct_ids[0].distinct_id,
        "svc_tomb_mode"
    );
    assert_eq!(response.tombstones[0].distinct_ids[0].version, 1);

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::hard(DeletePersonsMode::Hard as i32)]
#[case::unknown(99)]
#[tokio::test]
async fn test_delete_persons_rejects_unsupported_modes(#[case] mode: i32) {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_rejected_mode", None).await.unwrap();

    let status = ctx
        .service
        .delete_persons(Request::new(DeletePersonsRequest {
            team_id: ctx.team_id,
            person_uuids: vec![person.uuid.to_string()],
            mode,
        }))
        .await
        .unwrap_err();

    assert_eq!(status.code(), tonic::Code::InvalidArgument);
    assert!(ctx.person_row_exists(person.id).await.unwrap());
    assert_eq!(ctx.distinct_id_row_count(person.id).await.unwrap(), 1);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_delete_persons_batch_for_team() {
    let ctx = ServiceTestContext::new().await;
    let _p1 = ctx.insert_person("svc_batch_del_1", None).await.unwrap();
    let _p2 = ctx.insert_person("svc_batch_del_2", None).await.unwrap();

    // Delete with batch_size=1 — should delete 1
    let response = ctx
        .service
        .delete_persons_batch_for_team(Request::new(DeletePersonsBatchForTeamRequest {
            team_id: ctx.team_id,
            batch_size: 1,
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().deleted_count, 1);

    // Delete again — should delete the other 1
    let response = ctx
        .service
        .delete_persons_batch_for_team(Request::new(DeletePersonsBatchForTeamRequest {
            team_id: ctx.team_id,
            batch_size: 1,
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().deleted_count, 1);

    // Delete again — nothing left
    let response = ctx
        .service
        .delete_persons_batch_for_team(Request::new(DeletePersonsBatchForTeamRequest {
            team_id: ctx.team_id,
            batch_size: 1,
        }))
        .await
        .expect("RPC failed");

    assert_eq!(response.into_inner().deleted_count, 0);

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::zero(0)]
#[case::negative(-1)]
#[case::exceeds_max(50001)]
#[tokio::test]
async fn test_delete_persons_batch_for_team_invalid_batch_size(#[case] batch_size: i64) {
    let ctx = ServiceTestContext::new().await;

    let result = ctx
        .service
        .delete_persons_batch_for_team(Request::new(DeletePersonsBatchForTeamRequest {
            team_id: ctx.team_id,
            batch_size,
        }))
        .await;

    let status = result.unwrap_err();
    assert_eq!(status.code(), tonic::Code::InvalidArgument);
    assert!(status.message().contains("batch_size"));

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::exceeds_max((0..251).map(|i| format!("did_{i}")).collect(), "Maximum")]
#[case::duplicates(vec!["[email protected]".to_string(), "[email protected]".to_string()], "Duplicate")]
#[tokio::test]
async fn test_split_person_invalid_request(
    #[case] distinct_ids_to_split: Vec<String>,
    #[case] expected_message: &str,
) {
    let ctx = ServiceTestContext::new().await;

    let result = ctx
        .service
        .split_person(Request::new(SplitPersonRequest {
            team_id: ctx.team_id,
            person_id: 1,
            distinct_ids_to_split,
        }))
        .await;

    let status = result.unwrap_err();
    assert_eq!(status.code(), tonic::Code::InvalidArgument);
    assert!(
        status.message().contains(expected_message),
        "Expected message containing {expected_message:?}, got: {}",
        status.message()
    );

    ctx.cleanup().await.ok();
}

// ============================================================
// Undelete repair: reset version tests
// ============================================================

#[tokio::test]
async fn test_set_person_distinct_id_version_floor() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_repair_did", None).await.unwrap();

    let response = ctx
        .service
        .set_person_distinct_id_version_floor(Request::new(
            SetPersonDistinctIdVersionFloorRequest {
                team_id: ctx.team_id,
                distinct_id: "svc_repair_did".to_string(),
                min_version: 150,
            },
        ))
        .await
        .expect("RPC failed");

    let returned = response
        .into_inner()
        .person
        .expect("person should be present");
    assert_eq!(returned.id, person.id);
    assert_eq!(returned.uuid, person.uuid.to_string());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_set_person_distinct_id_version_floor_missing() {
    let ctx = ServiceTestContext::new().await;

    let response = ctx
        .service
        .set_person_distinct_id_version_floor(Request::new(
            SetPersonDistinctIdVersionFloorRequest {
                team_id: ctx.team_id,
                distinct_id: "svc_missing_did".to_string(),
                min_version: 10,
            },
        ))
        .await
        .expect("RPC failed");

    assert!(response.into_inner().person.is_none());

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_set_person_version_floor() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_rv_did", None).await.unwrap();

    let response = ctx
        .service
        .set_person_version_floor(Request::new(SetPersonVersionFloorRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            min_version: 50,
        }))
        .await
        .expect("RPC failed");
    assert!(response.into_inner().updated);

    // Lower min_version is a guarded no-op.
    let response = ctx
        .service
        .set_person_version_floor(Request::new(SetPersonVersionFloorRequest {
            team_id: ctx.team_id,
            person_id: person.id,
            min_version: 10,
        }))
        .await
        .expect("RPC failed");
    assert!(!response.into_inner().updated);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_ensure_person_version_floors_maps_results_to_proto() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_floor_live", None).await.unwrap();
    let absent_person = Uuid::now_v7();

    let person_floors = ctx
        .service
        .ensure_person_version_floors(Request::new(EnsurePersonVersionFloorsRequest {
            team_id: ctx.team_id,
            floors: vec![
                PersonVersionFloor {
                    person_uuid: person.uuid.to_string(),
                    min_version: 2,
                },
                PersonVersionFloor {
                    person_uuid: absent_person.to_string(),
                    min_version: 5,
                },
            ],
        }))
        .await
        .unwrap()
        .into_inner();
    assert_eq!(
        person_floors.results,
        vec![
            PersonVersionFloorResult {
                person_uuid: person.uuid.to_string(),
                outcome: VersionFloorOutcome::Live as i32,
                version: 0,
            },
            PersonVersionFloorResult {
                person_uuid: absent_person.to_string(),
                outcome: VersionFloorOutcome::TombstoneInserted as i32,
                version: 5,
            },
        ]
    );

    ctx.cleanup().await.ok();
}

fn read_options(strong: bool) -> Option<ReadOptions> {
    strong.then(|| ReadOptions {
        consistency: ConsistencyLevel::Strong as i32,
        ..Default::default()
    })
}

#[rstest]
#[case::eventual(false)]
#[case::strong(true)]
#[tokio::test]
async fn test_get_distinct_id_rows_reports_tombstones_and_owner_state(#[case] strong: bool) {
    let ctx = ServiceTestContext::new().await;
    let live = ctx.insert_person("rows_live", None).await.unwrap();
    ctx.add_distinct_id_to_person(live.id, "rows_live_gone")
        .await
        .unwrap();
    sqlx::query(
        "UPDATE posthog_persondistinctid SET is_deleted = true, version = 4 WHERE team_id = $1 AND distinct_id = 'rows_live_gone'",
    )
    .bind(ctx.team_id)
    .execute(&ctx.pool)
    .await
    .unwrap();
    let deleted = ctx.insert_person("rows_deleted", None).await.unwrap();
    ctx.add_distinct_id_to_person(deleted.id, "rows_stray")
        .await
        .unwrap();
    ctx.tombstone_person(deleted.id, Some("rows_stray"))
        .await
        .unwrap();

    let rows = ctx
        .service
        .get_distinct_id_rows(Request::new(GetDistinctIdRowsRequest {
            team_id: ctx.team_id,
            distinct_ids: [
                "rows_stray",
                "rows_live",
                "rows_missing",
                "rows_live_gone",
                "rows_deleted",
            ]
            .map(String::from)
            .to_vec(),
            read_options: read_options(strong),
        }))
        .await
        .expect("RPC failed")
        .into_inner()
        .rows;

    let got: Vec<(&str, i64, bool, Option<bool>)> = rows
        .iter()
        .map(|r| {
            (
                r.distinct_id.as_str(),
                r.version,
                r.is_deleted,
                r.person_is_deleted,
            )
        })
        .collect();
    assert_eq!(
        got,
        vec![
            ("rows_deleted", 1, true, Some(true)),
            ("rows_live", 0, false, Some(false)),
            ("rows_live_gone", 4, true, Some(false)),
            ("rows_stray", 0, false, Some(true)),
        ]
    );
    let deleted_uuid = deleted.uuid.to_string();
    let live_uuid = live.uuid.to_string();
    for row in &rows {
        let (expected_id, expected_uuid) = if row.distinct_id.starts_with("rows_live") {
            (live.id, &live_uuid)
        } else {
            (deleted.id, &deleted_uuid)
        };
        assert_eq!(row.person_id, expected_id);
        assert_eq!(row.person_uuid.as_ref(), Some(expected_uuid));
    }

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_get_distinct_id_rows_rejects_more_than_1000_ids() {
    let ctx = ServiceTestContext::new().await;
    let status = ctx
        .service
        .get_distinct_id_rows(Request::new(GetDistinctIdRowsRequest {
            team_id: ctx.team_id,
            distinct_ids: (0..1001).map(|i| format!("too_many_{i}")).collect(),
            read_options: None,
        }))
        .await
        .expect_err("over the cap");
    assert_eq!(status.code(), tonic::Code::InvalidArgument);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_list_persons_for_team_pages_in_id_order_with_tombstones() {
    let ctx = ServiceTestContext::new().await;
    let with_ids = ctx.insert_person("list_with_ids", None).await.unwrap();
    let tombstoned = ctx.insert_person("list_tombstoned", None).await.unwrap();
    ctx.tombstone_person(tombstoned.id, None).await.unwrap();
    let without_ids = ctx.insert_person("list_without_ids", None).await.unwrap();
    ctx.delete_distinct_ids_of(without_ids.id).await.unwrap();
    let mut expected = vec![
        (with_ids.id, with_ids.uuid.to_string(), 0, false, true),
        (tombstoned.id, tombstoned.uuid.to_string(), 1, true, false),
        (
            without_ids.id,
            without_ids.uuid.to_string(),
            0,
            false,
            false,
        ),
    ];
    expected.sort();

    let mut page_sizes = Vec::new();
    let mut listed = Vec::new();
    let mut after_person_id = 0;
    loop {
        let page = ctx
            .service
            .list_persons_for_team(Request::new(ListPersonsForTeamRequest {
                team_id: ctx.team_id,
                after_person_id,
                limit: 2,
                read_options: None,
                before_person_id: None,
            }))
            .await
            .expect("RPC failed")
            .into_inner();
        page_sizes.push(page.persons.len());
        for p in &page.persons {
            assert!(p.created_at_ms > 0);
            listed.push((
                p.id,
                p.uuid.clone(),
                p.version,
                p.is_deleted,
                p.has_live_distinct_ids,
            ));
        }
        match page.next_after_person_id {
            Some(id) => after_person_id = id,
            None => break,
        }
    }

    assert_eq!(page_sizes, vec![2, 1]);
    assert_eq!(listed, expected);

    let bounded = ctx
        .service
        .list_persons_for_team(Request::new(ListPersonsForTeamRequest {
            team_id: ctx.team_id,
            after_person_id: 0,
            limit: 0,
            read_options: None,
            before_person_id: Some(expected[2].0),
        }))
        .await
        .expect("RPC failed")
        .into_inner();
    let bounded_ids: Vec<i64> = bounded.persons.iter().map(|p| p.id).collect();
    assert_eq!(bounded_ids, vec![expected[0].0, expected[1].0]);
    assert_eq!(bounded.next_after_person_id, None);

    ctx.cleanup().await.ok();
}

#[rstest]
#[case::negative_limit(-1, false, tonic::Code::InvalidArgument)]
#[case::limit_over_the_cap(10_001, false, tonic::Code::InvalidArgument)]
#[case::strong_consistency(0, true, tonic::Code::FailedPrecondition)]
#[tokio::test]
async fn test_list_persons_for_team_rejects_bad_requests(
    #[case] limit: i64,
    #[case] strong: bool,
    #[case] code: tonic::Code,
) {
    let ctx = ServiceTestContext::new().await;
    let status = ctx
        .service
        .list_persons_for_team(Request::new(ListPersonsForTeamRequest {
            team_id: ctx.team_id,
            after_person_id: 0,
            limit,
            read_options: read_options(strong),
            before_person_id: None,
        }))
        .await
        .expect_err("rejected");
    assert_eq!(status.code(), code);

    ctx.cleanup().await.ok();
}

#[tokio::test]
async fn test_repair_writes_round_trip_through_the_service() {
    let ctx = ServiceTestContext::new().await;
    let person = ctx.insert_person("svc_repair", None).await.unwrap();

    let raised = ctx
        .service
        .raise_person_version_floors(Request::new(RaisePersonVersionFloorsRequest {
            team_id: ctx.team_id,
            floors: vec![PersonVersionFloor {
                person_uuid: person.uuid.to_string(),
                min_version: 5,
            }],
        }))
        .await
        .expect("raise")
        .into_inner()
        .results;
    assert_eq!(
        (raised[0].outcome, raised[0].version),
        (RaiseOutcome::Raised as i32, 5)
    );

    let absent = Uuid::new_v4();
    let restored = ctx
        .service
        .restore_persons(Request::new(RestorePersonsRequest {
            team_id: ctx.team_id,
            persons: vec![RestoredPerson {
                person_uuid: absent.to_string(),
                properties: br#"{"plan": "free"}"#.to_vec(),
                created_at_ms: 1_600_000_000_000,
                is_identified: false,
                version: 4,
                distinct_ids: vec![RestoredDistinctId {
                    distinct_id: "svc_repair_restored".to_string(),
                    version: 3,
                }],
            }],
        }))
        .await
        .expect("restore")
        .into_inner()
        .results;
    assert_eq!(restored[0].outcome, RestoreOutcome::Inserted as i32);
    assert_eq!(restored[0].version, 4);
    assert_eq!(
        restored[0].restored_distinct_ids,
        vec!["svc_repair_restored"]
    );

    let written = ctx
        .service
        .write_distinct_ids(Request::new(WriteDistinctIdsRequest {
            team_id: ctx.team_id,
            writes: vec![DistinctIdWrite {
                distinct_id: "svc_repair_new".to_string(),
                action: DistinctIdWriteAction::Insert as i32,
                person_uuid: person.uuid.to_string(),
                min_version: 6,
                expected_version: None,
            }],
        }))
        .await
        .expect("write")
        .into_inner()
        .results;
    assert_eq!(written[0].outcome, DistinctIdWriteOutcome::Applied as i32);
    let row = written[0].row.as_ref().expect("row after the write");
    assert_eq!(
        (
            row.person_id,
            row.person_uuid.clone(),
            row.version,
            row.is_deleted,
            row.person_is_deleted
        ),
        (
            person.id,
            Some(person.uuid.to_string()),
            6,
            false,
            Some(false)
        )
    );

    let tombstoned = ctx
        .service
        .write_distinct_ids(Request::new(WriteDistinctIdsRequest {
            team_id: ctx.team_id,
            writes: vec![DistinctIdWrite {
                distinct_id: "svc_repair_new".to_string(),
                action: DistinctIdWriteAction::Tombstone as i32,
                person_uuid: person.uuid.to_string(),
                min_version: 9,
                expected_version: None,
            }],
        }))
        .await
        .expect("tombstone")
        .into_inner()
        .results;
    assert_eq!(
        tombstoned[0].outcome,
        DistinctIdWriteOutcome::PreconditionFailed as i32
    );
    let row = tombstoned[0].row.as_ref().expect("row after the write");
    assert_eq!((row.version, row.is_deleted), (6, false));

    ctx.cleanup().await.ok();
}

#[derive(Debug, Clone, Copy)]
enum BadRepairRequest {
    TooManyFloors,
    DuplicateFloorUuid,
    PropertiesNotJson,
    PropertiesNotAnObject,
    DuplicateRestoredDistinctId,
    UnknownWriteAction,
}

#[rstest]
#[case::too_many_floors(BadRepairRequest::TooManyFloors)]
#[case::duplicate_floor_uuid(BadRepairRequest::DuplicateFloorUuid)]
#[case::properties_not_json(BadRepairRequest::PropertiesNotJson)]
#[case::properties_not_an_object(BadRepairRequest::PropertiesNotAnObject)]
#[case::duplicate_restored_distinct_id(BadRepairRequest::DuplicateRestoredDistinctId)]
#[case::unknown_write_action(BadRepairRequest::UnknownWriteAction)]
#[tokio::test]
async fn test_repair_writes_reject_bad_requests(#[case] bad: BadRepairRequest) {
    let ctx = ServiceTestContext::new().await;
    let uuid = Uuid::new_v4().to_string();
    let floor = |u: String| PersonVersionFloor {
        person_uuid: u,
        min_version: 1,
    };
    let restore = |properties: &[u8]| RestorePersonsRequest {
        team_id: ctx.team_id,
        persons: vec![RestoredPerson {
            person_uuid: uuid.clone(),
            properties: properties.to_vec(),
            created_at_ms: 0,
            is_identified: false,
            version: 1,
            distinct_ids: vec![],
        }],
    };
    let status = match bad {
        BadRepairRequest::TooManyFloors => ctx
            .service
            .raise_person_version_floors(Request::new(RaisePersonVersionFloorsRequest {
                team_id: ctx.team_id,
                floors: (0..251)
                    .map(|_| floor(Uuid::new_v4().to_string()))
                    .collect(),
            }))
            .await
            .map(|_| ()),
        BadRepairRequest::DuplicateFloorUuid => ctx
            .service
            .raise_person_version_floors(Request::new(RaisePersonVersionFloorsRequest {
                team_id: ctx.team_id,
                floors: vec![floor(uuid.clone()), floor(uuid.to_uppercase())],
            }))
            .await
            .map(|_| ()),
        BadRepairRequest::PropertiesNotJson => ctx
            .service
            .restore_persons(Request::new(restore(b"not json")))
            .await
            .map(|_| ()),
        BadRepairRequest::PropertiesNotAnObject => ctx
            .service
            .restore_persons(Request::new(restore(b"[1, 2]")))
            .await
            .map(|_| ()),
        BadRepairRequest::DuplicateRestoredDistinctId => {
            let mut request = restore(b"{}");
            let id = || RestoredDistinctId {
                distinct_id: "svc_dup".to_string(),
                version: 0,
            };
            request.persons[0].distinct_ids = vec![id(), id()];
            ctx.service
                .restore_persons(Request::new(request))
                .await
                .map(|_| ())
        }
        BadRepairRequest::UnknownWriteAction => ctx
            .service
            .write_distinct_ids(Request::new(WriteDistinctIdsRequest {
                team_id: ctx.team_id,
                writes: vec![DistinctIdWrite {
                    distinct_id: "svc_bad_action".to_string(),
                    action: DistinctIdWriteAction::Unspecified as i32,
                    person_uuid: uuid.clone(),
                    min_version: 1,
                    expected_version: None,
                }],
            }))
            .await
            .map(|_| ()),
    }
    .expect_err("rejected");
    assert_eq!(status.code(), tonic::Code::InvalidArgument, "{status:?}");

    ctx.cleanup().await.ok();
}