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.

perf(marketing-analytics): let callers inject attribution health into the mapping suggester (#78057)

Javier Bahamondescea25763c36a
diff --git a/products/marketing_analytics/backend/services/mapping_suggester.py b/products/marketing_analytics/backend/services/mapping_suggester.py
index 0e4357b7cfa8..d53c8f9fbd0b 100644
--- a/products/marketing_analytics/backend/services/mapping_suggester.py
+++ b/products/marketing_analytics/backend/services/mapping_suggester.py
@@ -16,7 +16,11 @@ from posthog.schema import NativeMarketingSource
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
-from products.marketing_analytics.backend.services.attribution_health import UnmatchedUtmSample, get_attribution_health
+from products.marketing_analytics.backend.services.attribution_health import (
+ AttributionHealthResponse,
+ UnmatchedUtmSample,
+ get_attribution_health,
+)
from products.marketing_analytics.backend.services.native_integrations import (
NATIVE_TO_KEY,
NativeIntegration,
@@ -108,13 +112,22 @@ async def suggest_utm_mappings(
min_event_count: int = DEFAULT_MIN_EVENT_COUNT,
max_per_integration: int = MAX_SUGGESTIONS_PER_INTEGRATION,
lookback_days: int = 90,
+ attribution: AttributionHealthResponse | None = None,
) -> UtmMappingSuggestionsResponse:
"""Detect unmatched utm_source values and propose target integrations.
`lookback_days` defaults to 90 (vs attribution_health's 7) to catch typo'd or
one-off values worth mapping; widen further for catalog-style audits.
+
+ `attribution` lets a caller that already ran `get_attribution_health` hand the
+ result in rather than paying for the same ClickHouse aggregation twice — the
+ setup plan needs both. `lookback_days` is ignored when it's supplied: the
+ reported window comes off the response so it can never disagree with the data
+ the suggestions were actually derived from.
"""
- attribution = await get_attribution_health(team, lookback_days=lookback_days)
+ if attribution is None:
+ attribution = await get_attribution_health(team, lookback_days=lookback_days)
+ lookback_days = attribution.lookback_days
current_mappings = await _read_current_mappings(team)
notes: list[str] = []
diff --git a/products/marketing_analytics/backend/services/test_mapping_suggester.py b/products/marketing_analytics/backend/services/test_mapping_suggester.py
index 132a818ea723..0fcbfc206a3c 100644
--- a/products/marketing_analytics/backend/services/test_mapping_suggester.py
+++ b/products/marketing_analytics/backend/services/test_mapping_suggester.py
@@ -158,3 +158,47 @@ class TestSuggestUtmMappings(APIBaseTest):
raw_values = [s.raw_utm_source for s in response.source_suggestions]
assert raw_values.count("paidsocial") == 1
assert response.source_suggestions[0].suggested_target == "meta_ads"
+
+ @pytest.mark.asyncio
+ async def test_injected_attribution_skips_the_internal_query(self):
+ # The setup plan needs attribution health for its own readiness block, so it
+ # hands the result in rather than paying for the aggregation twice.
+ sample = _sample("facebook_paid", 120, "meta_ads")
+ injected = AttributionHealthResponse(
+ lookback_days=90,
+ integrations=[_entry_with_samples("meta_ads", [sample])],
+ total_events_with_utm=120,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=120,
+ sample_globally_unmatched=[sample],
+ )
+
+ response = await suggest_utm_mappings(self.team, attribution=injected)
+
+ self.mock_attribution.assert_not_called()
+ assert [s.raw_utm_source for s in response.source_suggestions] == ["facebook_paid"]
+
+ @pytest.mark.asyncio
+ async def test_injected_attribution_window_wins_over_the_argument(self):
+ # Reporting the caller's `lookback_days` would misdescribe data derived from a
+ # different window, so the reported window comes off the injected response.
+ injected = AttributionHealthResponse(
+ lookback_days=7,
+ integrations=[],
+ total_events_with_utm=0,
+ total_events_matched_to_any_integration=0,
+ total_events_unmatched=0,
+ sample_globally_unmatched=[],
+ )
+
+ response = await suggest_utm_mappings(self.team, lookback_days=365, attribution=injected)
+
+ assert response.lookback_days_used == 7
+
+ @pytest.mark.asyncio
+ async def test_runs_its_own_query_when_attribution_is_absent(self):
+ response = await suggest_utm_mappings(self.team, lookback_days=45)
+
+ self.mock_attribution.assert_awaited_once_with(self.team, lookback_days=45)
+ # Still reported off the response, which the mock pins at 30.
+ assert response.lookback_days_used == 30