: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
refactor(marketing-analytics): extract UTM matching primitives from utm_audit (#78056)
Javier Bahamondes60166e40997d
diff --git a/products/marketing_analytics/backend/services/native_integrations.py b/products/marketing_analytics/backend/services/native_integrations.pyindex 7e1a90359c59..f84ad35c42dd 100644--- a/products/marketing_analytics/backend/services/native_integrations.py+++ b/products/marketing_analytics/backend/services/native_integrations.py@@ -76,6 +76,40 @@ def normalize(value: str) -> str:return "".join(c.lower() for c in value if c.isalnum())+def primary_source_for(native: NativeMarketingSource) -> str | None:+ """The `source_name` an integration's adapter emits ('google', 'meta').++ Lazy import for the same reason as `_build_canonical_aliases`: the constants+ module pulls in services indirectly during Django app boot.+ """+ from products.marketing_analytics.backend.hogql_queries.constants import INTEGRATION_PRIMARY_SOURCE++ primary = INTEGRATION_PRIMARY_SOURCE.get(native)+ return str(primary).lower().strip() if primary else None+++@cache+def primary_source_to_native() -> Mapping[str, NativeMarketingSource]:+ """Reverse of `INTEGRATION_PRIMARY_SOURCE`: 'google' → GOOGLE_ADS.++ Adapters emit `source_name` (the primary source), but team config is keyed by+ the PascalCase `NativeMarketingSource` value — anything crossing between the+ two needs this. Cached and read-only.+ """+ out: dict[str, NativeMarketingSource] = {}+ for native in NativeMarketingSource:+ primary = primary_source_for(native)+ if primary:+ out[primary] = native+ return MappingProxyType(out)+++def native_for_primary_source(primary_source: str) -> NativeMarketingSource | None:+ """Resolve an adapter's `source_name` back to its integration, or None if the+ value isn't a known primary source (e.g. an unmapped custom utm_source)."""+ return primary_source_to_native().get(primary_source.lower().strip())++def _build_canonical_aliases() -> dict[str, NativeIntegration]:"""Build the alias table from `INTEGRATION_DEFAULT_SOURCES` (the source of truthshared with adapters and the dashboard, so they agree on what's integrated).diff --git a/products/marketing_analytics/backend/services/test_utm_audit.py b/products/marketing_analytics/backend/services/test_utm_audit.pyindex aac53701c592..bacd4df21e6c 100644--- a/products/marketing_analytics/backend/services/test_utm_audit.py+++ b/products/marketing_analytics/backend/services/test_utm_audit.py@@ -14,16 +14,36 @@ from products.marketing_analytics.backend.services.types import ()from products.marketing_analytics.backend.services.utm_audit import (_build_all_utm_events,- _build_known_sources,_cross_reference,- _load_team_mappings,+ _make_headline,run_utm_audit,)+from products.marketing_analytics.backend.services.utm_matching import build_known_sources, load_team_mappingsNO_MAPPINGS = TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})# known_sources set populated from every integration's default utm_source values.-# Built lazily inside tests via _build_known_sources() so we don't hardcode every value.-DEFAULT_KNOWN_SOURCES: set[str] = _build_known_sources(NO_MAPPINGS)+# Built lazily inside tests via build_known_sources() so we don't hardcode every value.+DEFAULT_KNOWN_SOURCES: set[str] = build_known_sources(NO_MAPPINGS)+++class TestMakeHeadline:+ @parameterized.expand(+ [+ (UtmIssueKind.NOT_LINKED, "No pageview events found for 'brand_us'"),+ (UtmIssueKind.NAME_COLLISION, "Campaign name also used on meta"),+ (UtmIssueKind.NO_TAGGED_EVENTS, "No events tagged with utm_source='google'"),+ (UtmIssueKind.UNKNOWN_SOURCE, "No events tagged with utm_source='google'"),+ ]+ )+ def test_renders_headline_per_kind(self, kind, expected):+ assert _make_headline(kind, "google", "brand_us", ["meta"]) == expected++ def test_falls_back_for_an_unmapped_kind(self):+ # A newly added UtmIssueKind must not be able to break the audit response+ # over a cosmetic headline string.+ headline = _make_headline("some_future_kind", "google", "brand_us", []) # type: ignore[arg-type]++ assert headline == "UTM tagging issue on 'brand_us'"class TestCrossReference:@@ -96,7 +116,7 @@ class TestCrossReference:field_preferences={},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))google = next(r for r in results if r.source_name == "google")meta = next(r for r in results if r.source_name == "meta")@@ -153,7 +173,7 @@ class TestCrossReference:field_preferences={},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 1assert results[0].has_utm_events is True@@ -169,7 +189,7 @@ class TestCrossReference:field_preferences={},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 1assert results[0].has_utm_events is True@@ -185,7 +205,7 @@ class TestCrossReference:field_preferences={},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 1assert results[0].has_utm_events is True@@ -222,7 +242,7 @@ class TestCrossReferenceIssueKinds:# Mapping google→bing would break Google attribution, so ADD_SOURCE_MAPPING must not be suggested.campaigns = [Campaign("Shared Campaign", "1", "bing", 100.0, 50, 1000)]utm_events = {("shared campaign", "google"): 29}- known_sources = _build_known_sources(NO_MAPPINGS)+ known_sources = build_known_sources(NO_MAPPINGS)results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, known_sources)@@ -239,7 +259,7 @@ class TestCrossReferenceIssueKinds:# utm_source='partner_xyz' is not a default of any integration. Safe to offer ADD_SOURCE_MAPPING.campaigns = [Campaign("Brand Campaign", "1", "bing", 100.0, 50, 1000)]utm_events = {("brand campaign", "partner_xyz"): 40}- known_sources = _build_known_sources(NO_MAPPINGS)+ known_sources = build_known_sources(NO_MAPPINGS)assert "partner_xyz" not in known_sourcesresults = _cross_reference(campaigns, utm_events, NO_MAPPINGS, known_sources)@@ -301,7 +321,7 @@ class TestCrossReferenceIssueKinds:Campaign("Survey", "2", "google", 200.0, 100, 2000),]utm_events = {("survey", "google"): 29}- known_sources = _build_known_sources(NO_MAPPINGS)+ known_sources = build_known_sources(NO_MAPPINGS)results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, known_sources)google = next(r for r in results if r.source_name == "google")@@ -330,7 +350,7 @@ class TestCrossReferenceIssueKinds:("survey", "google"): 29, # Matches google's row("survey", "weird_source"): 5, # Unknown alt for bing}- known_sources = _build_known_sources(NO_MAPPINGS)+ known_sources = build_known_sources(NO_MAPPINGS)results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, known_sources)bing = next(r for r in results if r.source_name == "bing")@@ -345,7 +365,7 @@ class TestCrossReferenceIssueKinds:("brand", "unknown_partner"): 30,("brand", "yet_another"): 15,}- known_sources = _build_known_sources(NO_MAPPINGS)+ known_sources = build_known_sources(NO_MAPPINGS)results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, known_sources)issue = results[0].issues[0]@@ -363,7 +383,7 @@ class TestCrossReferenceIssueKinds:campaign_aliases={},field_preferences={},)- known_sources = _build_known_sources(mappings)+ known_sources = build_known_sources(mappings)assert "weird_source" in known_sourcesresults = _cross_reference(campaigns, utm_events, mappings, known_sources)@@ -386,7 +406,7 @@ class TestBuildKnownSources:],)def test_membership_for_default_known_sources(self, source, expected_present):- result = _build_known_sources(NO_MAPPINGS)+ result = build_known_sources(NO_MAPPINGS)assert (source in result) is expected_present@@ -397,7 +417,7 @@ class TestBuildKnownSources:field_preferences={},)- result = _build_known_sources(mappings)+ result = build_known_sources(mappings)assert "partner_blog" in resultassert "internal_source" in result@@ -422,7 +442,7 @@ class TestCrossReferenceFieldPreferences:field_preferences={"google": match_field},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 1if should_match:@@ -448,7 +468,7 @@ class TestCrossReferenceFieldPreferences:field_preferences={"google": "campaign_id", "meta": "campaign_name"},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 2google = next(r for r in results if r.source_name == "google")@@ -469,7 +489,7 @@ class TestCrossReferenceFieldPreferences:field_preferences={"google": "campaign_id"},)- results = _cross_reference(campaigns, utm_events, mappings, _build_known_sources(mappings))+ results = _cross_reference(campaigns, utm_events, mappings, build_known_sources(mappings))assert len(results) == 1assert results[0].has_utm_events is True@@ -589,7 +609,7 @@ class TestLoadTeamMappings(BaseTest):team = MagicMock()team.marketing_analytics_config = None- result = _load_team_mappings(team)+ result = load_team_mappings(team)assert result.source_to_integration == {}assert result.campaign_aliases == {}@@ -601,7 +621,7 @@ class TestLoadTeamMappings(BaseTest):self.team.marketing_analytics_config.campaign_field_preferences = {}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert result.source_to_integration == {}assert result.campaign_aliases == {}@@ -613,7 +633,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert result.source_to_integration["partner_blog"] == "google"assert result.source_to_integration["affiliate_site"] == "google"@@ -624,7 +644,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert "uppercase_source" in result.source_to_integrationassert "mixedcase" in result.source_to_integration@@ -637,7 +657,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert "partner_q1" in result.campaign_aliases["brand_campaign"]assert "brand_q1" in result.campaign_aliases["brand_campaign"]@@ -649,7 +669,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert "google_alias" in result.campaign_aliases["brand_campaign"]assert "meta_alias" in result.campaign_aliases["brand_campaign"]@@ -658,7 +678,7 @@ class TestLoadTeamMappings(BaseTest):self.team.marketing_analytics_config.campaign_name_mappings = {"GoogleAds": {"Brand Campaign": ["SomeAlias"]}}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert "brand campaign" in result.campaign_aliasesassert "somealias" in result.campaign_aliases["brand campaign"]@@ -669,7 +689,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert result.field_preferences.get("google") == "campaign_id"@@ -680,7 +700,7 @@ class TestLoadTeamMappings(BaseTest):}self.team.marketing_analytics_config.save()- result = _load_team_mappings(self.team)+ result = load_team_mappings(self.team)assert result.field_preferences.get("google") == "campaign_id"assert result.field_preferences.get("meta") == "campaign_name"@@ -694,7 +714,7 @@ class TestLoadTeamMappings(BaseTest):team = MagicMock()team.marketing_analytics_config = config- result = _load_team_mappings(team)+ result = load_team_mappings(team)assert result.field_preferences == {}@@ -721,7 +741,7 @@ class TestLoadTeamMappings(BaseTest):team = MagicMock()team.marketing_analytics_config = config- result = _load_team_mappings(team)+ result = load_team_mappings(team)assert result.source_to_integration.get("custom_source") == expected_primary_source@@ -745,8 +765,8 @@ class TestRunUtmAudit(BaseTest):impressions=impressions,)- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_returns_utm_audit_response_dataclass(self, mock_campaigns, mock_utm):mock_campaigns.return_value = []mock_utm.return_value = {}@@ -755,8 +775,8 @@ class TestRunUtmAudit(BaseTest):assert isinstance(result, UtmAuditResponse)- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_returns_zeroed_summary_when_no_campaigns(self, mock_campaigns, mock_utm):mock_campaigns.return_value = []mock_utm.return_value = {}@@ -770,8 +790,8 @@ class TestRunUtmAudit(BaseTest):assert result.results == []assert result.all_utm_events == []- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_counts_campaigns_with_and_without_issues(self, mock_campaigns, mock_utm):mock_campaigns.return_value = [self._make_campaign("good_campaign", "1", "google", spend=100.0),@@ -785,8 +805,8 @@ class TestRunUtmAudit(BaseTest):assert result.campaigns_with_issues == 1assert result.campaigns_without_issues == 1- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_sums_spend_at_risk_for_campaigns_with_issues(self, mock_campaigns, mock_utm):mock_campaigns.return_value = [self._make_campaign("no_tracking", "1", "google", spend=300.0),@@ -799,8 +819,8 @@ class TestRunUtmAudit(BaseTest):assert result.total_spend_at_risk == pytest.approx(450.0)- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_results_sorted_by_issue_count_then_spend_descending(self, mock_campaigns, mock_utm):mock_campaigns.return_value = [self._make_campaign("low_spend_bad", "1", "google", spend=50.0),@@ -816,8 +836,8 @@ class TestRunUtmAudit(BaseTest):assert result.results[1].campaign_name == "low_spend_bad"assert result.results[2].campaign_name == "good"- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_includes_all_utm_events_in_response(self, mock_campaigns, mock_utm):mock_campaigns.return_value = [self._make_campaign()]mock_utm.return_value = {@@ -829,8 +849,8 @@ class TestRunUtmAudit(BaseTest):assert len(result.all_utm_events) == 2- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_uses_team_mappings_when_resolving_sources(self, mock_campaigns, mock_utm):self.team.marketing_analytics_config.custom_source_mappings = {"GoogleAds": ["custom_blog"],@@ -845,8 +865,8 @@ class TestRunUtmAudit(BaseTest):assert result.campaigns_with_issues == 0assert result.results[0].has_utm_events is True- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_passes_date_params_to_data_fetchers(self, mock_campaigns, mock_utm):mock_campaigns.return_value = []mock_utm.return_value = {}@@ -863,8 +883,8 @@ class TestRunUtmAudit(BaseTest):assert utm_date_range.date_from_str is not Noneassert utm_date_range.date_to_str is not None- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_zero_spend_at_risk_when_all_campaigns_tracked(self, mock_campaigns, mock_utm):mock_campaigns.return_value = [self._make_campaign("campaign_a", "1", "google", spend=200.0),@@ -880,8 +900,8 @@ class TestRunUtmAudit(BaseTest):assert result.total_spend_at_risk == 0.0assert result.campaigns_with_issues == 0- @patch("products.marketing_analytics.backend.services.utm_audit._get_utm_events")- @patch("products.marketing_analytics.backend.services.utm_audit._get_campaigns_with_spend")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_utm_campaign_catalogue")+ @patch("products.marketing_analytics.backend.services.utm_audit.get_campaigns_with_spend")def test_e2e_name_collision_scenario_produces_correct_kind_and_actions(self, mock_campaigns, mock_utm):# End-to-end smoke test: same campaign name on Bing and Google, events only tagged as google.# Verifies the full run_utm_audit pipeline (known_sources building, _cross_reference,diff --git a/products/marketing_analytics/backend/services/test_utm_matching.py b/products/marketing_analytics/backend/services/test_utm_matching.pynew file mode 100644index 000000000000..49cc54a5cd22--- /dev/null+++ b/products/marketing_analytics/backend/services/test_utm_matching.py@@ -0,0 +1,241 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.hogql import ast++from products.marketing_analytics.backend.services.types import Campaign, MatchType, TeamMappings+from products.marketing_analytics.backend.services.utm_audit import get_campaigns_with_spend+from products.marketing_analytics.backend.services.utm_matching import (+ CampaignMatch,+ build_campaign_lookup,+ build_source_lookup,+ get_match_field,+ get_match_value,+ load_team_mappings,+ resolve_source,+)++NO_MAPPINGS = TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})+++def _campaign(name: str, campaign_id: str, source: str, spend: float = 100.0) -> Campaign:+ return Campaign(+ campaign_name=name,+ campaign_id=campaign_id,+ source_name=source,+ spend=spend,+ clicks=0,+ impressions=0,+ )+++class TestGetMatchField:+ def test_defaults_to_campaign_name(self):+ assert get_match_field("google", NO_MAPPINGS) == "campaign_name"++ def test_reads_preference_for_source(self):+ mappings = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )+ assert get_match_field("google", mappings) == "campaign_id"+ # A preference for one integration must not leak to another.+ assert get_match_field("meta", mappings) == "campaign_name"++ def test_normalizes_source_name(self):+ mappings = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )+ assert get_match_field(" Google ", mappings) == "campaign_id"+++class TestGetMatchValue:+ def test_returns_lowercased_name_by_default(self):+ assert get_match_value(_campaign("Brand_US", "12345", "google"), NO_MAPPINGS) == "brand_us"++ def test_returns_id_when_preference_is_id(self):+ mappings = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )+ assert get_match_value(_campaign("Brand_US", "12345", "google"), mappings) == "12345"+++class TestResolveSource:+ def test_resolves_canonical_alias(self):+ assert resolve_source("facebook", NO_MAPPINGS) == "meta"++ def test_custom_mapping_wins_over_canonical(self):+ mappings = TeamMappings(source_to_integration={"facebook": "google"}, campaign_aliases={}, field_preferences={})+ assert resolve_source("facebook", mappings) == "google"++ def test_passes_through_unknown_value(self):+ # Callers distinguish "resolved" from "passed through" via build_known_sources.+ assert resolve_source("partner_blog", NO_MAPPINGS) == "partner_blog"+++class TestBuildCampaignLookup:+ def test_maps_match_value_to_campaign_as_auto(self):+ lookup = build_campaign_lookup([_campaign("Brand_US", "1", "google")], NO_MAPPINGS)++ assert lookup == {"brand_us": CampaignMatch("Brand_US", MatchType.AUTO)}++ def test_keys_on_id_when_preference_is_id(self):+ mappings = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )++ lookup = build_campaign_lookup([_campaign("Brand_US", "12345", "google")], mappings)++ assert lookup == {"12345": CampaignMatch("Brand_US", MatchType.AUTO)}++ def test_includes_aliases_as_mapped(self):+ mappings = TeamMappings(+ source_to_integration={},+ campaign_aliases={"brand_us": {"brand-us-typo", "brnd_us"}},+ field_preferences={},+ )++ lookup = build_campaign_lookup([_campaign("Brand_US", "1", "google")], mappings)++ assert lookup["brand_us"].match_type == MatchType.AUTO+ assert lookup["brand-us-typo"] == CampaignMatch("Brand_US", MatchType.MAPPED)+ assert lookup["brnd_us"] == CampaignMatch("Brand_US", MatchType.MAPPED)++ def test_first_campaign_wins_on_collision(self):+ # Cross-platform name collisions are detected separately by the audit's+ # second pass — this lookup is deliberately last-write-loses.+ lookup = build_campaign_lookup(+ [_campaign("brand", "1", "google"), _campaign("brand", "2", "meta")],+ NO_MAPPINGS,+ )++ assert len(lookup) == 1+ assert lookup["brand"].match_type == MatchType.AUTO++ def test_empty_campaigns_yields_empty_lookup(self):+ assert build_campaign_lookup([], NO_MAPPINGS) == {}+++class TestBuildSourceLookup:+ def test_primary_sources_are_auto(self):+ lookup = build_source_lookup([_campaign("c", "1", "google")], NO_MAPPINGS)++ assert lookup == {"google": MatchType.AUTO}++ def test_custom_mapping_to_spending_integration_is_mapped(self):+ mappings = TeamMappings(+ source_to_integration={"partner_blog": "google"}, campaign_aliases={}, field_preferences={}+ )++ lookup = build_source_lookup([_campaign("c", "1", "google")], mappings)++ assert lookup["partner_blog"] == MatchType.MAPPED++ def test_custom_mapping_to_integration_without_spend_is_absent(self):+ # Nothing to attribute to, so the mapping must not read as "matched".+ mappings = TeamMappings(+ source_to_integration={"partner_blog": "meta"}, campaign_aliases={}, field_preferences={}+ )++ lookup = build_source_lookup([_campaign("c", "1", "google")], mappings)++ assert "partner_blog" not in lookup+++class TestLoadTeamMappings(BaseTest):+ """`self.team` is rebuilt from `setUpTestData` per test, but the config object it+ caches is not reliably reset between tests, so every test here writes the full+ config it expects rather than assuming a pristine one.+ """++ def _write_config(+ self,+ *,+ custom_source_mappings: dict | None = None,+ campaign_name_mappings: dict | None = None,+ campaign_field_preferences: dict | None = None,+ ):+ config = self.team.marketing_analytics_config+ config.custom_source_mappings = custom_source_mappings or {}+ config.campaign_name_mappings = campaign_name_mappings or {}+ config.campaign_field_preferences = campaign_field_preferences or {}+ config.save()+ return config++ def test_returns_empty_mappings_when_config_is_bare(self):+ self._write_config()++ mappings = load_team_mappings(self.team)++ assert mappings.source_to_integration == {}+ assert mappings.campaign_aliases == {}+ assert mappings.field_preferences == {}++ def test_flattens_custom_source_mappings_to_primary_source(self):+ self._write_config(custom_source_mappings={"GoogleAds": ["partner_blog", "Affiliate"]})++ mappings = load_team_mappings(self.team)++ assert mappings.source_to_integration == {"partner_blog": "google", "affiliate": "google"}++ def test_flattens_campaign_aliases_dropping_the_integration(self):+ self._write_config(campaign_name_mappings={"GoogleAds": {"Brand_US": ["brnd_us", "BRAND-US"]}})++ mappings = load_team_mappings(self.team)++ assert mappings.campaign_aliases == {"brand_us": {"brnd_us", "brand-us"}}++ def test_keys_field_preferences_by_primary_source(self):+ self._write_config(campaign_field_preferences={"GoogleAds": {"match_field": "campaign_id"}})++ mappings = load_team_mappings(self.team)++ # Keyed by 'google', not 'GoogleAds', so campaign rows can be looked up by source_name.+ assert mappings.field_preferences == {"google": "campaign_id"}++ def test_ignores_unknown_integration_types(self):+ config = self._write_config(campaign_field_preferences={"GoogleAds": {"match_field": "campaign_id"}})+ # Bypass the model validator to simulate config written by an older release.+ config._campaign_field_preferences["NotARealPlatform"] = {"match_field": "campaign_id"}++ mappings = load_team_mappings(self.team)++ assert mappings.field_preferences == {"google": "campaign_id"}+++class TestCampaignsQueryShape(BaseTest):+ """Pins the column contract the campaign-field suggester depends on.++ `campaign_field_suggester` compares the utm_campaign catalogue against BOTH+ `campaign_name` and `campaign_id`, which only works because this query selects+ the two raw columns. If it were ever changed to select `match_key` instead, the+ suggester would silently compare a field to itself and always report a tie.+ """++ @patch("products.marketing_analytics.backend.services.utm_audit.execute_hogql_query")+ @patch("products.marketing_analytics.backend.services.utm_audit.MarketingSourceFactory")+ def test_selects_campaign_and_id_as_separate_raw_columns(self, mock_factory_cls, mock_execute):+ mock_factory = mock_factory_cls.return_value+ mock_factory.get_valid_adapters.return_value = [object()]+ mock_factory.build_union_query_ast.return_value = ast.SelectQuery(select=[])+ mock_execute.return_value.results = []++ get_campaigns_with_spend(self.team, self._date_range())++ query = mock_execute.call_args[0][0]+ selected_fields = [expr.chain[0] for expr in query.select if isinstance(expr, ast.Field)]+ assert selected_fields == ["campaign", "id", "source"]+ assert "match_key" not in selected_fields++ def _date_range(self):+ from django.utils import timezone++ from posthog.schema import DateRange++ from posthog.hogql_queries.utils.query_date_range import QueryDateRange++ return QueryDateRange(+ date_range=DateRange(date_from="-30d", date_to=None),+ team=self.team,+ interval=None,+ now=timezone.now(),+ )diff --git a/products/marketing_analytics/backend/services/utm_audit.py b/products/marketing_analytics/backend/services/utm_audit.pyindex 3990a7df5a93..8878f53bde66 100644--- a/products/marketing_analytics/backend/services/utm_audit.py+++ b/products/marketing_analytics/backend/services/utm_audit.py@@ -1,11 +1,10 @@from dataclasses import dataclass-from functools import cachefrom django.utils import timezoneimport structlog-from posthog.schema import DateRange, NativeMarketingSource+from posthog.schema import DateRangefrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query@@ -14,19 +13,10 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import DEFAULT_CURRENCY, Teamfrom posthog.models.user import User+from posthog.sync import database_sync_to_asyncfrom products.marketing_analytics.backend.hogql_queries.adapters.base import QueryContextfrom products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory-from products.marketing_analytics.backend.hogql_queries.constants import (- INTEGRATION_DEFAULT_SOURCES,- INTEGRATION_PRIMARY_SOURCE,-)-from products.marketing_analytics.backend.services.native_integrations import (- KEY_TO_NATIVE,- canonical_source_aliases,- iter_custom_source_mappings,- normalize,-)from products.marketing_analytics.backend.services.types import (AlternativeSource,Campaign,@@ -40,92 +30,19 @@ from products.marketing_analytics.backend.services.types import (UtmIssueKind,UtmIssueSeverity,)+from products.marketing_analytics.backend.services.utm_matching import (+ build_campaign_lookup,+ build_known_sources,+ build_source_lookup,+ get_match_field,+ get_match_value,+ load_team_mappings,+ resolve_source,+)logger = structlog.get_logger(__name__)-def _load_team_mappings(team: Team) -> TeamMappings:- """Load custom source mappings and campaign name mappings from team config."""- config = team.marketing_analytics_config- if config is None:- return TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})-- # Build source mapping: custom utm_source values -> the integration's primary source.- # e.g. custom_source_mappings = {"GoogleAds": ["partner_blog", "affiliate"]} →- # {"partner_blog": "google", "affiliate": "google"} because the GoogleAds adapter- # uses "google" as `source_name`. The (target_key, raw_value) pairs come from- # `iter_custom_source_mappings` so the enum-resolution rules stay shared with- # `native_integrations.build_combined_alias_map`.- source_to_integration: dict[str, str] = {}- for target_key, raw_value in iter_custom_source_mappings(config.custom_source_mappings):- native = KEY_TO_NATIVE[target_key]- primary = INTEGRATION_PRIMARY_SOURCE.get(native)- if not primary:- # Integration without a registered primary source (e.g. shipped before- # INTEGRATION_PRIMARY_SOURCE was updated). Drop it, but log the gap.- logger.warning(- "utm_audit_dropping_custom_mapping_no_primary_source",- team_id=team.id,- integration=native.value,- raw_value=raw_value,- )- continue- source_to_integration[raw_value.lower().strip()] = str(primary).lower().strip()-- # Build campaign aliases: clean_campaign_name -> set of raw utm values- # e.g. campaign_name_mappings = {"GoogleAds": {"brand_campaign": ["partner_q1", "brand_q1"]}}- campaign_aliases: dict[str, set[str]] = {}- campaign_name_mappings = config.campaign_name_mappings or {}- for _integration_type, campaign_map in campaign_name_mappings.items():- for clean_name, raw_values in campaign_map.items():- clean_lower = clean_name.lower().strip()- if clean_lower not in campaign_aliases:- campaign_aliases[clean_lower] = set()- for raw_value in raw_values:- campaign_aliases[clean_lower].add(raw_value.lower().strip())-- # Build field preferences: lowercase source_name -> match field- # Reverse map: primary_source ("google") -> integration_type ("GoogleAds")- primary_to_integration: dict[str, str] = {}- for native_source in NativeMarketingSource:- primary = INTEGRATION_PRIMARY_SOURCE.get(native_source)- if primary:- primary_to_integration[str(primary).lower().strip()] = native_source.value-- field_preferences: dict[str, str] = {}- campaign_field_prefs = config.campaign_field_preferences or {}- for integration_type, prefs in campaign_field_prefs.items():- match_field = prefs.get("match_field", "campaign_name")- try:- native_source = NativeMarketingSource(integration_type)- primary = INTEGRATION_PRIMARY_SOURCE.get(native_source)- if primary:- field_preferences[str(primary).lower().strip()] = match_field- except ValueError:- pass-- return TeamMappings(- source_to_integration=source_to_integration,- campaign_aliases=campaign_aliases,- field_preferences=field_preferences,- )---def _build_known_sources(mappings: TeamMappings) -> set[str]:- """Build the set of utm_source values claimed by any integration (default or custom).-- Used to decide whether an unmatched utm_source is safe to suggest as a mapping —- if it's already claimed by another integration, mapping it would break that one.- """- known: set[str] = set()- for sources in INTEGRATION_DEFAULT_SOURCES.values():- for source in sources:- known.add(source.lower().strip())- # Custom mappings already flattened to source -> primary_source- known.update(mappings.source_to_integration.keys())- return known--def run_utm_audit(team: Team,date_from: str = "-30d",@@ -147,11 +64,11 @@ def run_utm_audit(now=timezone.now(),)- mappings = _load_team_mappings(team)- known_sources = _build_known_sources(mappings)+ mappings = load_team_mappings(team)+ known_sources = build_known_sources(mappings)- campaigns = _get_campaigns_with_spend(team, date_range, user=user)- utm_events = _get_utm_events(team, date_range, user=user)+ campaigns = get_campaigns_with_spend(team, date_range, user=user)+ utm_events = get_utm_campaign_catalogue(team, date_range, user=user)results = _cross_reference(campaigns, utm_events, mappings, known_sources) if campaigns else []all_utm = _build_all_utm_events(campaigns, utm_events, mappings)@@ -168,7 +85,12 @@ def run_utm_audit()-def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> list[Campaign]:+# The audit is sync (it reads team config through the ORM and runs HogQL inline), but the+# async services — `marketing_diagnostic`, `setup_plan` — gather it alongside coroutines.+run_utm_audit_async = database_sync_to_async(run_utm_audit)+++def get_campaigns_with_spend(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> list[Campaign]:"""Get all campaigns with spend from marketing integrations."""context = QueryContext(date_range=date_range,@@ -245,7 +167,9 @@ def _get_campaigns_with_spend(team: Team, date_range: QueryDateRange, *, user: Ureturn campaigns-def _get_utm_events(team: Team, date_range: QueryDateRange, *, user: User | None = None) -> dict[tuple[str, str], int]:+def get_utm_campaign_catalogue(+ team: Team, date_range: QueryDateRange, *, user: User | None = None+) -> dict[tuple[str, str], int]:"""Get distinct utm_campaign + utm_source combinations from pageview events.Returns a dict mapping (campaign, source) -> event_count.@@ -286,37 +210,6 @@ def _get_utm_events(team: Team, date_range: QueryDateRange, *, user: User | Nonereturn utm_map-@cache-def _default_alias_to_primary() -> dict[str, str]:- """Normalized default utm_source aliases ('facebook', 'adwords') -> the- integration's primary source name ('meta', 'google')."""- out: dict[str, str] = {}- for alias, target_key in canonical_source_aliases().items():- primary = INTEGRATION_PRIMARY_SOURCE.get(KEY_TO_NATIVE[target_key])- if primary:- out[alias] = str(primary).lower().strip()- return out---def _resolve_source(utm_source: str, mappings: TeamMappings) -> str:- """Resolve a utm_source to its integration's primary source: team custom- mappings first (they win, matching `build_combined_alias_map`), then the- platform default aliases so e.g. 'facebook' resolves to 'meta'."""- custom = mappings.source_to_integration.get(utm_source)- if custom is not None:- return custom- return _default_alias_to_primary().get(normalize(utm_source), utm_source)---def _get_match_value(campaign: Campaign, mappings: TeamMappings) -> str:- """Get the campaign value to match against utm_campaign, based on field preference."""- source_name_lower = campaign.source_name.lower().strip()- match_field = mappings.field_preferences.get(source_name_lower, "campaign_name")- if match_field == "campaign_id":- return campaign.campaign_id.lower().strip()- return campaign.campaign_name.lower().strip()--def _build_all_utm_events(campaigns: list[Campaign],utm_events: dict[tuple[str, str], int],@@ -326,37 +219,18 @@ def _build_all_utm_events(Build a list of all UTM events with their match status against campaigns.Uses pre-computed lookup dicts for O(1) matching per UTM event instead of O(C)."""- # Pre-compute campaign lookup: match_value -> (campaign_name, match_type="auto")- # and alias lookup: alias -> (campaign_name, match_type="mapped")- campaign_lookup: dict[str, tuple[str, str]] = {}- for campaign in campaigns:- match_value = _get_match_value(campaign, mappings)- campaign_name_lower = campaign.campaign_name.lower().strip()- if match_value not in campaign_lookup:- campaign_lookup[match_value] = (campaign.campaign_name, MatchType.AUTO)- for alias in mappings.campaign_aliases.get(campaign_name_lower, set()):- if alias not in campaign_lookup:- campaign_lookup[alias] = (campaign.campaign_name, MatchType.MAPPED)-- # Pre-compute source lookup: source_name -> match_type- source_lookup: dict[str, str] = {}- for campaign in campaigns:- source_name_lower = campaign.source_name.lower().strip()- if source_name_lower not in source_lookup:- source_lookup[source_name_lower] = MatchType.AUTO- for custom_source, primary_source in mappings.source_to_integration.items():- if primary_source in source_lookup and custom_source not in source_lookup:- source_lookup[custom_source] = MatchType.MAPPED+ campaign_lookup = build_campaign_lookup(campaigns, mappings)+ source_lookup = build_source_lookup(campaigns, mappings)result: list[UtmEvent] = []for (utm_campaign, utm_source), count in utm_events.items():campaign_entry = campaign_lookup.get(utm_campaign)- campaign_match = campaign_entry[1] if campaign_entry else MatchType.NONE- matched_campaign_name = campaign_entry[0] if campaign_entry else None+ campaign_match = campaign_entry.match_type if campaign_entry else MatchType.NONE+ matched_campaign_name = campaign_entry.campaign_name if campaign_entry else Nonesource_match = source_lookup.get(utm_source, MatchType.NONE)if source_match == MatchType.NONE:- resolved = _resolve_source(utm_source, mappings)+ resolved = resolve_source(utm_source, mappings)if resolved in source_lookup:source_match = MatchType.MAPPED if utm_source in mappings.source_to_integration else MatchType.AUTO@@ -400,8 +274,8 @@ def _compute_campaign_stats("""Aggregate UTM events for a campaign and separate exact-source vs alternative-source counts."""campaign_name_lower = campaign.campaign_name.lower().strip()source_name_lower = campaign.source_name.lower().strip()- match_value = _get_match_value(campaign, mappings)- match_field = mappings.field_preferences.get(source_name_lower, "campaign_name")+ match_value = get_match_value(campaign, mappings)+ match_field = get_match_field(campaign.source_name, mappings)match_display = campaign.campaign_id if match_field == "campaign_id" else campaign.campaign_namematching_keys = {match_value}@@ -419,7 +293,7 @@ def _compute_campaign_stats(if not utm_source:missing_source_count += countcontinue- resolved_source = _resolve_source(utm_source, mappings)+ resolved_source = resolve_source(utm_source, mappings)if resolved_source == source_name_lower or utm_source == source_name_lower:exact_count += countelse:@@ -437,6 +311,7 @@ def _compute_campaign_stats(_NO_TAGGED_EVENTS_HEADLINE = "No events tagged with utm_source='{platform}'"+_FALLBACK_HEADLINE = "UTM tagging issue on '{campaign}'"_HEADLINE_BY_KIND: dict[UtmIssueKind, str] = {UtmIssueKind.NOT_LINKED: "No pageview events found for '{campaign}'",@@ -452,8 +327,11 @@ def _make_headline(kind: UtmIssueKind, platform: str, campaign: str, shared_withThe UI composes richer text from the structured `UtmIssue` fields (kind, alternative_sources,shared_with_integrations, suggested_actions) — this string is intentionally one line.++ Unknown kinds fall back rather than raising: this is a cosmetic log/fallback string, and a+ newly added `UtmIssueKind` should never be able to break the whole audit response."""- template = _HEADLINE_BY_KIND[kind]+ template = _HEADLINE_BY_KIND.get(kind, _FALLBACK_HEADLINE)return template.format(platform=platform,campaign=campaign,@@ -559,7 +437,7 @@ def _cross_reference(and build the appropriate issue."""if known_sources is None:- known_sources = _build_known_sources(mappings)+ known_sources = build_known_sources(mappings)utm_by_campaign: dict[str, list[tuple[str, int]]] = {}for (utm_campaign, utm_source), count in utm_events.items():diff --git a/products/marketing_analytics/backend/services/utm_matching.py b/products/marketing_analytics/backend/services/utm_matching.pynew file mode 100644index 000000000000..642a5a807b4c--- /dev/null+++ b/products/marketing_analytics/backend/services/utm_matching.py@@ -0,0 +1,206 @@+"""How a raw UTM value resolves to an ad-platform campaign or source.++Extracted from `utm_audit` so the audit and the setup suggesters share one+definition of "matched". Everything here is a pure function over a `TeamMappings`+snapshot plus the campaign rows an adapter emitted — no queries, no Django ORM+beyond the single config read in `load_team_mappings`.++Two vocabularies meet in this module and are easy to confuse:++- `source_name` / *primary source* — what an adapter emits on its rows ('google',+ 'meta'). Lowercase, matched against `utm_source`.+- `NativeMarketingSource` — the PascalCase enum value team config is keyed by+ ('GoogleAds'). Use `native_integrations.native_for_primary_source` to cross over.+"""++from functools import cache+from typing import Literal, NamedTuple++import structlog++from posthog.schema import NativeMarketingSource++from posthog.models.team.team import Team++from products.marketing_analytics.backend.hogql_queries.constants import INTEGRATION_DEFAULT_SOURCES+from products.marketing_analytics.backend.services.native_integrations import (+ KEY_TO_NATIVE,+ canonical_source_aliases,+ iter_custom_source_mappings,+ normalize,+ primary_source_for,+)+from products.marketing_analytics.backend.services.types import Campaign, MatchType, TeamMappings++logger = structlog.get_logger(__name__)++MatchFieldName = Literal["campaign_name", "campaign_id"]++DEFAULT_MATCH_FIELD: MatchFieldName = "campaign_name"+++class CampaignMatch(NamedTuple):+ """Why a `utm_campaign` value resolved to a platform campaign.++ `match_type` is AUTO when the raw value equals the campaign's configured match+ field, MAPPED when it only matched through `campaign_name_mappings`.+ """++ campaign_name: str+ match_type: str+++def load_team_mappings(team: Team) -> TeamMappings:+ """Load custom source mappings and campaign name mappings from team config."""+ config = team.marketing_analytics_config+ if config is None:+ return TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})++ # Build source mapping: custom utm_source values -> the integration's primary source.+ # e.g. custom_source_mappings = {"GoogleAds": ["partner_blog", "affiliate"]} →+ # {"partner_blog": "google", "affiliate": "google"} because the GoogleAds adapter+ # uses "google" as `source_name`. The (target_key, raw_value) pairs come from+ # `iter_custom_source_mappings` so the enum-resolution rules stay shared with+ # `native_integrations.build_combined_alias_map`.+ source_to_integration: dict[str, str] = {}+ for target_key, raw_value in iter_custom_source_mappings(config.custom_source_mappings):+ native = KEY_TO_NATIVE[target_key]+ primary = primary_source_for(native)+ if not primary:+ # Integration without a registered primary source (e.g. shipped before+ # INTEGRATION_PRIMARY_SOURCE was updated). Drop it, but log the gap.+ logger.warning(+ "utm_audit_dropping_custom_mapping_no_primary_source",+ team_id=team.id,+ integration=native.value,+ raw_value=raw_value,+ )+ continue+ source_to_integration[raw_value.lower().strip()] = primary++ # Build campaign aliases: clean_campaign_name -> set of raw utm values+ # e.g. campaign_name_mappings = {"GoogleAds": {"brand_campaign": ["partner_q1", "brand_q1"]}}+ campaign_aliases: dict[str, set[str]] = {}+ campaign_name_mappings = config.campaign_name_mappings or {}+ for _integration_type, campaign_map in campaign_name_mappings.items():+ for clean_name, raw_values in campaign_map.items():+ clean_lower = clean_name.lower().strip()+ if clean_lower not in campaign_aliases:+ campaign_aliases[clean_lower] = set()+ for raw_value in raw_values:+ campaign_aliases[clean_lower].add(raw_value.lower().strip())++ # Build field preferences, keyed by primary source so campaign rows can be looked+ # up directly by their `source_name`.+ field_preferences: dict[str, str] = {}+ campaign_field_prefs = config.campaign_field_preferences or {}+ for integration_type, prefs in campaign_field_prefs.items():+ match_field = prefs.get("match_field", DEFAULT_MATCH_FIELD)+ try:+ native_source = NativeMarketingSource(integration_type)+ except ValueError:+ continue+ primary = primary_source_for(native_source)+ if primary:+ field_preferences[primary] = match_field++ return TeamMappings(+ source_to_integration=source_to_integration,+ campaign_aliases=campaign_aliases,+ field_preferences=field_preferences,+ )+++def build_known_sources(mappings: TeamMappings) -> set[str]:+ """Build the set of utm_source values claimed by any integration (default or custom).++ Used to decide whether an unmatched utm_source is safe to suggest as a mapping —+ if it's already claimed by another integration, mapping it would break that one.+ """+ known: set[str] = set()+ for sources in INTEGRATION_DEFAULT_SOURCES.values():+ for source in sources:+ known.add(source.lower().strip())+ # Custom mappings already flattened to source -> primary_source+ known.update(mappings.source_to_integration.keys())+ return known+++@cache+def default_alias_to_primary() -> dict[str, str]:+ """Normalized default utm_source aliases ('facebook', 'adwords') -> the+ integration's primary source name ('meta', 'google')."""+ out: dict[str, str] = {}+ for alias, target_key in canonical_source_aliases().items():+ primary = primary_source_for(KEY_TO_NATIVE[target_key])+ if primary:+ out[alias] = primary+ return out+++def resolve_source(utm_source: str, mappings: TeamMappings) -> str:+ """Resolve a utm_source to its integration's primary source: team custom+ mappings first (they win, matching `build_combined_alias_map`), then the+ platform default aliases so e.g. 'facebook' resolves to 'meta'.++ Returns the input unchanged when nothing claims it — callers check against+ `build_known_sources` to tell "resolved" from "passed through".+ """+ custom = mappings.source_to_integration.get(utm_source)+ if custom is not None:+ return custom+ return default_alias_to_primary().get(normalize(utm_source), utm_source)+++def get_match_field(source_name: str, mappings: TeamMappings) -> str:+ """The field this integration matches campaigns on, per `campaign_field_preferences`."""+ return mappings.field_preferences.get(source_name.lower().strip(), DEFAULT_MATCH_FIELD)+++def get_match_value(campaign: Campaign, mappings: TeamMappings) -> str:+ """Get the campaign value to match against utm_campaign, based on field preference."""+ if get_match_field(campaign.source_name, mappings) == "campaign_id":+ return campaign.campaign_id.lower().strip()+ return campaign.campaign_name.lower().strip()+++def build_campaign_lookup(+ campaigns: list[Campaign],+ mappings: TeamMappings,+) -> dict[str, CampaignMatch]:+ """`utm_campaign` value -> the platform campaign it resolves to.++ The single definition of "this UTM campaign is already matched": a value absent+ from this dict is an orphan, whether the audit is reporting it or a suggester is+ trying to map it. First campaign wins on collision, so callers that care about+ cross-platform collisions must detect those separately (see `_cross_reference`).+ """+ lookup: dict[str, CampaignMatch] = {}+ for campaign in campaigns:+ match_value = get_match_value(campaign, mappings)+ campaign_name_lower = campaign.campaign_name.lower().strip()+ if match_value not in lookup:+ lookup[match_value] = CampaignMatch(campaign.campaign_name, MatchType.AUTO)+ for alias in mappings.campaign_aliases.get(campaign_name_lower, set()):+ if alias not in lookup:+ lookup[alias] = CampaignMatch(campaign.campaign_name, MatchType.MAPPED)+ return lookup+++def build_source_lookup(campaigns: list[Campaign], mappings: TeamMappings) -> dict[str, str]:+ """`utm_source` value -> how it matched a connected integration.++ Only covers sources that a connected integration actually spends on: AUTO for a+ primary source emitted by an adapter, MAPPED for a team custom mapping pointing+ at one of those. A custom mapping to an integration with no campaign rows is+ deliberately absent — there's nothing to attribute to.+ """+ lookup: dict[str, str] = {}+ for campaign in campaigns:+ source_name_lower = campaign.source_name.lower().strip()+ if source_name_lower not in lookup:+ lookup[source_name_lower] = MatchType.AUTO+ for custom_source, primary_source in mappings.source_to_integration.items():+ if primary_source in lookup and custom_source not in lookup:+ lookup[custom_source] = MatchType.MAPPED+ return lookup