: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
feat(marketing-analytics): leave a platform unconnected so demo data reaches connect_source (#83328)
Javier Bahamondesf33baad1c1f5
diff --git a/products/marketing_analytics/backend/demo/config.py b/products/marketing_analytics/backend/demo/config.pyindex 87e3b4a04b1b..7fe4acd94bdd 100644--- a/products/marketing_analytics/backend/demo/config.py+++ b/products/marketing_analytics/backend/demo/config.py@@ -15,6 +15,11 @@ MARKETING_FEATURE_FLAGS = ("marketing-analytics-multi-touch-attribution","marketing-analytics-ai","advance-marketing-analytics-settings",+ # Gate the Setup tab and the ROAS / cost-per-customer columns. Without these the+ # seeded world renders as if none of this work existed, which is the opposite of+ # what a seeder is for.+ "marketing-analytics-setup",+ "marketing-analytics-return-metrics",)_DEFAULT_SCHEMA_MAP = {@@ -90,10 +95,11 @@ def build_conversion_goals(team: Team) -> list[dict]:"distinct_id_field": "distinct_id",},},- # Sums money and is flagged as neither, so ROAS and cost per customer stay- # blocked with a goal sitting right there that would unblock them. Drives- # mark_goal_as_revenue / mark_goal_as_customer, and gives the settings- # checkboxes something to turn on.+ # Sums money and is flagged as neither, so the settings checkboxes have a goal+ # to turn on. It does not produce mark_goal_as_revenue / mark_goal_as_customer:+ # those ask "is there any flagged goal at all", and the two below are, which is+ # what keeps ROAS and cost per customer unlocked here. A fixture can show the+ # metrics working or the nudge to enable them, not both.{"kind": "EventsNode","event": EVENT_PURCHASE,diff --git a/products/marketing_analytics/backend/demo/health.py b/products/marketing_analytics/backend/demo/health.pyindex 9f7fc5017a43..e5120edfd4a2 100644--- a/products/marketing_analytics/backend/demo/health.py+++ b/products/marketing_analytics/backend/demo/health.py@@ -2,10 +2,7 @@Source health is computed purely from ExternalDataSource / ExternalDataSchema /ExternalDataJob rows, so each platform below is staged into a different-`last_sync_status`.--Every native platform gets a source here, so no platform lands in `events_only`-and `connect_source` is the one suggestion kind this fixture never produces.+`last_sync_status`, plus one platform deliberately left without a source at all."""import datetime as dt@@ -14,6 +11,7 @@ from django.utils import timezonefrom posthog.models import Team+from products.marketing_analytics.backend.services.native_integrations import EXTERNAL_SOURCE_TYPE_TO_NATIVEfrom products.warehouse_sources.backend.facade.models import (DataWarehouseTable,ExternalDataJob,@@ -29,12 +27,24 @@ PLATFORM_STATES: dict[str, tuple[tuple[str, ...], str]] = {"MetaAds": (("campaigns", "campaign_stats"), "ok"),"LinkedinAds": (("campaign_groups", "campaign_group_stats"), "ok"),"RedditAds": (("campaigns", "campaign_report"), "ok"),- "PinterestAds": (("campaigns", "campaign_analytics"), "ok"),"BingAds": (("campaigns", "campaign_performance_report"), "stale"),"SnapchatAds": (("campaigns", "campaign_stats_daily"), "error"),"TikTokAds": (("campaigns", "campaign_report"), "tables_disabled"),}+# Left without a source so the diagnose service reports `events_only`, which is the+# only way the setup plan reaches `connect_source`. Reddit keeps its paid campaign, so+# the suggestion is correct there and fires. Reddit was in the `ok` state, so no health+# scenario is lost — its cost-table format is, and `--connect-all` brings it back.+UNCONNECTED_PLATFORMS: frozenset[str] = frozenset({"RedditAds"})++# Absent from PLATFORM_STATES entirely rather than listed above, because `--connect-all`+# must not connect them: they send organic traffic only, which is the half the paid gate+# suppresses, so they reach `events_only` and draw no suggestion. That's the mirror of+# Reddit and the pair is the point of the fixture. Named here so the dry-run summary can+# count them — deriving `events_only` from PLATFORM_STATES alone silently misses them.+ORGANIC_ONLY_PLATFORMS: frozenset[str] = frozenset({"PinterestAds"})+def _create_job(source: ExternalDataSource,@@ -56,14 +66,28 @@ def _create_job(ExternalDataJob.objects.filter(id=job.id).update(created_at=now - age)-def create_sources(team: Team) -> dict[str, ExternalDataSource]:- """Create one ExternalDataSource per staged platform (replacing previous demo runs)."""+def create_sources(team: Team, *, unconnected: frozenset[str] = UNCONNECTED_PLATFORMS) -> dict[str, ExternalDataSource]:+ """Create one ExternalDataSource per staged platform (replacing previous demo runs).++ Platforms in `unconnected` are skipped and get no row, which is what puts them in+ `events_only`. Callers must treat a missing key as "no source", not an error.+ """+ # Retire every previous demo fixture across all native platforms first — including+ # ones since dropped from PLATFORM_STATES (e.g. a platform moved to organic-only+ # traffic). Retiring inside the create loop would miss those, leaving a stale source+ # live so the diagnostic keeps the platform "connected" and re-seeding never reaches+ # events_only. Scoped to the marketing-demo- prefix so real integrations are untouched.+ ExternalDataSource.objects.filter(+ team=team,+ source_type__in=EXTERNAL_SOURCE_TYPE_TO_NATIVE.keys(),+ deleted=False,+ source_id__startswith="marketing-demo-",+ ).update(deleted=True)+sources: dict[str, ExternalDataSource] = {}for platform in PLATFORM_STATES:- # Only retire previous demo fixtures - never a real integration the team may have.- ExternalDataSource.objects.filter(- team=team, source_type=platform, deleted=False, source_id__startswith="marketing-demo-"- ).update(deleted=True)+ if platform in unconnected:+ continuesources[platform] = ExternalDataSource.objects.create(team=team,source_id=f"marketing-demo-{platform.lower()}",@@ -82,7 +106,9 @@ def stage_schemas_and_jobs() -> None:now = timezone.now()for platform, (schema_names, state) in PLATFORM_STATES.items():- source = sources[platform]+ source = sources.get(platform)+ if source is None: # deliberately unconnected+ continuefor schema_name in schema_names:schema_status: str | None = ExternalDataSchema.Status.COMPLETEDshould_sync = Truediff --git a/products/marketing_analytics/backend/demo/test_config.py b/products/marketing_analytics/backend/demo/test_config.pyindex fa67f40d35e4..a331d45393ee 100644--- a/products/marketing_analytics/backend/demo/test_config.py+++ b/products/marketing_analytics/backend/demo/test_config.py@@ -15,6 +15,9 @@ class TestDemoConversionGoals(BaseTest):assert goal.get("math_property"), goal["conversion_goal_id"]def test_a_revenue_shaped_goal_is_left_unflagged(self):+ # For the settings checkboxes, not for the mark_goal_* suggestions: those fire+ # only when no goal carries the flag, and this fixture keeps two that do so ROAS+ # and cost per customer stay unlocked.unflagged = [gfor g in build_conversion_goals(self.team)@@ -23,7 +26,7 @@ class TestDemoConversionGoals(BaseTest):and not g.get("counts_as_revenue")and not g.get("counts_as_customer")]- assert unflagged, "nothing drives mark_goal_as_revenue / mark_goal_as_customer"+ assert unflagged, "the revenue/customer checkboxes have no goal to turn on"def test_both_flags_are_represented(self):goals = build_conversion_goals(self.team)diff --git a/products/marketing_analytics/backend/demo/test_health.py b/products/marketing_analytics/backend/demo/test_health.pynew file mode 100644index 000000000000..3735f58907f2--- /dev/null+++ b/products/marketing_analytics/backend/demo/test_health.py@@ -0,0 +1,110 @@+from posthog.test.base import BaseTest++from products.marketing_analytics.backend.demo import health, warehouse+from products.marketing_analytics.backend.demo.world import CAMPAIGNS, FREE_CHANNELS+from products.marketing_analytics.backend.services.native_integrations import (+ EXTERNAL_SOURCE_TYPE_TO_NATIVE,+ NATIVE_TO_KEY,+ lookup_alias,+)+from products.warehouse_sources.backend.facade.models import ExternalDataSource++PAID_MEDIUMS = frozenset({"cpc", "cpm", "cpv", "cpa", "ppc", "retargeting"})+++def _organic_only_platforms_in_fixture() -> frozenset[str]:+ """Sourceless native platforms the free channels name via utm_source, sending no paid traffic.++ Both halves matter. A connected platform never reaches `events_only` however its traffic+ is tagged — Meta and LinkedIn also send organic channels and belong nowhere near this set.+ And one paid channel stops the gate suppressing, which makes it Reddit's case, not+ Pinterest's.+ """+ by_platform: dict[str, list[str | None]] = {}+ for source_type, native in EXTERNAL_SOURCE_TYPE_TO_NATIVE.items():+ if source_type in health.PLATFORM_STATES and source_type not in health.UNCONNECTED_PLATFORMS:+ continue+ key = NATIVE_TO_KEY[native]+ mediums = [c.utm_medium for c in FREE_CHANNELS if lookup_alias(c.utm_source or "") == key]+ if mediums:+ by_platform[source_type] = mediums+ return frozenset(+ source_type+ for source_type, mediums in by_platform.items()+ if all(medium and medium not in PAID_MEDIUMS for medium in mediums)+ )+++class TestUnconnectedPlatforms(BaseTest):+ def test_unconnected_platforms_get_no_source(self):+ sources = health.create_sources(self.team)+ for platform in health.UNCONNECTED_PLATFORMS:+ assert platform not in sources+ assert sources, "every platform was skipped"++ def test_connect_all_creates_every_source(self):+ sources = health.create_sources(self.team, unconnected=frozenset())+ assert set(sources) == set(health.PLATFORM_STATES)++ def test_reseeding_retires_a_source_a_previous_run_left_behind(self):+ platform = next(iter(health.UNCONNECTED_PLATFORMS))+ health.create_sources(self.team, unconnected=frozenset())+ health.create_sources(self.team)+ assert not ExternalDataSource.objects.filter(team=self.team, source_type=platform, deleted=False).exists()++ def test_reseeding_retires_a_dropped_platform_but_keeps_real_integrations(self):+ # A platform removed from PLATFORM_STATES (moved to organic-only traffic) can still+ # have a live demo source from an earlier run when it was connected. It must be+ # retired, or the diagnostic keeps calling it connected and it never reaches+ # events_only — while a real integration the team owns stays untouched.+ ExternalDataSource.objects.create(+ team=self.team,+ source_id="marketing-demo-pinterestads",+ connection_id="marketing-demo-pinterestads",+ status=ExternalDataSource.Status.COMPLETED,+ source_type="PinterestAds",+ prefix="",+ )+ real = ExternalDataSource.objects.create(+ team=self.team,+ source_id="real-pinterest-integration",+ connection_id="real-pinterest-integration",+ status=ExternalDataSource.Status.COMPLETED,+ source_type="PinterestAds",+ prefix="",+ )+ health.create_sources(self.team)+ live_ids = set(+ ExternalDataSource.objects.filter(team=self.team, source_type="PinterestAds", deleted=False).values_list(+ "id", flat=True+ )+ )+ assert live_ids == {real.id}++ def test_every_unconnected_platform_still_has_traffic(self):+ # No traffic means no events, and no events means no `events_only` — the+ # platform just disappears instead of asking to be connected.+ for platform in health.UNCONNECTED_PLATFORMS:+ assert any(c.platform == platform and c.daily_sessions > 0 for c in CAMPAIGNS), platform++ def test_organic_only_platforms_match_the_channels_the_fixture_actually_sends(self):+ # Derived from the channel list rather than spot-checked, so the constant can't be+ # emptied or fall behind a newly added organic channel — either way the summary's+ # events_only count would go quietly wrong.+ assert health.ORGANIC_ONLY_PLATFORMS == _organic_only_platforms_in_fixture()++ def test_organic_only_platforms_stay_out_of_the_staged_tables(self):+ # Being absent from both is what keeps `--connect-all` from connecting them and+ # erasing the suppressed half of the gate.+ for platform in health.ORGANIC_ONLY_PLATFORMS:+ assert platform not in health.PLATFORM_STATES, platform+ assert platform not in warehouse.NATIVE_SPECS, platform++ def test_organic_only_platforms_are_never_also_staged_as_unconnected(self):+ # Both sets feed the dry-run summary's events_only count; an overlap would+ # double-count and mean a platform is claimed to be organic-only and paid at once.+ assert not (health.ORGANIC_ONLY_PLATFORMS & health.UNCONNECTED_PLATFORMS)++ def test_cost_tables_are_only_built_for_connected_platforms(self):+ sources = health.create_sources(self.team)+ assert not (set(warehouse.NATIVE_SPECS) - set(sources) - health.UNCONNECTED_PLATFORMS)diff --git a/products/marketing_analytics/backend/demo/warehouse.py b/products/marketing_analytics/backend/demo/warehouse.pyindex 1c8528269ad3..11b0c0161012 100644--- a/products/marketing_analytics/backend/demo/warehouse.py+++ b/products/marketing_analytics/backend/demo/warehouse.py@@ -553,7 +553,6 @@ NATIVE_SPECS: dict[str, tuple[str, str, dict[str, dict[str, str]]]] = {"BingAds": ("build_bing", "bingads", BING_COLUMNS),"LinkedinAds": ("build_linkedin", "linkedinads", LINKEDIN_COLUMNS),"RedditAds": ("build_reddit", "redditads", REDDIT_COLUMNS),- "PinterestAds": ("build_pinterest", "pinterestads", PINTEREST_COLUMNS),"SnapchatAds": ("build_snapchat", "snapchatads", SNAPCHAT_COLUMNS),"TikTokAds": ("build_tiktok", "tiktokads", TIKTOK_COLUMNS),}diff --git a/products/marketing_analytics/backend/demo/world.py b/products/marketing_analytics/backend/demo/world.pyindex 82f9cff4234b..3fd140fff3ee 100644--- a/products/marketing_analytics/backend/demo/world.py+++ b/products/marketing_analytics/backend/demo/world.py@@ -373,23 +373,6 @@ CAMPAIGNS: tuple[DemoCampaign, ...] = (purchase_rate=0.01,scenario="Reddit: micros + cents formats",),- # --- Pinterest Ads (total_impression / spend_in_dollar columns) ---- DemoCampaign(- platform="PinterestAds",- campaign_id="2001",- name="pin_inspiration",- daily_cost=22.0,- daily_impressions=8800,- daily_clicks=95,- daily_sessions=14,- utm_source="pinterest",- utm_campaign="pin_inspiration",- utm_medium="paid-social",- referring_domain="pinterest.com",- signup_rate=0.04,- purchase_rate=0.012,- scenario="Pinterest: dollar spend + micro-dollar checkout value",- ),# --- Snapchat Ads (swipes as clicks, spend in micros; source in error state) ---DemoCampaign(platform="SnapchatAds",@@ -657,6 +640,20 @@ FREE_CHANNELS: tuple[DemoFreeChannel, ...] = (purchase_rate=0.005,scenario="Organic page posts under an alias of Meta Ads",),+ # Pinterest is unconnected and its traffic is entirely organic, so the paid gate has+ # positive evidence and connect_source stays silent. Reddit is the mirror: also+ # unconnected, but its campaign is paid, so there the suggestion is right.+ DemoFreeChannel(+ key="pinterest_organic",+ daily_sessions=14,+ referring_domain="pinterest.com",+ utm_source="pinterest",+ utm_medium="social",+ utm_campaign="pin_inspiration",+ signup_rate=0.04,+ purchase_rate=0.012,+ scenario="Unconnected platform with organic-only traffic: connect_source suppressed",+ ),DemoFreeChannel(key="youtube_kol",daily_sessions=10,@@ -683,17 +680,6 @@ FREE_CHANNELS: tuple[DemoFreeChannel, ...] = ()# Sources with cost rows written to the warehouse (must stay in sync with health.py).-NATIVE_PLATFORMS_WITH_DATA: tuple[str, ...] = (- "GoogleAds",- "MetaAds",- "BingAds",- "LinkedinAds",- "RedditAds",- "PinterestAds",- "SnapchatAds",- "TikTokAds",-)-BIGQUERY_SOURCE_LABEL = "demo_partner"EVENT_SIGNUP = "user signed up"diff --git a/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.pyindex b14e242a5a96..250a88d2c7b5 100644--- a/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py+++ b/products/marketing_analytics/backend/management/commands/generate_marketing_demo_data.py@@ -60,6 +60,14 @@ class Command(BaseCommand):parser.add_argument("--dry-run", action="store_true", help="Print the plan without writing anything.")parser.add_argument("--skip-events", action="store_true", help="Skip event generation (config/tables only).")parser.add_argument("--skip-flags", action="store_true", help="Skip enabling feature flags.")+ parser.add_argument(+ "--connect-all",+ action="store_true",+ help=(+ "Connect every staged ad platform, trading the connect_source case for full cost-table "+ "coverage. Organic-only platforms stay unconnected — they draw no suggestion either way."+ ),+ )def handle(self, *args: Any, **options: Any) -> None:# Local-dev only: this seeder persists the deployment's OBJECT_STORAGE_*@@ -83,7 +91,7 @@ class Command(BaseCommand):now = timezone.now()if options["dry_run"]:- self._print_plan(days_past, scale)+ self._print_plan(days_past, scale, connect_all=options["connect_all"])return# Ahead of the event write: the per-table check in `register_table` fires too late to keep a@@ -106,7 +114,9 @@ class Command(BaseCommand):builder = warehouse.CostTableBuilder(seed=options["seed"], days_past=days_past, now=now, out_dir=out_dir)self.stdout.write("Creating warehouse sources and staging Integration health states...")- sources = health.create_sources(team)+ sources = health.create_sources(+ team, unconnected=frozenset() if options["connect_all"] else health.UNCONNECTED_PLATFORMS+ )credential = get_or_create_datawarehouse_credential(team_id=team.pk,access_key=OBJECT_STORAGE_ACCESS_KEY_ID,@@ -116,6 +126,8 @@ class Command(BaseCommand):self.stdout.write("Uploading cost tables for all native platforms...")table_map: dict[tuple[str, str], Any] = {}for platform, (builder_method, prefix, columns_by_schema) in warehouse.NATIVE_SPECS.items():+ if platform not in sources: # unconnected: spend with nowhere to hang it+ continuefor schema_name, csv_path in getattr(builder, builder_method)().items():registered = warehouse.register_table(team,@@ -198,15 +210,30 @@ class Command(BaseCommand):"Kafka delivery is async: give ClickHouse a minute before expecting all events in the dashboard.")- def _print_plan(self, days_past: int, scale: float) -> None:+ def _print_plan(self, days_past: int, scale: float, *, connect_all: bool) -> None:daily_sessions = sum(c.daily_sessions for c in CAMPAIGNS) + sum(c.daily_sessions for c in FREE_CHANNELS)self.stdout.write(f"Would generate ~{round(daily_sessions * scale)} sessions/day for {days_past} days:")for campaign in CAMPAIGNS:self.stdout.write(f" [{campaign.platform}] {campaign.name}: {campaign.scenario or 'traffic'}")for channel in FREE_CHANNELS:self.stdout.write(f" [free] {channel.key}: {channel.scenario or 'traffic'}")- native_tables = sum(len(columns) for _method, _prefix, columns in warehouse.NATIVE_SPECS.values())+ # Mirror the real run's source of truth so the summary matches what --connect-all creates.+ unconnected = frozenset() if connect_all else health.UNCONNECTED_PLATFORMS+ native_tables = sum(+ len(columns)+ for platform, (_method, _prefix, columns) in warehouse.NATIVE_SPECS.items()+ if platform not in unconnected+ )+ connected = len(health.PLATFORM_STATES) - len(unconnected)+ # A platform reaches events_only whenever it has no source and its utm_source+ # matches, so the organic-only ones count too even though `--connect-all` never+ # touches them. Only the paid half draws connect_source; the gate suppresses the rest.+ drawing = ", ".join(sorted(unconnected)) or "none"+ suppressed = ", ".join(sorted(health.ORGANIC_ONLY_PLATFORMS)) or "none"+ events_only = len(unconnected) + len(health.ORGANIC_ONLY_PLATFORMS)self.stdout.write(- f"Plus: health fixtures for {len(warehouse.NATIVE_SPECS)} platforms, "- f"{native_tables + 2} warehouse tables, 6 conversion goals, flags."+ f"Plus: health fixtures for {connected} connected platforms, "+ f"{events_only} in events_only ({drawing} draw connect_source; "+ f"{suppressed} organic-only, suppressed by the paid gate), "+ f"{native_tables + 2} warehouse tables, conversion goals, flags.")