: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(marketing): generate varied demo traffic sessions (#98788)
Javier Bahamondes53713263c8a6
diff --git a/docs/internal/marketing-analytics-demo-data.md b/docs/internal/marketing-analytics-demo-data.mdnew file mode 100644index 000000000000..37aa5a6051b2--- /dev/null+++ b/docs/internal/marketing-analytics-demo-data.md@@ -0,0 +1,11 @@+# Marketing analytics demo traffic++`generate_marketing_demo_data` generates returning visitors and a mix of single-page and multi-page sessions for paid and free channels. Repeated pageviews share a session ID and have later timestamps, so visitors, sessions, pageviews and engagement metrics can be reviewed separately.++Use a fresh local project and at least twice the dashboard date range for previous-period comparisons. The command defaults to 60 days, covering two 30-day periods. It also configures demo warehouse sources and goals; it is not a traffic-only seeder.++```sh+DEBUG=1 python manage.py generate_marketing_demo_data --team-id <demo-project-id> --days-past 60 --scale 0.1+```++Existing seeded events are unchanged. Generate into a new project to avoid mixing old and new traffic distributions.diff --git a/products/marketing_analytics/backend/demo/events.py b/products/marketing_analytics/backend/demo/events.pyindex a3053aec3353..871a319a15e2 100644--- a/products/marketing_analytics/backend/demo/events.py+++ b/products/marketing_analytics/backend/demo/events.py@@ -55,6 +55,7 @@ class MarketingEventGenerator:self.now = nowself.result = GenerationResult()self._person_counter = 0+ self._visitors: list[tuple[str, uuid.UUID]] = []def generate(self) -> GenerationResult:for day_offset in range(self.days_past, 0, -1):@@ -71,7 +72,7 @@ class MarketingEventGenerator:def _generate_campaign_day(self, campaign: DemoCampaign, day: dt.datetime) -> None:for _ in range(self._daily_volume(campaign.daily_sessions, day)):- distinct_id, person_uuid = self._new_person()+ distinct_id, person_uuid = self._traffic_visitor()ts = self._time_in_day(day)utm_source = self._pick_variant(campaign.utm_source, campaign.utm_source_variants)utm_campaign = self._pick_variant(@@ -86,7 +87,7 @@ class MarketingEventGenerator:}if campaign.click_id_property:properties[campaign.click_id_property] = uuid.uuid5(PERSON_NAMESPACE, f"click-{distinct_id}").hex- session_id = self._pageview(distinct_id, person_uuid, ts, properties)+ session_id = self._browse_session(distinct_id, person_uuid, ts, properties)self._maybe_convert(distinct_id,person_uuid,@@ -100,7 +101,7 @@ class MarketingEventGenerator:def _generate_free_channel_day(self, channel: DemoFreeChannel, day: dt.datetime) -> None:for _ in range(self._daily_volume(channel.daily_sessions, day)):- distinct_id, person_uuid = self._new_person()+ distinct_id, person_uuid = self._traffic_visitor()ts = self._time_in_day(day)properties: dict = {"$referring_domain": channel.referring_domain}utm_source = self._pick_variant(channel.utm_source, channel.utm_source_variants)@@ -113,7 +114,7 @@ class MarketingEventGenerator:if channel.click_id_property:properties[channel.click_id_property] = uuid.uuid5(PERSON_NAMESPACE, f"click-{distinct_id}").hexproperties.update(channel.extra_properties)- session_id = self._pageview(distinct_id, person_uuid, ts, properties)+ session_id = self._browse_session(distinct_id, person_uuid, ts, properties)self._maybe_convert(distinct_id,person_uuid,@@ -286,6 +287,30 @@ class MarketingEventGenerator:seconds=self.rng.randint(6 * 3600, 22 * 3600))+ def _traffic_visitor(self) -> tuple[str, uuid.UUID]:+ if self._visitors and self.rng.random() < 0.35:+ return self.rng.choice(self._visitors)+ visitor = self._new_person()+ self._visitors.append(visitor)+ return visitor++ def _browse_session(self, distinct_id: str, person_uuid: uuid.UUID, ts: dt.datetime, properties: dict) -> str:+ session_id = self._pageview(distinct_id, person_uuid, ts, properties)+ if self.rng.random() < 0.4:+ return session_id+ elapsed = 0+ for pathname in self.rng.sample(["/features", "/pricing", "/docs", "/customers"], self.rng.randint(1, 4)):+ elapsed += self.rng.randint(15, 150)+ self._emit(+ distinct_id,+ person_uuid,+ EVENT_PAGEVIEW,+ ts + dt.timedelta(seconds=elapsed),+ {**properties, "$current_url": SITE_URL + pathname, "$pathname": pathname},+ session_id=session_id,+ )+ return session_id+def _new_person(self) -> tuple[str, uuid.UUID]:self._person_counter += 1distinct_id = f"mkt-demo-{self._person_counter}"diff --git a/products/marketing_analytics/backend/demo/test_events.py b/products/marketing_analytics/backend/demo/test_events.pynew file mode 100644index 000000000000..959fe5f7630a--- /dev/null+++ b/products/marketing_analytics/backend/demo/test_events.py@@ -0,0 +1,47 @@+import datetime as dt+from collections import Counter, defaultdict++from unittest.mock import patch++from django.test import SimpleTestCase++from posthog.models import Team++from products.marketing_analytics.backend.demo.events import MarketingEventGenerator+from products.marketing_analytics.backend.demo.world import EVENT_PAGEVIEW+++class TestMarketingDemoTraffic(SimpleTestCase):+ def test_traffic_has_returning_visitors_and_multi_page_sessions(self) -> None:+ now = dt.datetime(2026, 8, 1, tzinfo=dt.UTC)+ with patch("products.marketing_analytics.backend.demo.events.create_event") as capture:+ MarketingEventGenerator(Team(), seed="traffic-mix", days_past=14, scale=0.02, now=now).generate()++ pageviews = [call.kwargs for call in capture.call_args_list if call.kwargs["event"] == EVENT_PAGEVIEW]+ visitors = {event["distinct_id"] for event in pageviews}+ sessions = Counter(event["properties"]["$session_id"] for event in pageviews)+ visitor_days: dict[str, set[dt.date]] = defaultdict(set)+ for event in pageviews:+ visitor_days[event["distinct_id"]].add(event["timestamp"].date())++ assert len(visitors) < len(sessions) < len(pageviews)+ assert any(len(days) > 1 for days in visitor_days.values())+ assert any(count == 1 for count in sessions.values())+ assert any(count > 1 for count in sessions.values())+ assert all(event["timestamp"] < now for event in pageviews)++ for start, end in [+ (now - dt.timedelta(days=14), now - dt.timedelta(days=7)),+ (now - dt.timedelta(days=7), now),+ ]:+ period = [event for event in pageviews if start <= event["timestamp"] < end]+ assert (+ len({event["distinct_id"] for event in period})+ < len({event["properties"]["$session_id"] for event in period})+ < len(period)+ )++ timestamps: dict[str, list[dt.datetime]] = defaultdict(list)+ for event in pageviews:+ timestamps[event["properties"]["$session_id"]].append(event["timestamp"])+ assert any(max(times) > min(times) for times in timestamps.values())