From c554256db1ca446ff62264a55ede5fe410699b81 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 19 Jun 2026 21:08:09 +0530 Subject: [PATCH] chore: fix phantom user creation in posthog --- api/services/posthog_client.py | 3 ++- api/tests/test_posthog_client.py | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 api/tests/test_posthog_client.py diff --git a/api/services/posthog_client.py b/api/services/posthog_client.py index 96e10280..15e3a4ac 100644 --- a/api/services/posthog_client.py +++ b/api/services/posthog_client.py @@ -6,6 +6,7 @@ from posthog import Posthog from api.constants import POSTHOG_API_KEY, POSTHOG_HOST _posthog_client: Posthog | None = None +POSTHOG_SERVER_GROUP_IDENTIFY_DISTINCT_ID = "server-group-identify" def get_posthog() -> Posthog | None: @@ -77,7 +78,7 @@ def group_identify( group_type, group_key, properties, - distinct_id=distinct_id, + distinct_id=distinct_id or POSTHOG_SERVER_GROUP_IDENTIFY_DISTINCT_ID, ) except Exception: logger.exception("Failed to identify PostHog group") diff --git a/api/tests/test_posthog_client.py b/api/tests/test_posthog_client.py new file mode 100644 index 00000000..cbf9919d --- /dev/null +++ b/api/tests/test_posthog_client.py @@ -0,0 +1,34 @@ +from api.services import posthog_client + + +class FakePostHog: + def __init__(self): + self.group_identify_calls = [] + + def group_identify(self, *args, **kwargs): + self.group_identify_calls.append((args, kwargs)) + + +def test_group_identify_uses_stable_server_distinct_id(monkeypatch): + fake_posthog = FakePostHog() + monkeypatch.setattr(posthog_client, "get_posthog", lambda: fake_posthog) + + posthog_client.group_identify("organization", "42", {}) + + _, kwargs = fake_posthog.group_identify_calls[0] + assert kwargs["distinct_id"] == "server-group-identify" + + +def test_group_identify_preserves_real_distinct_id(monkeypatch): + fake_posthog = FakePostHog() + monkeypatch.setattr(posthog_client, "get_posthog", lambda: fake_posthog) + + posthog_client.group_identify( + "organization", + "42", + {}, + distinct_id="stack-user-1", + ) + + _, kwargs = fake_posthog.group_identify_calls[0] + assert kwargs["distinct_id"] == "stack-user-1"