:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(demo): emit $experiment_exposure copies in demo data (#117321)
Rodrigo Ilorodacb09da878f
diff --git a/products/demo/backend/logic/matrix/manager.py b/products/demo/backend/logic/matrix/manager.pyindex 89f58bc24c94..8203a48052f4 100644--- a/products/demo/backend/logic/matrix/manager.py+++ b/products/demo/backend/logic/matrix/manager.py@@ -1,16 +1,18 @@# ruff: noqa: T201 allow print statementsimport datetime as dt-from collections.abc import Callable+from collections.abc import Callable, Iteratorfrom functools import partialfrom time import sleepfrom typing import Any, Literal, cast+from uuid import UUID, uuid5from django.conf import settingsfrom django.core import exceptionsfrom django.db import transactionfrom posthog.clickhouse.client import sync_execute+from posthog.dataclasses import frozenfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_EVENTS_JSONfrom posthog.models import Organization, OrganizationMembership, Team, User@@ -31,6 +33,40 @@ from .models import EVENT_IDENTIFY, SimEvent, SimPerson# Each flush waits at most 1 second, so one event waits at most about this many seconds for queue room.QUEUE_FULL_MAX_FLUSHES = 60+# Demo events go straight to ClickHouse and skip Node ingestion, so this module makes the+# $experiment_exposure copies itself. Keep these values and the copy rule in sync with+# nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts.+EVENT_FEATURE_FLAG_CALLED = "$feature_flag_called"+EVENT_EXPERIMENT_EXPOSURE = "$experiment_exposure"+EXPERIMENT_EXPOSURE_UUID_NAMESPACE = UUID("1b7c9119-5953-4668-97b7-ab0ef8a6bb48")+++def _is_multivariate_flag_call(event: SimEvent) -> bool:+ response = event.properties.get("$feature_flag_response")+ return (+ event.event == EVENT_FEATURE_FLAG_CALLED and isinstance(response, str) and response not in ("", "true", "false")+ )+++@frozen+class _EventToSave:+ uuid: UUID+ name: str+ source: SimEvent+++def _with_exposure_copies(events: list[SimEvent]) -> Iterator[_EventToSave]:+ """Yield each event to save, with each multivariate flag call followed by its $experiment_exposure copy."""+ for event in events:+ event_uuid = UUIDT(unix_time_ms=int(event.timestamp.timestamp() * 1000))+ yield _EventToSave(uuid=event_uuid, name=event.event, source=event)+ if _is_multivariate_flag_call(event):+ yield _EventToSave(+ uuid=uuid5(EXPERIMENT_EXPOSURE_UUID_NAMESPACE, str(event_uuid)),+ name=EVENT_EXPERIMENT_EXPOSURE,+ source=event,+ )+def _produce_when_queue_has_room(produce: Callable[[], object]) -> None:"""Run one produce, and wait for room when the local Kafka queue is full.@@ -313,13 +349,13 @@ class MatrixManager:"""Past events are saved into ClickHouse right away (via Kafka of course)."""from posthog.models.event.util import create_event- for event in events:- event_uuid = UUIDT(unix_time_ms=int(event.timestamp.timestamp() * 1000))+ for to_save in _with_exposure_copies(events):+ event = to_save.source_produce_when_queue_has_room(partial(create_event,- event_uuid=event_uuid,- event=event.event,+ event_uuid=to_save.uuid,+ event=to_save.name,team=team,distinct_id=event.distinct_id,timestamp=event.timestamp,diff --git a/products/demo/backend/test/test_matrix_manager.py b/products/demo/backend/test/test_matrix_manager.pyindex dc79feafb729..fe6f29ac200b 100644--- a/products/demo/backend/test/test_matrix_manager.py+++ b/products/demo/backend/test/test_matrix_manager.py@@ -1,6 +1,7 @@import datetime as dtfrom enum import auto-from typing import Optional+from typing import Any, Optional+from uuid import UUID, uuid4, uuid5from zoneinfo import ZoneInfofrom posthog.test.base import ClickhouseDestroyTablesMixin@@ -17,10 +18,12 @@ from posthog.models import OrganizationMembershipfrom products.demo.backend.logic.matrix.manager import (QUEUE_FULL_MAX_FLUSHES,MatrixManager,+ _EventToSave,_produce_when_queue_has_room,+ _with_exposure_copies,)from products.demo.backend.logic.matrix.matrix import Cluster, Matrix-from products.demo.backend.logic.matrix.models import SimPerson, SimSessionIntent+from products.demo.backend.logic.matrix.models import SimEvent, SimPerson, SimSessionIntentclass DummySessionIntent(SimSessionIntent):@@ -38,6 +41,12 @@ class DummyPerson(SimPerson):self.active_client.capture_pageview("/", {"foo": "bar"})self.active_client.identify(self.in_product_id)self.active_client.group("company", "Acme", {"bar": "foo"})+ self.active_client.capture(+ "$feature_flag_called", {"$feature_flag": "multivariate-flag", "$feature_flag_response": "test"}+ )+ self.active_client.capture(+ "$feature_flag_called", {"$feature_flag": "boolean-flag", "$feature_flag_response": "true"}+ )self.advance_timer(86400 * 12)@@ -112,6 +121,17 @@ class TestMatrixManager(ClickhouseDestroyTablesMixin):>= 3)assert self.team.name == DummyMatrix.PRODUCT_NAME+ exposures, multivariate_flag_calls = sync_execute(+ """+ SELECT+ countIf(event = '$experiment_exposure'),+ countIf(event = '$feature_flag_called' AND JSONExtractString(properties, '$feature_flag_response') = 'test')+ FROM events WHERE team_id = %(team_id)s+ """,+ {"team_id": self.team.pk},+ )[0]+ assert multivariate_flag_calls >= 3+ assert exposures == multivariate_flag_callsdef test_run_on_team_marks_persons_that_identified(self):manager = MatrixManager(self.matrix)@@ -142,6 +162,45 @@ class TestMatrixManager(ClickhouseDestroyTablesMixin):)+class TestWithExposureCopies(SimpleTestCase):+ @parameterized.expand(+ [+ ("multivariate_response", "$feature_flag_called", "test", True),+ ("true_string_response", "$feature_flag_called", "true", False),+ ("false_string_response", "$feature_flag_called", "false", False),+ ("empty_string_response", "$feature_flag_called", "", False),+ ("boolean_response", "$feature_flag_called", True, False),+ ("other_event_with_variant", "$pageview", "test", False),+ ]+ )+ def test_copies_only_multivariate_flag_calls(+ self, _name: str, event_name: str, response: Any, expect_copy: bool+ ) -> None:+ timestamp = dt.datetime(2020, 1, 1, tzinfo=ZoneInfo("UTC"))+ event = SimEvent(+ event=event_name,+ distinct_id="person-1",+ properties={"$feature_flag": "some-flag", "$feature_flag_response": response},+ timestamp=timestamp,+ person_id=uuid4(),+ person_properties={},+ person_created_at=timestamp,+ )++ saved = list(_with_exposure_copies([event]))++ source_uuid = saved[0].uuid+ expected = [_EventToSave(uuid=source_uuid, name=event_name, source=event)]+ if expect_copy:+ ingestion_namespace = UUID("1b7c9119-5953-4668-97b7-ab0ef8a6bb48")+ expected.append(+ _EventToSave(+ uuid=uuid5(ingestion_namespace, str(source_uuid)), name="$experiment_exposure", source=event+ )+ )+ assert saved == expected++class TestProduceWhenQueueHasRoom(SimpleTestCase):@parameterized.expand([