: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): suggest campaign_name_mappings for typo'd utm_campaign values (#78059)
Javier Bahamondes11c8d32f780d
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.pyindex 50043e4700d5..d02e7b360f52 100644--- a/products/marketing_analytics/backend/api.py+++ b/products/marketing_analytics/backend/api.py@@ -35,7 +35,7 @@ from products.marketing_analytics.backend.services.data_source_health import getfrom products.marketing_analytics.backend.services.event_suggestions import suggest_conversion_goalsfrom products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappingsfrom products.marketing_analytics.backend.services.marketing_diagnostic import get_marketing_diagnostic-from products.marketing_analytics.backend.services.types import UTM_ISSUE_KIND_CHOICES+from products.marketing_analytics.backend.services.types import SUGGESTED_ACTION_CHOICES, UTM_ISSUE_KIND_CHOICESfrom products.marketing_analytics.backend.services.utm_audit import run_utm_auditfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable@@ -94,6 +94,21 @@ class UtmIssueSerializer(serializers.Serializer):missing_source_count = serializers.IntegerField(help_text="Pageviews that matched this campaign but carried no utm_source, on any issue kind")+ suggested_actions = serializers.ListField(+ child=serializers.ChoiceField(choices=SUGGESTED_ACTION_CHOICES),+ help_text=(+ "Recommended remediations, most-recommended first. fix_platform_urls cures the tagging "+ "bug itself; the others are workarounds that leave the bad URLs in place."+ ),+ )+ mapping_candidate = serializers.CharField(+ allow_blank=True,+ help_text=(+ "The orphaned utm_campaign value that looks like a typo of this campaign, when one was "+ "found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, "+ "including when several candidates tie and picking one could misattribute spend."+ ),+ )class CampaignAuditResultSerializer(serializers.Serializer):@@ -354,6 +369,9 @@ class SourceMappingSuggestionSerializer(serializers.Serializer):suggested_target = serializers.CharField(help_text="Integration key it maps to")suggested_target_display_name = serializers.CharField(help_text="Human-readable name of the suggested integration")reason = serializers.CharField(help_text="Why this mapping is suggested")+ event_count_30d = serializers.IntegerField(+ help_text="Events carrying this raw utm_source in the window. Suggestions are ordered by it."+ )class CampaignMappingSuggestionSerializer(serializers.Serializer):@@ -366,6 +384,9 @@ class CampaignMappingSuggestionSerializer(serializers.Serializer):confidence = serializers.FloatField(help_text="Confidence score for the clustering (0-1)")method = serializers.CharField(help_text="Mapping method")reason = serializers.CharField(help_text="Why these campaign values were clustered together")+ event_count_30d = serializers.IntegerField(+ help_text="Events across every raw value folded into this suggestion. Suggestions are ordered by it."+ )class RawUnmatchedSampleSerializer(serializers.Serializer):@@ -402,7 +423,11 @@ class UtmMappingSuggestionsResponseSerializer(serializers.Serializer):many=True, help_text="Suggested custom_source_mappings entries")campaign_suggestions = CampaignMappingSuggestionSerializer(- many=True, help_text="Suggested campaign-name clusters (empty in v1)"+ many=True,+ help_text=(+ "campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real "+ "campaign. Near-ties are withheld, so an absent campaign may still be mappable by hand."+ ),)raw_unmatched_samples = RawUnmatchedSampleSerializer(many=True, help_text="All unmatched raw utm_source values worth reviewing"diff --git a/products/marketing_analytics/backend/demo/test_warehouse.py b/products/marketing_analytics/backend/demo/test_warehouse.pynew file mode 100644index 000000000000..d6833bad89c5--- /dev/null+++ b/products/marketing_analytics/backend/demo/test_warehouse.py@@ -0,0 +1,45 @@+import pytest+from posthog.test.base import BaseTest++from products.marketing_analytics.backend.demo import warehouse+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+++class TestAssertSeedable(BaseTest):+ def _table(self, name: str, source_id: str | None) -> DataWarehouseTable:+ source = (+ ExternalDataSource.objects.create(team=self.team, source_type="GoogleAds", source_id=source_id)+ if source_id is not None+ else None+ )+ return DataWarehouseTable.objects.create(+ team=self.team, name=name, columns={"campaign_id": "String"}, external_data_source=source+ )++ def test_a_clean_team_is_seedable(self):+ warehouse.assert_seedable(self.team)++ def test_a_previously_seeded_team_is_seedable_again(self):+ self._table("googleads_campaign", "marketing-demo-googleads")++ warehouse.assert_seedable(self.team)++ def test_a_real_integration_is_refused_and_named(self):+ self._table("googleads_campaign", "real-oauth-connection")++ with pytest.raises(ValueError) as error:+ warehouse.assert_seedable(self.team)++ assert "googleads_campaign" in str(error.value)++ def test_a_table_the_seeder_never_writes_is_ignored(self):+ self._table("some_customer_table", "real-oauth-connection")++ warehouse.assert_seedable(self.team)++ def test_a_deleted_table_does_not_block(self):+ table = self._table("googleads_campaign", "real-oauth-connection")+ table.deleted = True+ table.save()++ warehouse.assert_seedable(self.team)diff --git a/products/marketing_analytics/backend/demo/warehouse.py b/products/marketing_analytics/backend/demo/warehouse.pyindex 44c2ddf97efd..1c8528269ad3 100644--- a/products/marketing_analytics/backend/demo/warehouse.py+++ b/products/marketing_analytics/backend/demo/warehouse.py@@ -581,6 +581,34 @@ STRIPE_INVOICES_COLUMNS = {}+def assert_seedable(team: Team) -> None:+ """Refuse a team whose warehouse tables came from a real integration.++ `register_table` checks the same thing, but only once it reaches each table — by which point+ the seeder has already written tens of thousands of events into ClickHouse, where they are far+ harder to take back than a Postgres row. Pointed at the wrong project, the run should cost+ nothing.+ """+ wanted = {+ f"{prefix}_{schema}" for _, prefix, columns_by_schema in NATIVE_SPECS.values() for schema in columns_by_schema+ }+ wanted |= {BIGQUERY_ADS_TABLE, STRIPE_INVOICES_TABLE}++ clashes = sorted(+ table.name+ for table in DataWarehouseTable.objects.filter(team=team, name__in=wanted, deleted=False).select_related(+ "external_data_source"+ )+ if table.external_data_source is not None+ and not (table.external_data_source.source_id or "").startswith("marketing-demo")+ )+ if clashes:+ raise ValueError(+ f"Team {team.pk} has warehouse tables from a real integration ({', '.join(clashes)}). "+ "Seed a dedicated project instead, or delete those tables first."+ )++def register_table(team: Team,*,diff --git a/products/marketing_analytics/backend/demo/world.py b/products/marketing_analytics/backend/demo/world.pyindex 76bfdd0aad7e..98cb60ed82c4 100644--- a/products/marketing_analytics/backend/demo/world.py+++ b/products/marketing_analytics/backend/demo/world.py@@ -162,6 +162,80 @@ CAMPAIGNS: tuple[DemoCampaign, ...] = (purchase_rate=0.015,scenario="same campaign name as a Meta campaign; only google-tagged events",),+ DemoCampaign(+ platform="GoogleAds",+ campaign_id="10006",+ name="autumn_clearance",+ daily_cost=120.0,+ daily_impressions=3200,+ daily_clicks=95,+ daily_sessions=30,+ utm_source="google",+ utm_campaign="autumn_clearance",+ referring_domain="google.com",+ signup_rate=0.03,+ purchase_rate=0.008,+ # Every session carries the typo, so the campaign has spend and zero matched events — the+ # shape the mapping suggester proposes for. `spring_sale_2026` above is the already-mapped+ # counterpart, and `generic_search`'s traffic is clean, so neither produces a suggestion.+ # Scores 93.3: proposed, but under the bar to be batch-applied.+ utm_campaign_variants={"autum_clearnce": 1.0},+ scenario="spend with no matched events: typo'd utm_campaign the suggester should map",+ ),+ DemoCampaign(+ platform="GoogleAds",+ campaign_id="10007",+ name="holiday_push_q4",+ daily_cost=80.0,+ daily_impressions=2400,+ daily_clicks=70,+ daily_sessions=22,+ utm_source="google",+ utm_campaign="holiday_push_q4",+ referring_domain="google.com",+ signup_rate=0.04,+ purchase_rate=0.01,+ # Duplicated from Q3 without updating the template. Scores 93.3 against its own campaign,+ # well over the cutoff, and is refused anyway because the only differing token is the+ # quarter — merging the two would merge two quarters' spend.+ utm_campaign_variants={"holiday_push_q3": 1.0},+ scenario="period sibling: high score the suggester must refuse",+ ),+ DemoCampaign(+ platform="GoogleAds",+ campaign_id="10008",+ name="retargeting_uk",+ daily_cost=60.0,+ daily_impressions=1800,+ daily_clicks=55,+ daily_sessions=18,+ utm_source="google",+ utm_campaign="retargeting_uk",+ referring_domain="google.com",+ signup_rate=0.05,+ purchase_rate=0.012,+ # Both regional campaigns share one typo'd template, so neither receives its own name and+ # the orphan sits 92.9 from each. A tie the score can't break: it becomes advice, not a+ # guess, because picking one would move the other region's spend.+ utm_campaign_variants={"retargeting_ux": 1.0},+ scenario="near-tie between two campaigns: advice-only, never a guess",+ ),+ DemoCampaign(+ platform="GoogleAds",+ campaign_id="10009",+ name="retargeting_us",+ daily_cost=60.0,+ daily_impressions=1800,+ daily_clicks=55,+ daily_sessions=18,+ utm_source="google",+ utm_campaign="retargeting_us",+ referring_domain="google.com",+ signup_rate=0.05,+ purchase_rate=0.012,+ utm_campaign_variants={"retargeting_ux": 1.0},+ scenario="the other half of the near-tie above",+ ),# --- Meta Ads (source stale: last sync > 24h ago) ---DemoCampaign(platform="MetaAds",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 6725b2a95975..b14e242a5a96 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@@ -86,6 +86,13 @@ class Command(BaseCommand):self._print_plan(days_past, scale)return+ # Ahead of the event write: the per-table check in `register_table` fires too late to keep a+ # wrong `--team-id` from leaving 48k events behind in ClickHouse.+ try:+ warehouse.assert_seedable(team)+ except ValueError as error:+ raise CommandError(str(error))+generator = MarketingEventGenerator(team, seed=options["seed"], days_past=days_past, scale=scale, now=now)if options["skip_events"]:self.stdout.write("Skipping event generation.")diff --git a/products/marketing_analytics/backend/max_tools.py b/products/marketing_analytics/backend/max_tools.pyindex deaf4da0e157..2d0f5e82c0e0 100644--- a/products/marketing_analytics/backend/max_tools.py+++ b/products/marketing_analytics/backend/max_tools.py@@ -749,6 +749,21 @@ def _format_utm_mapping_suggestions_for_llm(response) -> str:lines.append("## Suggestions: none")lines.append("")+ if response.campaign_suggestions:+ lines.append(f"## Campaign name suggestions ({len(response.campaign_suggestions)})")+ for c in response.campaign_suggestions:+ raw_values = ", ".join(f"`{_sanitize_for_prompt(v)}`" for v in c.raw_campaign_values)+ lines.append(+ f"- {raw_values} → **{_sanitize_for_prompt(c.suggested_clean_name)}** "+ f"on {c.integration_display_name} (events_in_window={c.event_count_30d}, "+ f"confidence={c.confidence:.2f})"+ )+ lines.append(f" {_sanitize_for_prompt(c.reason, max_len=400)}")+ lines.append("")+ else:+ lines.append("## Campaign name suggestions: none")+ lines.append("")+# Raw catalogue: every unmatched value we saw, with the alias-token hint if anyif response.raw_unmatched_samples:lines.append(diff --git a/products/marketing_analytics/backend/services/campaign_mapping_suggester.py b/products/marketing_analytics/backend/services/campaign_mapping_suggester.pynew file mode 100644index 000000000000..19dcbd1b608d--- /dev/null+++ b/products/marketing_analytics/backend/services/campaign_mapping_suggester.py@@ -0,0 +1,397 @@+"""Propose `campaign_name_mappings` for typo'd `utm_campaign` values.++`sprng_sale_2024` against a platform campaign named `spring_sale_2024` shows up in the+audit as "not linked" with no explanation. This proposes the mapping that reconnects it.++BEFORE LOOSENING ANYTHING HERE: the errors are not symmetric. A miss costs one unlinked+campaign; a false positive misattributes spend and surfaces months later as "our ROAS is+wrong". The thresholds, the near-tie refusals and the period guard all pay for that.++Pure function. Feed it `get_campaigns_with_spend` and `get_utm_campaign_catalogue` output.+"""++import re+from collections import Counter, defaultdict+from collections.abc import Mapping+from dataclasses import dataclass, field+from typing import Literal, NamedTuple++import structlog++from posthog.schema import NativeMarketingSource++from posthog.helpers.fuzzy_search import fuzzy_rank++from products.marketing_analytics.backend.services.native_integrations import (+ NATIVE_TO_KEY,+ display_name_for_key,+ native_for_primary_source,+)+from products.marketing_analytics.backend.services.types import Campaign, TeamMappings+from products.marketing_analytics.backend.services.utm_matching import (+ build_campaign_lookup,+ get_match_value_raw,+ group_campaigns_by_source,+ normalize_source_name,+ resolve_source,+)++logger = structlog.get_logger(__name__)++MIN_EVENT_COUNT = 25+MAX_UNMATCHED_VALUES = 100++# Longer than any real campaign name — Google Ads caps them at 128 characters and the rest are in+# that range — so anything past this is junk that can't be a typo of a real name. It is also the+# only bound on the fuzzy pass's cost: `utm_campaign` arrives from an event property with no length+# limit, and 100 orphans against 500 candidates takes 60ms at realistic lengths and 5 minutes when+# both sides are 20k characters.+MAX_VALUE_LENGTH = 200++# 88, not the helper's default 70: that one is tuned for a search box with a human reading it.+SCORE_CUTOFF = 88.0+MIN_MARGIN = 6.0+UNSCOPED_SCORE_CUTOFF = 93.0+BATCH_SCORE = 95.0+BATCH_MARGIN = 15.0++# Floor for measuring the margin, not for accepting a match: a runner-up below this can't change+# a verdict, one above it must stay visible.+MARGIN_FLOOR = SCORE_CUTOFF - BATCH_MARGIN++TOP_N_CANDIDATES = 3+# Slack so a quarterly family, alike across every sibling, can't fill every slot pre-filter.+CANDIDATE_HEADROOM = 4++_TOKEN_SPLIT = re.compile(r"[-_./\s+|:]+")+_MONTHS = frozenset(+ "jan feb mar apr may jun jul aug sep oct nov dec january february march april june "+ "july august september october november december".split()+)+_PERIOD_TOKEN = re.compile(r"^(?:q[1-4]|h[12]|fy\d{2,4}|wk?\d{1,2}|\d{4}q[1-4])$")++SuggestionMethod = Literal["fuzzy_exact_scope", "fuzzy_unscoped"]+++@dataclass+class CampaignMappingProposal:+ # PascalCase `NativeMarketingSource` value, i.e. the key team config uses.+ integration: str+ integration_display_name: str+ # Must equal `match_key`, so it follows `campaign_field_preferences` — a name proposed to an+ # id-matching integration writes a mapping that never joins.+ clean_name: str+ raw_utm_campaign: str+ event_count: int+ campaign_spend: float+ score: float+ confidence: float+ safe_to_batch: bool+ method: SuggestionMethod+ reason: str+ observed_utm_source: str+ expected_utm_campaign: str+ expected_utm_source: str+++@dataclass+class AmbiguousCampaign:+ raw_utm_campaign: str+ event_count: int+ observed_utm_source: str+ candidates: list[tuple[str, float]] = field(default_factory=list)+ reason: str = ""+++@dataclass+class CampaignMappingSuggestions:+ proposals: list[CampaignMappingProposal] = field(default_factory=list)+ ambiguous: list[AmbiguousCampaign] = field(default_factory=list)+ unresolved: list[AmbiguousCampaign] = field(default_factory=list)+ notes: list[str] = field(default_factory=list)+++def suggest_campaign_name_mappings(+ campaigns: list[Campaign],+ utm_events: dict[tuple[str, str], int],+ mappings: TeamMappings,+ *,+ min_event_count: int = MIN_EVENT_COUNT,+ max_unmatched_values: int = MAX_UNMATCHED_VALUES,+) -> CampaignMappingSuggestions:+ already_matched = set(build_campaign_lookup(campaigns, mappings))+ already_mapped = {raw for aliases in mappings.campaign_aliases.values() for raw in aliases}+ campaigns_by_source = group_campaigns_by_source(campaigns)++ # Per platform, not global: name reuse is the norm, and a global set let Meta's `brand`+ # traffic disqualify Google's own `brand` campaign.+ seen_by_source: dict[str, set[str]] = {}+ for utm_campaign, utm_source in utm_events:+ if not utm_campaign:+ continue+ seen_by_source.setdefault(resolve_source(normalize_source_name(utm_source), mappings), set()).add(+ utm_campaign.lower()+ )++ orphans = _orphans(utm_events, already_matched | already_mapped)+ considered = [o for o in orphans if o.event_count >= min_event_count][:max_unmatched_values]++ notes: list[str] = []+ if len(orphans) > len(considered):+ notes.append(+ f"{len(orphans) - len(considered)} orphaned utm_campaign value(s) were skipped: below "+ f"{min_event_count} events or beyond the top {max_unmatched_values} by volume."+ )++ result = CampaignMappingSuggestions(notes=notes)+ # clean_name -> the utm_source already proposed for it, so two platforms' orphans can't merge.+ claimed_clean_names: dict[str, str] = {}++ for orphan in considered:+ verdict = _classify(+ orphan=orphan,+ campaigns_by_source=campaigns_by_source,+ mappings=mappings,+ seen_by_source=seen_by_source,+ claimed_clean_names=claimed_clean_names,+ )+ match verdict:+ case CampaignMappingProposal():+ claimed_clean_names[verdict.clean_name] = verdict.observed_utm_source+ result.proposals.append(verdict)+ case _Ambiguous(entry):+ result.ambiguous.append(entry)+ case _Unresolved(entry):+ result.unresolved.append(entry)++ result.proposals.sort(key=lambda p: (-p.campaign_spend, -p.event_count, p.raw_utm_campaign))+ result.ambiguous.sort(key=lambda a: -a.event_count)+ result.unresolved.sort(key=lambda a: -a.event_count)+ return result+++@dataclass+class _Orphan:+ raw_utm_campaign: str+ event_count: int+ dominant_utm_source: str+++def _orphans(utm_events: dict[tuple[str, str], int], excluded: set[str]) -> list[_Orphan]:+ """Unmatched values with the utm_source they mostly arrive on. "Unmatched" is+ `build_campaign_lookup`'s definition, so this can't disagree with the audit."""+ totals: Counter[str] = Counter()+ by_source: dict[str, Counter[str]] = defaultdict(Counter)+ for (utm_campaign, utm_source), count in utm_events.items():+ if not utm_campaign or len(utm_campaign) > MAX_VALUE_LENGTH or utm_campaign in excluded:+ continue+ totals[utm_campaign] += count+ by_source[utm_campaign][utm_source] += count++ orphans = []+ for raw, count in totals.most_common():+ sources = by_source[raw]+ dominant = min(sources.most_common(), key=lambda item: (-item[1], item[0]))[0] if sources else ""+ orphans.append(_Orphan(raw_utm_campaign=raw, event_count=count, dominant_utm_source=dominant))+ return orphans+++def _tokens(value: str) -> list[str]:+ return [token for token in _TOKEN_SPLIT.split(value.lower()) if token]+++def _is_period_token(token: str) -> bool:+ return token.isdigit() or bool(_PERIOD_TOKEN.match(token)) or token in _MONTHS+++def differs_only_by_period(a: str, b: str) -> bool:+ """True when the two names differ *only* in period/instance tokens.++ `brand_us_q1` vs `brand_us_q2` is a sibling, not a typo. An identical multiset is a separator+ or ordering difference, i.e. a real match, so it returns False. Accepted false negative: a+ truncation like `spring_sale_202` is indistinguishable from a sibling, so both are refused.+ """+ diff = (Counter(_tokens(a)) - Counter(_tokens(b))) + (Counter(_tokens(b)) - Counter(_tokens(a)))+ return bool(diff) and all(_is_period_token(token) for token in diff.elements())+++class _Target(NamedTuple):+ campaign: Campaign+ native: NativeMarketingSource+++class _Ambiguous(NamedTuple):+ """Several plausible targets. Distinct from `_Unresolved` only in which list it lands in."""++ entry: AmbiguousCampaign+++class _Unresolved(NamedTuple):+ entry: AmbiguousCampaign+++_Verdict = CampaignMappingProposal | _Ambiguous | _Unresolved | None+++def _refuse(orphan: _Orphan, reason: str, candidates: list[tuple[str, float]] | None = None) -> AmbiguousCampaign:+ return AmbiguousCampaign(+ raw_utm_campaign=orphan.raw_utm_campaign,+ event_count=orphan.event_count,+ observed_utm_source=orphan.dominant_utm_source,+ candidates=candidates or [],+ reason=reason,+ )+++def _classify(+ *,+ orphan: _Orphan,+ campaigns_by_source: dict[str, list[Campaign]],+ mappings: TeamMappings,+ seen_by_source: dict[str, set[str]],+ claimed_clean_names: Mapping[str, str],+) -> _Verdict:+ """Decide one orphan's fate. Returns the verdict rather than filing it, so the caller owns+ both accumulators — `claimed_clean_names` is read here and written only there."""+ scoped_source = resolve_source(orphan.dominant_utm_source, mappings)+ scoped_group = campaigns_by_source.get(scoped_source)++ if scoped_group:+ candidates, method, cutoff = scoped_group, "fuzzy_exact_scope", SCORE_CUTOFF+ else:+ candidates = [c for group in campaigns_by_source.values() for c in group]+ method, cutoff = "fuzzy_unscoped", UNSCOPED_SCORE_CUTOFF++ if not candidates:+ return None++ seen = (+ seen_by_source.get(scoped_source, set())+ if scoped_group+ else {value for values in seen_by_source.values() for value in values}+ )++ by_value: dict[str, _Target] = {}+ # Which platforms carry each value; only ever >1 unscoped. See the guard on `top_value`.+ natives_by_value: dict[str, set[str]] = {}+ for campaign in candidates:+ value = get_match_value_raw(campaign, mappings)+ if not value or len(value) > MAX_VALUE_LENGTH or value.lower() in seen:+ continue+ native = native_for_primary_source(campaign.source_name)+ if native is None:+ continue+ natives_by_value.setdefault(value, set()).add(native.value)+ if value not in by_value or campaign.spend > by_value[value].campaign.spend:+ by_value[value] = _Target(campaign, native)++ # MARGIN_FLOOR, not `cutoff`: a sub-cutoff runner-up still proves ambiguity, and filtering it+ # out here made a 90.9-vs-85.5 pair read as a lone match at margin 100.+ ranked = fuzzy_rank(+ orphan.raw_utm_campaign,+ list(by_value),+ score_cutoff=MARGIN_FLOOR,+ limit=TOP_N_CANDIDATES * CANDIDATE_HEADROOM,+ )+ # Split before the margin, or `brand_q2` beside `brand_q1` reads as ambiguous instead of no+ # match. The siblings are kept to explain the refusal, not to rank.+ kept: list[tuple[str, float]] = []+ siblings: list[str] = []+ for value, score in ranked:+ if differs_only_by_period(orphan.raw_utm_campaign, value):+ siblings.append(value)+ else:+ kept.append((value, score))+ ranked = kept[:TOP_N_CANDIDATES]++ if ranked and ranked[0][1] < cutoff:+ ranked = []++ if not ranked:+ # Naming the sibling matters: without it the reason claims nothing was close, while the+ # campaign the user is looking at sits well above the cutoff and was refused on purpose.+ if siblings:+ reason = (+ f"'{orphan.raw_utm_campaign}' closely matches {siblings[0]}, but the two differ only "+ "in the period they name, so they are different runs of one campaign. Mapping them "+ "together would merge their spend."+ )+ else:+ reason = (+ f"No platform campaign is within {cutoff:.0f}% similarity of "+ f"'{orphan.raw_utm_campaign}'. Either the campaign was renamed beyond what edit "+ "distance can match, or this traffic isn't from a connected ad platform."+ )+ return _Unresolved(_refuse(orphan, reason))++ top_value, top_score = ranked[0]+ margin = top_score - ranked[1][1] if len(ranked) > 1 else 100.0++ if margin < MIN_MARGIN:+ return _Ambiguous(+ _refuse(+ orphan,+ f"'{orphan.raw_utm_campaign}' is a near-equal match for "+ f"{' and '.join(value for value, _ in ranked[:2])} "+ f"({ranked[0][1]:.0f}% vs {ranked[1][1]:.0f}%). Picking one could attribute this "+ "campaign's traffic to the wrong ad spend, so it needs a human.",+ ranked,+ )+ )++ # A name two platforms both run ties *at* the top, so the margin reads 100 and the spend+ # tiebreak would silently pick the platform. Unreachable when scoped.+ contenders = natives_by_value.get(top_value, set())+ if len(contenders) > 1:+ return _Ambiguous(+ _refuse(+ orphan,+ f"'{top_value}' is a campaign on {' and '.join(sorted(contenders))}, and "+ f"utm_source='{orphan.dominant_utm_source}' doesn't say which one this traffic "+ "belongs to. Mapping it to the wrong platform would move real spend, so it "+ "needs a human.",+ ranked,+ )+ )++ campaign, native = by_value[top_value]++ claimed_by = claimed_clean_names.get(top_value)+ if claimed_by is not None and claimed_by != orphan.dominant_utm_source:+ logger.debug(+ "campaign_mapping_suggester.clean_name_already_claimed",+ clean_name=top_value,+ claimed_by=claimed_by,+ skipped=orphan.raw_utm_campaign,+ )+ return None++ expected_utm_source = normalize_source_name(campaign.source_name)+ display_name = display_name_for_key(NATIVE_TO_KEY[native])+ return CampaignMappingProposal(+ integration=native.value,+ integration_display_name=display_name,+ clean_name=top_value,+ raw_utm_campaign=orphan.raw_utm_campaign,+ event_count=orphan.event_count,+ campaign_spend=campaign.spend,+ score=round(top_score, 1),+ confidence=_confidence(top_score),+ safe_to_batch=(method == "fuzzy_exact_scope" and top_score >= BATCH_SCORE and margin >= BATCH_MARGIN),+ method=method, # type: ignore[arg-type]+ reason=(+ f"'{orphan.raw_utm_campaign}' — {orphan.event_count:,} events, {top_score:.0f}% similar to "+ f"{display_name} campaign '{top_value}', which has {campaign.spend:,.0f} spend and no "+ "matched events."+ ),+ observed_utm_source=orphan.dominant_utm_source,+ expected_utm_campaign=top_value,+ expected_utm_source=expected_utm_source,+ )+++def _confidence(score: float) -> float:+ """Score band above the cutoff mapped onto 0.5-0.9. The ceiling keeps these rows out of any+ UI that auto-applies on confidence."""+ span = max(100.0 - SCORE_CUTOFF, 1e-9)+ return round(min(0.5 + ((score - SCORE_CUTOFF) / span) * 0.4, 0.9), 2)diff --git a/products/marketing_analytics/backend/services/mapping_suggester.py b/products/marketing_analytics/backend/services/mapping_suggester.pyindex d53c8f9fbd0b..25457bc987c5 100644--- a/products/marketing_analytics/backend/services/mapping_suggester.py+++ b/products/marketing_analytics/backend/services/mapping_suggester.py@@ -5,14 +5,18 @@ Reuses `attribution_health`'s alias-token suggestions (canonical + team-custom)catalogue for the LLM to interpret."""+import asynciofrom collections import defaultdictfrom dataclasses import asdict, dataclass, fieldfrom typing import Any, Literal+from django.utils import timezone+import structlog-from posthog.schema import NativeMarketingSource+from posthog.schema import DateRange, NativeMarketingSource+from posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_async@@ -21,16 +25,27 @@ from products.marketing_analytics.backend.services.attribution_health import (UnmatchedUtmSample,get_attribution_health,)+from products.marketing_analytics.backend.services.campaign_mapping_suggester import (+ CampaignMappingSuggestions,+ suggest_campaign_name_mappings,+)from products.marketing_analytics.backend.services.native_integrations import (NATIVE_TO_KEY,NativeIntegration,canonical_source_aliases,display_name_for_key,)+from products.marketing_analytics.backend.services.utm_audit import (+ get_campaigns_with_spend_async,+ get_utm_campaign_catalogue_async,+)+from products.marketing_analytics.backend.services.utm_matching import load_team_mappingslogger = structlog.get_logger(__name__)-MappingMethod = Literal["exact_alias", "llm"]+# `fuzzy_*` come from `campaign_mapping_suggester`, which now fills `campaign_suggestions`.+# Additive: consumers keep seeing the two values they already handle.+MappingMethod = Literal["exact_alias", "llm", "fuzzy_exact_scope", "fuzzy_unscoped"]# Minimum 30d event count worth suggesting — tiny tails don't justify config changes.DEFAULT_MIN_EVENT_COUNT = 10@@ -113,6 +128,7 @@ async def suggest_utm_mappings(max_per_integration: int = MAX_SUGGESTIONS_PER_INTEGRATION,lookback_days: int = 90,attribution: AttributionHealthResponse | None = None,+ campaign_proposals: CampaignMappingSuggestions | None = None,) -> UtmMappingSuggestionsResponse:"""Detect unmatched utm_source values and propose target integrations.@@ -124,9 +140,14 @@ async def suggest_utm_mappings(setup plan needs both. `lookback_days` is ignored when it's supplied: thereported window comes off the response so it can never disagree with the datathe suggestions were actually derived from.++ `campaign_proposals` does the same for `campaign_name_mappings`: left out, this derives them+ itself at the cost of three more reads."""if attribution is None:attribution = await get_attribution_health(team, lookback_days=lookback_days)+ if campaign_proposals is None:+ campaign_proposals = await _derive_campaign_proposals(team, lookback_days)lookback_days = attribution.lookback_dayscurrent_mappings = await _read_current_mappings(team)notes: list[str] = []@@ -202,8 +223,9 @@ async def suggest_utm_mappings(final_notes = [*notes,- "Campaign clustering (campaign_name_mappings) is not yet implemented; "- "this v1 only proposes custom_source_mappings entries.",+ "campaign_suggestions are fuzzy matches over orphaned utm_campaign values. Near-ties are "+ "deliberately withheld rather than guessed, so an absent campaign is not necessarily "+ "unmappable — it may just need a human to pick between two candidates.",]catalogue: list[CatalogueEntry] = []for entry in attribution.all_utm_source_samples:@@ -221,7 +243,7 @@ async def suggest_utm_mappings(return UtmMappingSuggestionsResponse(source_suggestions=source_suggestions,- campaign_suggestions=[], # campaign clustering disabled in v1+ campaign_suggestions=_to_campaign_suggestions(campaign_proposals),raw_unmatched_samples=raw_unmatched,full_utm_source_catalogue=catalogue,current_mappings=current_mappings,@@ -232,12 +254,85 @@ async def suggest_utm_mappings()+async def _derive_campaign_proposals(team: Team, lookback_days: int) -> CampaignMappingSuggestions:+ """Run the campaign mapping suggester over this team's own window.++ Contained: an empty `campaign_suggestions` is what every consumer sees today, so a broken+ campaign query must not take the source suggestions down with it.+ """+ date_range = QueryDateRange(+ date_range=DateRange(date_from=f"-{lookback_days}d", date_to=None),+ team=team,+ interval=None,+ now=timezone.now(),+ )+ try:+ campaigns, utm_events, mappings = await asyncio.gather(+ get_campaigns_with_spend_async(team, date_range),+ get_utm_campaign_catalogue_async(team, date_range),+ load_team_mappings_async(team),+ )+ except Exception:+ logger.exception("mapping_suggester.campaign_proposals_failed", team_id=team.pk)+ return CampaignMappingSuggestions()+ return suggest_campaign_name_mappings(campaigns, utm_events, mappings)+++def _to_campaign_suggestions(proposals: CampaignMappingSuggestions) -> list[CampaignMappingSuggestion]:+ """Fold the suggester's per-orphan proposals into this response's per-target shape.++ One proposal is one raw `utm_campaign`; one suggestion is one clean name with every raw value+ pointing at it, which is how `campaign_name_mappings` is stored — so several collapse into one.+ Confidence is the *lowest* of the folded proposals: the entry applies as a unit. Excludes+ `ambiguous`, which exists because the suggester refused to guess.+ """+ grouped: dict[tuple[str, str], list] = defaultdict(list)+ for proposal in proposals.proposals:+ grouped[(proposal.integration, proposal.clean_name)].append(proposal)++ suggestions: list[CampaignMappingSuggestion] = []+ for (integration, clean_name), group in grouped.items():+ native = NATIVE_TO_KEY.get(NativeMarketingSource(integration))+ if native is None:+ # Not an integration this response can name; dropping beats emitting a broken key.+ logger.warning("mapping_suggester.unknown_integration", integration=integration)+ continue+ first = group[0]+ suggestions.append(+ CampaignMappingSuggestion(+ integration=native,+ integration_display_name=first.integration_display_name,+ suggested_clean_name=clean_name,+ raw_campaign_values=sorted(p.raw_utm_campaign for p in group),+ confidence=min(p.confidence for p in group),+ method=first.method,+ reason=first.reason if len(group) == 1 else _folded_reason(group, clean_name),+ event_count_30d=sum(p.event_count for p in group),+ )+ )+ # Highest-volume first: same ordering rule the source suggestions use.+ suggestions.sort(key=lambda s: (-s.event_count_30d, s.suggested_clean_name))+ return suggestions+++def _folded_reason(group: list, clean_name: str) -> str:+ values = ", ".join(sorted(f"'{p.raw_utm_campaign}'" for p in group))+ total = sum(p.event_count for p in group)+ return (+ f"{values} all look like typo'd variants of '{clean_name}' — {total} events in the window "+ "that currently attribute to nothing."+ )++@database_sync_to_asyncdef _read_team_custom_mappings(team: Team) -> dict:config = getattr(team, "marketing_analytics_config", None)return config.custom_source_mappings if config is not None else {}+load_team_mappings_async = database_sync_to_async(load_team_mappings)++async def _read_current_mappings(team: Team) -> list[CurrentMapping]:"""Return the full list of utm_source → integration mappings already ineffect for this team: hardcoded canonical aliases plus the team'sdiff --git a/products/marketing_analytics/backend/services/test_campaign_mapping_suggester.py b/products/marketing_analytics/backend/services/test_campaign_mapping_suggester.pynew file mode 100644index 000000000000..dcd26ab1da39--- /dev/null+++ b/products/marketing_analytics/backend/services/test_campaign_mapping_suggester.py@@ -0,0 +1,432 @@+import time++import pytest++from products.marketing_analytics.backend.services.campaign_mapping_suggester import (+ BATCH_SCORE,+ MIN_EVENT_COUNT,+ SCORE_CUTOFF,+ differs_only_by_period,+ suggest_campaign_name_mappings,+)+from products.marketing_analytics.backend.services.types import Campaign, TeamMappings++NO_MAPPINGS = TeamMappings(source_to_integration={}, campaign_aliases={}, field_preferences={})+++def _campaign(name: str, campaign_id: str = "1", spend: float = 1000.0, source: str = "google") -> Campaign:+ return Campaign(+ campaign_name=name,+ campaign_id=campaign_id,+ source_name=source,+ spend=spend,+ clicks=0,+ impressions=0,+ )+++def _events(*rows: tuple[str, str, int]) -> dict[tuple[str, str], int]:+ return {(campaign, source): count for campaign, source, count in rows}+++class TestPeriodGuard:+ """`brand_us_q1` vs `brand_us_q2` scores ~96 on WRatio and is a different campaign."""++ @pytest.mark.parametrize(+ "a,b",+ [+ ("brand_us_q1", "brand_us_q2"),+ ("sale_2024", "sale_2025"),+ ("promo", "promo_march"),+ ("brand-h1", "brand-h2"),+ ("retarget_w1", "retarget_w2"),+ ("brand_fy24", "brand_fy25"),+ ("launch_2024q1", "launch_2024q2"),+ ],+ )+ def test_rejects_period_siblings(self, a, b):+ assert differs_only_by_period(a, b) is True++ @pytest.mark.parametrize(+ "a,b",+ [+ ("sprng_sale_2024", "spring_sale_2024"),+ ("brand_us", "brnd_us"),+ ("brand_us_q1", "brand-us-q1"),+ ("brand_us_q1", "q1_us_brand"),+ ("sprng_sale_q1", "spring_sale_q2"),+ ],+ )+ def test_allows_real_matches(self, a, b):+ assert differs_only_by_period(a, b) is False+++class TestProposals:+ def test_proposes_mapping_for_a_typo(self):+ campaigns = [_campaign("spring_sale_2024", spend=8200.0)]+ utm_events = _events(("sprng_sale_2024", "google", 1340))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ proposal = result.proposals[0]+ assert proposal.raw_utm_campaign == "sprng_sale_2024"+ assert proposal.clean_name == "spring_sale_2024"+ assert proposal.integration == "GoogleAds"+ assert proposal.event_count == 1340+ assert proposal.campaign_spend == 8200.0+ assert proposal.method == "fuzzy_exact_scope"+ assert proposal.expected_utm_campaign == "spring_sale_2024"+ assert proposal.expected_utm_source == "google"++ def test_confidence_never_reaches_certainty(self):+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("sprng_sale_2024", "google", 500))++ proposal = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS).proposals[0]++ assert 0.5 <= proposal.confidence <= 0.9++ def test_proposes_the_id_when_integration_matches_on_id(self):+ # A name proposed to an id-matching integration never joins.+ prefers_id = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )+ campaigns = [_campaign("spring_sale_2024", campaign_id="promo_1234x")]+ utm_events = _events(("promo_1234y", "google", 500))++ result = suggest_campaign_name_mappings(campaigns, utm_events, prefers_id)++ assert len(result.proposals) == 1+ assert result.proposals[0].clean_name == "promo_1234x"++ def test_a_campaign_already_receiving_traffic_is_never_a_target(self):+ # Mixed case is the point: the guard compared a lowercased candidate against a set+ # built with original casing.+ campaigns = [_campaign("Spring_Sale_2024", spend=8200.0)]+ utm_events = _events(+ ("Spring_Sale_2024", "google", 900), # already linked, mixed case+ ("sprng_sale_2024", "google", 500), # the orphan that must not land on it+ )++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []++ def test_a_quarterly_family_does_not_bury_a_real_match(self):+ # The siblings score 93.33 and the real match 92.86, so truncating to 3 before the period+ # filter buried it. Here the platform campaign carries the typo, not the URL.+ campaigns = [+ _campaign("winter_promo_q2", campaign_id="2"),+ _campaign("winter_promo_q3", campaign_id="3"),+ _campaign("winter_promo_q4", campaign_id="4"),+ _campaign("wintr_prom_q1", campaign_id="1", spend=9000.0),+ ]+ utm_events = _events(("winter_promo_q1", "google", 700))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert [p.clean_name for p in result.proposals] == ["wintr_prom_q1"]++ def test_another_platform_traffic_does_not_veto_a_starved_candidate(self):+ # A global `seen` set let Meta's traffic on "brand" disqualify Google's own "brand".+ campaigns = [+ _campaign("brand", campaign_id="1", spend=9000.0, source="google"),+ _campaign("brand", campaign_id="2", spend=4000.0, source="meta"),+ ]+ utm_events = _events(+ ("brand", "facebook", 1200), # Meta's own traffic, correctly attributed+ ("brnd", "google", 800), # the Google orphan that should map onto Google's "brand"+ )++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert [(p.raw_utm_campaign, p.clean_name, p.integration) for p in result.proposals] == [+ ("brnd", "brand", "GoogleAds")+ ]++ def test_a_runner_up_below_the_cutoff_still_counts_as_ambiguity(self):+ # 90.9 and 85.5 are the scorer's real numbers: the runner-up is below the cutoff, so+ # ranking with it applied reported margin 100 against a real 5.4.+ campaigns = [+ _campaign("uk_uss", campaign_id="1", spend=5000.0),+ _campaign("email_uk", campaign_id="2", spend=4000.0),+ ]+ utm_events = _events(("uk_us", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert [a.raw_utm_campaign for a in result.ambiguous] == ["uk_us"]++ def test_purely_numeric_id_near_miss_is_refused(self):+ # `1234` vs `12345` is indistinguishable from one real id beside another.+ prefers_id = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )+ campaigns = [_campaign("spring_sale_2024", campaign_id="12345")]+ utm_events = _events(("1234", "google", 500))++ result = suggest_campaign_name_mappings(campaigns, utm_events, prefers_id)++ assert result.proposals == []+ assert [u.raw_utm_campaign for u in result.unresolved] == ["1234"]++ def test_numeric_only_typo_is_refused_and_handed_to_the_ai_layer(self):+ # A truncated year is a real typo, but indistinguishable from next year's campaign.+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("spring_sale_202", "google", 500))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert [u.raw_utm_campaign for u in result.unresolved] == ["spring_sale_202"]++ def test_a_period_sibling_refusal_names_the_campaign_it_refused(self):+ # The generic reason claims nothing was within the cutoff, which reads as false when the+ # campaign is right there at 93.3 and was refused on purpose.+ campaigns = [_campaign("holiday_push_q4")]+ utm_events = _events(("holiday_push_q3", "google", 500))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ reason = result.unresolved[0].reason+ assert "holiday_push_q4" in reason+ assert "period" in reason+ assert "similarity" not in reason++ def test_a_candidate_between_the_ranking_floor_and_the_cutoff_is_no_match(self):+ # 85.7: survives MARGIN_FLOOR's 73 and gets ranked, then fails SCORE_CUTOFF's 88. The+ # module's headline threshold, and the only line applying it had no test — every other+ # refusal here goes through the period guard or the margin instead.+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("sprig_sl_204", "google", 500))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert result.ambiguous == []+ assert [u.raw_utm_campaign for u in result.unresolved] == ["sprig_sl_204"]++ def test_orders_proposals_by_spend_at_stake(self):+ campaigns = [_campaign("cheap_campaign", spend=10.0), _campaign("costly_campaign", "2", spend=50000.0)]+ utm_events = _events(("cheap_campaig", "google", 900), ("costly_campaig", "google", 100))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert [p.clean_name for p in result.proposals] == ["costly_campaign", "cheap_campaign"]+++class TestRefusals:+ def test_period_sibling_is_never_proposed(self):+ campaigns = [_campaign("brand_us_q1")]+ utm_events = _events(("brand_us_q2", "google", 5000))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert result.ambiguous == []+ assert [u.raw_utm_campaign for u in result.unresolved] == ["brand_us_q2"]++ def test_near_tie_becomes_advice_not_a_guess(self):+ campaigns = [_campaign("brand_usa", "1"), _campaign("brand_use", "2")]+ utm_events = _events(("brand_us", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert len(result.ambiguous) == 1+ assert result.ambiguous[0].raw_utm_campaign == "brand_us"+ assert len(result.ambiguous[0].candidates) >= 2+ assert "needs a human" in result.ambiguous[0].reason++ def test_below_min_event_count_is_skipped(self):+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("sprng_sale_2024", "google", MIN_EVENT_COUNT - 1))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert any("were skipped" in n for n in result.notes)++ def test_already_mapped_value_is_skipped(self):+ mappings = TeamMappings(+ source_to_integration={},+ campaign_aliases={"spring_sale_2024": {"sprng_sale_2024"}},+ field_preferences={},+ )+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("sprng_sale_2024", "google", 1000))++ result = suggest_campaign_name_mappings(campaigns, utm_events, mappings)++ assert result.proposals == []++ def test_exact_match_of_another_integrations_campaign_is_a_collision_not_a_typo(self):+ campaigns = [_campaign("brand_global", "1", source="google"), _campaign("brand_globa", "2", source="meta")]+ # An exact match for meta's name is a collision, not a typo.+ utm_events = _events(("brand_globa", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []++ def test_will_not_map_onto_a_campaign_that_already_has_traffic(self):+ # spring_sale_2024 is already linked under its own name.+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("spring_sale_2024", "google", 4000), ("sprng_sale_2024", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert [u.raw_utm_campaign for u in result.unresolved] == ["sprng_sale_2024"]++ def test_two_platforms_cannot_collapse_into_one_clean_name(self):+ campaigns = [_campaign("spring_sale_2024", spend=5000.0, source="google")]+ utm_events = _events(+ ("sprng_sale_2024", "google", 2000),+ ("spring_sale_2024x", "meta", 1500),+ )++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ assert result.proposals[0].observed_utm_source == "google"++ def test_no_campaigns_yields_nothing(self):+ assert suggest_campaign_name_mappings([], _events(("whatever", "google", 900)), NO_MAPPINGS).proposals == []+++class TestScoping:+ def test_unresolvable_source_uses_the_higher_bar_and_never_batches(self):+ # utm_source resolves to no platform, so the search can't be narrowed.+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("spring_sale_2024!", "some_partner", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ assert result.proposals[0].method == "fuzzy_unscoped"+ assert result.proposals[0].safe_to_batch is False++ def test_scoped_match_ignores_other_platforms_campaigns(self):+ campaigns = [+ _campaign("spring_sale_2024", "1", source="google"),+ _campaign("sprng_sale_2025", "2", source="meta"),+ ]+ utm_events = _events(("sprng_sale_2024", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ assert result.proposals[0].integration == "GoogleAds"+ assert result.proposals[0].clean_name == "spring_sale_2024"++ def test_unscoped_refuses_a_name_two_platforms_both_run(self):+ # Identical spellings tie *at* the top, so the margin reads 100 and only the spend+ # tiebreak separated them.+ campaigns = [+ _campaign("spring_sale_2024", "1", spend=9000.0, source="google"),+ _campaign("spring_sale_2024", "2", spend=4000.0, source="meta"),+ ]+ utm_events = _events(("sprng_sale_2024", "some_partner", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert result.proposals == []+ assert len(result.ambiguous) == 1+ assert "GoogleAds and MetaAds" in result.ambiguous[0].reason++ def test_unscoped_verdict_does_not_move_with_the_budget(self):+ # Identical evidence, opposite spend: a verdict that flips here follows the budget.+ def integrations_for(google_spend: float, meta_spend: float) -> list[str]:+ campaigns = [+ _campaign("spring_sale_2024", "1", spend=google_spend, source="google"),+ _campaign("spring_sale_2024", "2", spend=meta_spend, source="meta"),+ ]+ utm_events = _events(("sprng_sale_2024", "some_partner", 900))+ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)+ return [proposal.integration for proposal in result.proposals]++ assert integrations_for(9000.0, 1000.0) == integrations_for(1000.0, 9000.0) == []++ def test_scoped_still_proposes_when_another_platform_shares_the_name(self):+ # utm_source names google, so the shared name isn't ambiguous and the proposal survives.+ campaigns = [+ _campaign("spring_sale_2024", "1", spend=9000.0, source="google"),+ _campaign("spring_sale_2024", "2", spend=4000.0, source="meta"),+ ]+ utm_events = _events(("sprng_sale_2024", "google", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ assert result.proposals[0].integration == "GoogleAds"++ def test_canonical_source_alias_still_scopes(self):+ campaigns = [_campaign("spring_sale_2024", source="meta")]+ utm_events = _events(("sprng_sale_2024", "facebook", 900))++ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)++ assert len(result.proposals) == 1+ assert result.proposals[0].method == "fuzzy_exact_scope"+ assert result.proposals[0].integration == "MetaAds"+++class TestBatchSafety:+ def test_high_score_clear_margin_is_batchable(self):+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("spring_sale_2024 ", "google", 900))++ proposal = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS).proposals[0]++ assert proposal.safe_to_batch is True++ def test_merely_good_match_is_not_batchable(self):+ campaigns = [_campaign("spring_sale_2024")]+ utm_events = _events(("sprng_sle_2024", "google", 900))++ proposals = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS).proposals++ # 93.3: above the proposal cutoff, below the batch bar. Both halves asserted, because+ # `[] or not safe_to_batch` also passes when nothing is proposed.+ assert len(proposals) == 1+ assert SCORE_CUTOFF < proposals[0].score < BATCH_SCORE+ assert proposals[0].safe_to_batch is False+++class TestScale:+ def test_stays_fast_at_the_documented_caps(self):+ # 500 is the query's LIMIT, 100 is MAX_UNMATCHED_VALUES.+ campaigns = [_campaign(f"campaign_number_{i:04d}", str(i), spend=float(i)) for i in range(500)]+ utm_events = _events(*[(f"campaign_numbr_{i:04d}", "google", 100) for i in range(100)])++ started = time.perf_counter()+ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)+ elapsed = time.perf_counter() - started++ assert elapsed < 2.0, f"took {elapsed:.2f}s"+ # Or the timing would pass for a suggester that bailed out. All 100 land in `ambiguous`:+ # 500 names one digit apart is a wall of near-ties, i.e. the slowest path.+ assert len(result.proposals) + len(result.ambiguous) + len(result.unresolved) == 100++ def test_oversized_values_cannot_slow_the_fuzzy_pass(self):+ # `utm_campaign` comes off an event property, which has no length bound. At the documented+ # caps but 20k characters a side this took 309 seconds; the length cap is what holds it at+ # milliseconds, so the assertion is the point of the test rather than the timing.+ pad = "y" * 20_000+ campaigns = [_campaign(f"{pad}_camp_{i:04d}", str(i), spend=float(i)) for i in range(500)]+ utm_events = _events(*[(f"{pad}_camp_{i:04d}z", "google", 100) for i in range(100)])++ started = time.perf_counter()+ result = suggest_campaign_name_mappings(campaigns, utm_events, NO_MAPPINGS)+ elapsed = time.perf_counter() - started++ assert elapsed < 2.0, f"took {elapsed:.2f}s"+ # Dropped outright rather than truncated: a mapping has to carry the whole raw value to+ # apply, and a 20k-character utm_campaign is not a typo of any real campaign name.+ assert result.proposals == []+ assert result.ambiguous == []+ assert result.unresolved == []diff --git a/products/marketing_analytics/backend/services/test_mapping_suggester.py b/products/marketing_analytics/backend/services/test_mapping_suggester.pyindex 0fcbfc206a3c..f8eabf822c21 100644--- a/products/marketing_analytics/backend/services/test_mapping_suggester.py+++ b/products/marketing_analytics/backend/services/test_mapping_suggester.py@@ -7,9 +7,34 @@ from products.marketing_analytics.backend.services.attribution_health import (AttributionHealthResponse,UnmatchedUtmSample,)+from products.marketing_analytics.backend.services.campaign_mapping_suggester import (+ CampaignMappingProposal,+ CampaignMappingSuggestions,+)from products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappingsfrom products.marketing_analytics.backend.services.native_integrations import NativeIntegration+_MODULE = "products.marketing_analytics.backend.services.mapping_suggester"+++def _proposal(raw: str, clean: str, *, events: int = 100, confidence: float = 0.8) -> CampaignMappingProposal:+ return CampaignMappingProposal(+ integration="GoogleAds",+ integration_display_name="Google Ads",+ clean_name=clean,+ raw_utm_campaign=raw,+ event_count=events,+ campaign_spend=1000.0,+ score=95.0,+ confidence=confidence,+ safe_to_batch=False,+ method="fuzzy_exact_scope",+ reason=f"'{raw}' looks like a typo of '{clean}'",+ observed_utm_source="google",+ expected_utm_campaign=clean,+ expected_utm_source="google",+ )+def _sample(raw_value: str, event_count: int, suggested_integration: NativeIntegration | None) -> UnmatchedUtmSample:return UnmatchedUtmSample(raw_value=raw_value, event_count=event_count, suggested_integration=suggested_integration)@@ -56,6 +81,100 @@ class TestSuggestUtmMappings(APIBaseTest):)self.mock_custom.return_value = {}+ @pytest.mark.asyncio+ async def test_campaign_suggestions_are_no_longer_hardcoded_empty(self):+ # This field returned [] unconditionally while the suggester that fills it lived beside it,+ # so every MCP consumer saw "no campaign mappings to make" no matter the data.+ proposals = CampaignMappingSuggestions(proposals=[_proposal("sprng_sale", "spring_sale")])++ response = await suggest_utm_mappings(self.team, campaign_proposals=proposals)++ assert len(response.campaign_suggestions) == 1+ suggestion = response.campaign_suggestions[0]+ assert suggestion.integration == "google_ads" # NativeIntegration key, not the PascalCase value+ assert suggestion.suggested_clean_name == "spring_sale"+ assert suggestion.raw_campaign_values == ["sprng_sale"]+ assert suggestion.method == "fuzzy_exact_scope"++ @pytest.mark.asyncio+ async def test_proposals_for_one_target_fold_into_a_single_suggestion(self):+ # `campaign_name_mappings` stores one clean name with many raw values, so several orphans+ # pointing at the same campaign are one entry, not three.+ proposals = CampaignMappingSuggestions(+ proposals=[+ _proposal("sprng_sale", "spring_sale", events=100, confidence=0.9),+ _proposal("spring_sle", "spring_sale", events=50, confidence=0.6),+ ]+ )++ response = await suggest_utm_mappings(self.team, campaign_proposals=proposals)++ assert len(response.campaign_suggestions) == 1+ suggestion = response.campaign_suggestions[0]+ assert suggestion.raw_campaign_values == ["spring_sle", "sprng_sale"]+ assert suggestion.event_count_30d == 150+ # Applied as a unit, so it is only as trustworthy as its weakest member.+ assert suggestion.confidence == 0.6++ @pytest.mark.asyncio+ async def test_ambiguous_campaigns_are_never_offered_as_mappings(self):+ # They exist because the suggester refused to guess; this field is things to apply.+ proposals = CampaignMappingSuggestions(proposals=[], ambiguous=[object()]) # type: ignore[list-item]++ response = await suggest_utm_mappings(self.team, campaign_proposals=proposals)++ assert response.campaign_suggestions == []++ @pytest.mark.asyncio+ async def test_derives_proposals_when_the_caller_does_not_inject_them(self):+ with (+ patch(f"{_MODULE}.get_campaigns_with_spend_async", new_callable=AsyncMock) as campaigns,+ patch(f"{_MODULE}.get_utm_campaign_catalogue_async", new_callable=AsyncMock) as catalogue,+ patch(f"{_MODULE}.load_team_mappings_async", new_callable=AsyncMock),+ patch(f"{_MODULE}.suggest_campaign_name_mappings") as suggester,+ ):+ campaigns.return_value = []+ catalogue.return_value = {}+ suggester.return_value = CampaignMappingSuggestions(proposals=[_proposal("sprng", "spring")])++ response = await suggest_utm_mappings(self.team)++ assert [s.suggested_clean_name for s in response.campaign_suggestions] == ["spring"]+ campaigns.assert_awaited_once()+ catalogue.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_injected_proposals_skip_the_extra_queries(self):+ with (+ patch(f"{_MODULE}.get_campaigns_with_spend_async", new_callable=AsyncMock) as campaigns,+ patch(f"{_MODULE}.get_utm_campaign_catalogue_async", new_callable=AsyncMock) as catalogue,+ ):+ await suggest_utm_mappings(self.team, campaign_proposals=CampaignMappingSuggestions())++ campaigns.assert_not_awaited()+ catalogue.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_a_broken_campaign_query_does_not_lose_the_source_suggestions(self):+ # campaign_suggestions going back to [] is what every consumer has today; taking the+ # source suggestions down with it would be a regression against the current behaviour.+ sample = _sample("facebook_paid", 120, "meta_ads")+ self.mock_attribution.return_value = AttributionHealthResponse(+ lookback_days=30,+ 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],+ )+ with patch(f"{_MODULE}.get_campaigns_with_spend_async", new_callable=AsyncMock) as campaigns:+ campaigns.side_effect = RuntimeError("clickhouse is having a day")++ response = await suggest_utm_mappings(self.team)++ assert response.campaign_suggestions == []+ assert [s.raw_utm_source for s in response.source_suggestions] == ["facebook_paid"]+@pytest.mark.asyncioasync def test_no_unmatched_returns_empty_suggestions(self):response = await suggest_utm_mappings(self.team)@@ -132,10 +251,15 @@ class TestSuggestUtmMappings(APIBaseTest):assert any("Meta Ads" in n and "showing top 3" in n for n in response.notes)@pytest.mark.asyncio- async def test_v1_does_not_emit_campaign_suggestions(self):- response = await suggest_utm_mappings(self.team)- assert response.campaign_suggestions == []- assert any("Campaign clustering" in n for n in response.notes)+ async def test_the_note_explains_why_an_orphan_may_be_absent(self):+ # Replaces `test_v1_does_not_emit_campaign_suggestions`, which pinned the placeholder+ # behaviour: the field hardcoded to [] plus a "not yet implemented" note. Both are now+ # wrong — it is populated, and the remaining reason a campaign is missing is that the+ # suggester refused to guess between near-ties, which a consumer has to be told.+ response = await suggest_utm_mappings(self.team, campaign_proposals=CampaignMappingSuggestions())++ assert not any("not yet implemented" in n for n in response.notes)+ assert any("Near-ties are deliberately withheld" in n for n in response.notes)@pytest.mark.asyncioasync def test_dedupe_when_same_raw_value_appears_in_multiple_integrations(self):diff --git a/products/marketing_analytics/backend/services/test_utm_audit.py b/products/marketing_analytics/backend/services/test_utm_audit.pyindex bacd4df21e6c..1decf3a63858 100644--- a/products/marketing_analytics/backend/services/test_utm_audit.py+++ b/products/marketing_analytics/backend/services/test_utm_audit.py@@ -237,6 +237,70 @@ class TestCrossReferenceIssueKinds:assert issue.shared_with_integrations == []assert issue.suggested_actions == [SuggestedAction.FIX_PLATFORM_URLS]+ def test_not_linked_offers_the_typo_mapping_when_one_exists(self):+ # The audit sees no pageviews; the suggester holds the other half, the typo'd value+ # with real traffic on it.+ campaigns = [Campaign("spring_sale_2024", "456", "google", 500.0, 100, 5000)]+ utm_events = {("sprng_sale_2024", "google"): 1340}++ results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, DEFAULT_KNOWN_SOURCES)++ issue = results[0].issues[0]+ assert issue.kind == UtmIssueKind.NOT_LINKED+ assert issue.mapping_candidate == "sprng_sale_2024"+ # Appended, not prepended: fixing the URL is still the cure.+ assert issue.suggested_actions == [+ SuggestedAction.FIX_PLATFORM_URLS,+ SuggestedAction.ADD_CAMPAIGN_NAME_MAPPING,+ ]++ def test_candidate_stays_on_the_platform_the_suggester_named(self):+ # A campaign name is unique only within a platform, and the traffic is tagged google.+ # Keying on the name alone explained meta's row with google's traffic.+ campaigns = [+ Campaign("brand", "1", "google", 9000.0, 100, 5000),+ Campaign("brand", "2", "meta", 4000.0, 100, 5000),+ ]+ utm_events = {("brnd", "google"): 900}++ results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, DEFAULT_KNOWN_SOURCES)++ google = next(r for r in results if r.source_name == "google")+ meta = next(r for r in results if r.source_name == "meta")+ assert google.issues[0].mapping_candidate == "brnd"+ assert meta.issues[0].mapping_candidate == ""+ assert SuggestedAction.ADD_CAMPAIGN_NAME_MAPPING not in meta.issues[0].suggested_actions++ def test_not_linked_offers_nothing_when_the_match_is_ambiguous(self):+ # The audit must not launder the suggester's refusal into a confident suggestion.+ campaigns = [+ Campaign("uk_uss", "1", "google", 5000.0, 10, 100),+ Campaign("email_uk", "2", "google", 4000.0, 10, 100),+ ]+ utm_events = {("uk_us", "google"): 900}++ results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, DEFAULT_KNOWN_SOURCES)++ for result in results:+ for issue in result.issues:+ assert issue.mapping_candidate == ""+ assert SuggestedAction.ADD_CAMPAIGN_NAME_MAPPING not in issue.suggested_actions++ @patch("products.marketing_analytics.backend.services.utm_audit.suggest_campaign_name_mappings")+ def test_audit_survives_a_broken_suggester(self, mock_suggester):+ # The candidate is advisory; the `except` is all that keeps a suggester bug from+ # 500ing the audit.+ mock_suggester.side_effect = RuntimeError("boom")+ campaigns = [Campaign("spring_sale_2024", "456", "google", 500.0, 100, 5000)]+ utm_events = {("sprng_sale_2024", "google"): 1340}++ results = _cross_reference(campaigns, utm_events, NO_MAPPINGS, DEFAULT_KNOWN_SOURCES)++ issue = results[0].issues[0]+ assert issue.kind == UtmIssueKind.NOT_LINKED+ assert issue.mapping_candidate == ""+ assert issue.suggested_actions == [SuggestedAction.FIX_PLATFORM_URLS]+def test_no_tagged_events_when_alt_source_is_another_default(self):# Bing campaign but events only arrive with utm_source=google (Google's default).# Mapping google→bing would break Google attribution, so ADD_SOURCE_MAPPING must not be suggested.diff --git a/products/marketing_analytics/backend/services/test_utm_matching.py b/products/marketing_analytics/backend/services/test_utm_matching.pyindex 49cc54a5cd22..fed13440c848 100644--- a/products/marketing_analytics/backend/services/test_utm_matching.py+++ b/products/marketing_analytics/backend/services/test_utm_matching.py@@ -11,7 +11,10 @@ from products.marketing_analytics.backend.services.utm_matching import (build_source_lookup,get_match_field,get_match_value,+ get_match_value_raw,+ group_campaigns_by_source,load_team_mappings,+ normalize_source_name,resolve_source,)@@ -239,3 +242,41 @@ class TestCampaignsQueryShape(BaseTest):interval=None,now=timezone.now(),)+++class TestSharedMatchHelpers(BaseTest):+ """These existed as private copies in both suggesters before they moved here."""++ PREFERS_ID = TeamMappings(+ source_to_integration={}, campaign_aliases={}, field_preferences={"google": "campaign_id"}+ )++ def test_the_lowercased_value_is_the_raw_one_folded(self):+ # They differ only by casing; a second copy of the *field choice* is what drifts.+ campaign = _campaign("Spring_Sale_2024", "PROMO_1234", "google")++ for mappings in (NO_MAPPINGS, self.PREFERS_ID):+ assert get_match_value(campaign, mappings) == get_match_value_raw(campaign, mappings).lower()++ def test_the_raw_value_keeps_platform_casing(self):+ # What gets stored in campaign_name_mappings has to equal what the platform calls it.+ campaign = _campaign("Spring_Sale_2024", "PROMO_1234", "google")++ assert get_match_value_raw(campaign, NO_MAPPINGS) == "Spring_Sale_2024"+ assert get_match_value_raw(campaign, self.PREFERS_ID) == "PROMO_1234"++ def test_grouping_skips_campaigns_with_no_source(self):+ # A blank source would otherwise form its own "" group.+ campaigns = [+ _campaign("a", "1", "GOOGLE"),+ _campaign("b", "2", " google "),+ _campaign("c", "3", " "),+ ]++ grouped = group_campaigns_by_source(campaigns)++ assert set(grouped) == {"google"}+ assert [c.campaign_name for c in grouped["google"]] == ["a", "b"]++ def test_source_names_normalize_consistently(self):+ assert normalize_source_name(" GoogleAds ") == "googleads"diff --git a/products/marketing_analytics/backend/services/types.py b/products/marketing_analytics/backend/services/types.pyindex 30d7bb0488ff..afb67e2ebbc7 100644--- a/products/marketing_analytics/backend/services/types.py+++ b/products/marketing_analytics/backend/services/types.py@@ -42,6 +42,13 @@ class SuggestedAction(StrEnum):# Switch this integration's match field from campaign_name to campaign_id to avoid# cross-platform name collisions. Caveat: requires utm_campaign URLs to use the ID too.SWITCH_TO_ID_MATCH = "switch_to_id_match"+ # Only offered when the suggester found a confident match; `mapping_candidate` holds it.+ # Secondary to FIX_PLATFORM_URLS, which cures the tagging bug itself.+ ADD_CAMPAIGN_NAME_MAPPING = "add_campaign_name_mapping"+++# Same reason as UTM_ISSUE_KIND_CHOICES above: a stable enum name in the generated schema.+SUGGESTED_ACTION_CHOICES = [action.value for action in SuggestedAction]class MatchType(StrEnum):@@ -74,6 +81,9 @@ class UtmIssue:missing_source_count: int = 0# Ordered list of suggested remediations. First entry is the primary recommendation.suggested_actions: list[SuggestedAction] = dataclass_field(default_factory=list)+ # The orphaned value that looks like a typo of this campaign. Set only alongside+ # ADD_CAMPAIGN_NAME_MAPPING, and the half the audit can't see on its own.+ mapping_candidate: str = ""@dataclassdiff --git a/products/marketing_analytics/backend/services/utm_audit.py b/products/marketing_analytics/backend/services/utm_audit.pyindex 8878f53bde66..9068a5c9a7cb 100644--- a/products/marketing_analytics/backend/services/utm_audit.py+++ b/products/marketing_analytics/backend/services/utm_audit.py@@ -17,6 +17,8 @@ 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.services.campaign_mapping_suggester import suggest_campaign_name_mappings+from products.marketing_analytics.backend.services.native_integrations import native_for_primary_sourcefrom products.marketing_analytics.backend.services.types import (AlternativeSource,Campaign,@@ -37,6 +39,8 @@ from products.marketing_analytics.backend.services.utm_matching import (get_match_field,get_match_value,load_team_mappings,+ normalize_campaign_name,+ normalize_source_name,resolve_source,)@@ -203,13 +207,18 @@ def get_utm_campaign_catalogue()utm_map: dict[tuple[str, str], int] = {}for row in result.results or []:- campaign = (row[0] or "").lower().strip()- source = (row[1] or "").lower().strip()+ campaign = normalize_campaign_name(row[0] or "")+ source = normalize_source_name(row[1] or "")count = int(row[2] or 0)utm_map[(campaign, source)] = countreturn utm_map+# Same reason as `run_utm_audit_async`: sync ORM and HogQL, gathered by async callers.+get_campaigns_with_spend_async = database_sync_to_async(get_campaigns_with_spend)+get_utm_campaign_catalogue_async = database_sync_to_async(get_utm_campaign_catalogue)++def _build_all_utm_events(campaigns: list[Campaign],utm_events: dict[tuple[str, str], int],@@ -272,8 +281,8 @@ def _compute_campaign_stats(mappings: TeamMappings,) -> _CampaignStats:"""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()+ campaign_name_lower = normalize_campaign_name(campaign.campaign_name)+ source_name_lower = normalize_source_name(campaign.source_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_name@@ -421,6 +430,37 @@ def _build_issue()+def _mapping_candidates(+ campaigns: list[Campaign],+ utm_events: dict[tuple[str, str], int],+ mappings: TeamMappings,+) -> dict[tuple[str, str], str]:+ """(integration, target match value) -> the orphaned `utm_campaign` the suggester maps onto it.++ Keyed by match value, not campaign name, because that is what a proposal names and what+ id-matching integrations join on. The integration is half the key because a name is unique only+ within a platform — without it, one platform's candidate explained another's unlinked campaign.++ Only confident proposals: `ambiguous` and `unresolved` are excluded by construction. Contained,+ so a broken suggester leaves every issue exactly as it was.+ """+ try:+ proposals = suggest_campaign_name_mappings(campaigns, utm_events, mappings).proposals+ except Exception:+ logger.exception("utm_audit.mapping_candidates_failed")+ return {}++ # Highest event count wins when several orphans point at one campaign.+ best: dict[tuple[str, str], str] = {}+ best_count: dict[tuple[str, str], int] = {}+ for proposal in proposals:+ key = (proposal.integration, normalize_campaign_name(proposal.clean_name))+ if proposal.event_count > best_count.get(key, -1):+ best[key] = proposal.raw_utm_campaign+ best_count[key] = proposal.event_count+ return best++def _cross_reference(campaigns: list[Campaign],utm_events: dict[tuple[str, str], int],@@ -452,12 +492,28 @@ def _cross_reference(if stats.exact_count > 0:exact_matches_by_name.setdefault(stats.campaign_name_lower, set()).add(stats.source_name_lower)+ # The audit sees a campaign is unlinked but not why; the suggester holds the other half.+ mapping_candidates = _mapping_candidates(campaigns, utm_events, mappings)+results: list[CampaignAuditResult] = []for stats in all_stats:all_matching_sources = exact_matches_by_name.get(stats.campaign_name_lower, set())shared_with = all_matching_sources - {stats.source_name_lower}issue = _build_issue(stats, shared_with, known_sources)+ if issue is not None and issue.kind == UtmIssueKind.NOT_LINKED:+ # Same key the proposals were bucketed under, so id-matching integrations look up+ # correctly and a shared name can't cross platforms.+ native = native_for_primary_source(stats.campaign.source_name)+ candidate = (+ mapping_candidates.get((native.value, get_match_value(stats.campaign, mappings)))+ if native is not None+ else None+ )+ if candidate:+ issue.mapping_candidate = candidate+ # Appended: the order is the recommendation order, and the URL fix is the cure.+ issue.suggested_actions.append(SuggestedAction.ADD_CAMPAIGN_NAME_MAPPING)issues = [issue] if issue is not None else []results.append(diff --git a/products/marketing_analytics/backend/services/utm_matching.py b/products/marketing_analytics/backend/services/utm_matching.pyindex 642a5a807b4c..286f33a4d7ea 100644--- a/products/marketing_analytics/backend/services/utm_matching.py+++ b/products/marketing_analytics/backend/services/utm_matching.py@@ -76,7 +76,7 @@ def load_team_mappings(team: Team) -> TeamMappings:raw_value=raw_value,)continue- source_to_integration[raw_value.lower().strip()] = primary+ source_to_integration[normalize_source_name(raw_value)] = primary# Build campaign aliases: clean_campaign_name -> set of raw utm values# e.g. campaign_name_mappings = {"GoogleAds": {"brand_campaign": ["partner_q1", "brand_q1"]}}@@ -84,11 +84,11 @@ def load_team_mappings(team: Team) -> TeamMappings: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()+ clean_lower = normalize_campaign_name(clean_name)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())+ campaign_aliases[clean_lower].add(normalize_campaign_name(raw_value))# Build field preferences, keyed by primary source so campaign rows can be looked# up directly by their `source_name`.@@ -120,7 +120,7 @@ def build_known_sources(mappings: TeamMappings) -> set[str]:known: set[str] = set()for sources in INTEGRATION_DEFAULT_SOURCES.values():for source in sources:- known.add(source.lower().strip())+ known.add(normalize_source_name(source))# Custom mappings already flattened to source -> primary_sourceknown.update(mappings.source_to_integration.keys())return known@@ -152,16 +152,53 @@ def resolve_source(utm_source: str, mappings: TeamMappings) -> str:return default_alias_to_primary().get(normalize(utm_source), utm_source)+def normalize_source_name(source_name: str) -> str:+ """Canonical form of a `source_name`, for keying anything per integration."""+ return source_name.lower().strip()+++def normalize_campaign_name(campaign_name: str) -> str:+ """Canonical form of a campaign name or `utm_campaign` value, for comparing the two.++ A function rather than two method calls at each site: matching hinges on both sides folding+ the same way, and halves that stop agreeing match nothing, silently.+ """+ return campaign_name.lower().strip()++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)+ return mappings.field_preferences.get(normalize_source_name(source_name), 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."""+def get_match_value_raw(campaign: Campaign, mappings: TeamMappings) -> str:+ """The platform-side value a mapping has to produce, in its original casing.++ The field choice lives here, not at each call site: proposing a name to an integration that+ matches on id writes a mapping that never joins.+ """if get_match_field(campaign.source_name, mappings) == "campaign_id":- return campaign.campaign_id.lower().strip()- return campaign.campaign_name.lower().strip()+ return campaign.campaign_id.strip()+ return campaign.campaign_name.strip()+++def get_match_value(campaign: Campaign, mappings: TeamMappings) -> str:+ """`get_match_value_raw`, lowercased for comparison against utm_campaign values."""+ return normalize_campaign_name(get_match_value_raw(campaign, mappings))+++def group_campaigns_by_source(campaigns: list[Campaign]) -> dict[str, list[Campaign]]:+ """Campaigns keyed by normalized `source_name`, skipping any that don't name one.++ Skipping matters: a blank source would otherwise collect its own `""` group.+ """+ grouped: dict[str, list[Campaign]] = {}+ for campaign in campaigns:+ source_name = normalize_source_name(campaign.source_name)+ if not source_name:+ continue+ grouped.setdefault(source_name, []).append(campaign)+ return groupeddef build_campaign_lookup(@@ -178,7 +215,7 @@ def build_campaign_lookup(lookup: dict[str, CampaignMatch] = {}for campaign in campaigns:match_value = get_match_value(campaign, mappings)- campaign_name_lower = campaign.campaign_name.lower().strip()+ campaign_name_lower = normalize_campaign_name(campaign.campaign_name)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()):@@ -197,7 +234,7 @@ def build_source_lookup(campaigns: list[Campaign], mappings: TeamMappings) -> di"""lookup: dict[str, str] = {}for campaign in campaigns:- source_name_lower = campaign.source_name.lower().strip()+ source_name_lower = normalize_source_name(campaign.source_name)if source_name_lower not in lookup:lookup[source_name_lower] = MatchType.AUTOfor custom_source, primary_source in mappings.source_to_integration.items():diff --git a/products/marketing_analytics/backend/test_api_serializer_parity.py b/products/marketing_analytics/backend/test_api_serializer_parity.pynew file mode 100644index 000000000000..fc0c280e088b--- /dev/null+++ b/products/marketing_analytics/backend/test_api_serializer_parity.py@@ -0,0 +1,75 @@+"""Every field a service dataclass carries must survive its response serializer.++A DRF `Serializer` drops an undeclared key silently — no error, no failing test, so a forgotten+field looks exactly like the feature not existing. `UtmIssue.suggested_actions` reached no consumer+for that reason while every service test passed, because they assert on the dataclass.+"""++from dataclasses import fields as dataclass_fields++from posthog.test.base import BaseTest++from parameterized import parameterized++from products.marketing_analytics.backend.api import (+ CampaignAuditResultSerializer,+ CampaignMappingSuggestionSerializer,+ SourceMappingSuggestionSerializer,+ UtmAuditResponseSerializer,+ UtmEventSerializer,+ UtmIssueSerializer,+)+from products.marketing_analytics.backend.services.mapping_suggester import (+ CampaignMappingSuggestion,+ SourceMappingSuggestion,+)+from products.marketing_analytics.backend.services.types import (+ CampaignAuditResult,+ UtmAuditResponse,+ UtmEvent,+ UtmIssue,+)++# Deliberate omissions go here with a reason, so "not serialized" stays a decision.+_INTENTIONALLY_UNSERIALIZED: dict[str, set[str]] = {}+++class TestSerializerFieldParity(BaseTest):+ @parameterized.expand(+ [+ ("UtmIssue", UtmIssue, UtmIssueSerializer),+ ("CampaignAuditResult", CampaignAuditResult, CampaignAuditResultSerializer),+ ("UtmEvent", UtmEvent, UtmEventSerializer),+ ("UtmAuditResponse", UtmAuditResponse, UtmAuditResponseSerializer),+ ("SourceMappingSuggestion", SourceMappingSuggestion, SourceMappingSuggestionSerializer),+ ("CampaignMappingSuggestion", CampaignMappingSuggestion, CampaignMappingSuggestionSerializer),+ ]+ )+ def test_every_dataclass_field_is_serialized(self, name, dataclass_type, serializer_type):+ declared = set(serializer_type().get_fields())+ expected = {f.name for f in dataclass_fields(dataclass_type)} - _INTENTIONALLY_UNSERIALIZED.get(name, set())++ missing = expected - declared+ assert not missing, (+ f"{serializer_type.__name__} drops {sorted(missing)} from {name}. DRF discards undeclared "+ f"keys silently, so these never reach the API or MCP. Declare them, or add them to "+ f"_INTENTIONALLY_UNSERIALIZED with a reason."+ )++ @parameterized.expand(+ [+ ("UtmIssue", UtmIssue, UtmIssueSerializer),+ ("CampaignAuditResult", CampaignAuditResult, CampaignAuditResultSerializer),+ ("UtmEvent", UtmEvent, UtmEventSerializer),+ ("UtmAuditResponse", UtmAuditResponse, UtmAuditResponseSerializer),+ ("SourceMappingSuggestion", SourceMappingSuggestion, SourceMappingSuggestionSerializer),+ ("CampaignMappingSuggestion", CampaignMappingSuggestion, CampaignMappingSuggestionSerializer),+ ]+ )+ def test_serializer_declares_no_field_the_dataclass_lacks(self, name, dataclass_type, serializer_type):+ # A serializer field with no source is a required key the service can never supply.+ declared = set(serializer_type().get_fields())+ available = {f.name for f in dataclass_fields(dataclass_type)}++ extra = declared - available+ assert not extra, f"{serializer_type.__name__} declares {sorted(extra)}, which {name} does not carry."diff --git a/products/marketing_analytics/backend/test_max_tools.py b/products/marketing_analytics/backend/test_max_tools.pyindex ea807cfe9ab6..00396d1e66ed 100644--- a/products/marketing_analytics/backend/test_max_tools.py+++ b/products/marketing_analytics/backend/test_max_tools.py@@ -46,6 +46,7 @@ from products.marketing_analytics.backend.services.data_source_health import ()from products.marketing_analytics.backend.services.event_suggestions import CandidateEvent, EventSuggestionsResponsefrom products.marketing_analytics.backend.services.mapping_suggester import (+ CampaignMappingSuggestion,CatalogueEntry,CurrentMapping,RawUnmatchedSample,@@ -719,6 +720,26 @@ class TestFormatUtmMappingSuggestionsForLlm(BaseTest):assert "facebook_paid" in resultassert "Meta Ads" in result+ def test_campaign_suggestions_shown(self):+ # The tool returns the response dict as its artifact, but Max composes its reply from this+ # string. A section missing here is a suggestion the user is never told about.+ suggestion = CampaignMappingSuggestion(+ integration="google_ads",+ integration_display_name="Google Ads",+ suggested_clean_name="autumn_clearance",+ raw_campaign_values=["autum_clearnce"],+ confidence=0.72,+ method="fuzzy_exact_scope",+ reason="'autum_clearnce' — 150 events, 93% similar to Google Ads campaign 'autumn_clearance'.",+ event_count_30d=150,+ )+ response = self._make_empty_response()+ response.campaign_suggestions = [suggestion]+ result = _format_utm_mapping_suggestions_for_llm(response)+ assert "autum_clearnce" in result+ assert "autumn_clearance" in result+ assert "Google Ads" in result+def test_no_suggestions_shows_none(self):result = _format_utm_mapping_suggestions_for_llm(self._make_empty_response())assert "none" in result.lower()diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.tsindex c08dd743ca3d..289dcecc3e98 100644--- a/products/marketing_analytics/frontend/generated/api.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts@@ -385,6 +385,8 @@ export interface SourceMappingSuggestionApi {suggested_target_display_name: string/** Why this mapping is suggested */reason: string+ /** Events carrying this raw utm_source in the window. Suggestions are ordered by it. */+ event_count_30d: number}export interface CampaignMappingSuggestionApi {@@ -402,6 +404,8 @@ export interface CampaignMappingSuggestionApi {method: string/** Why these campaign values were clustered together */reason: string+ /** Events across every raw value folded into this suggestion. Suggestions are ordered by it. */+ event_count_30d: number}export interface RawUnmatchedSampleApi {@@ -452,7 +456,7 @@ export interface CurrentMappingApi {export interface UtmMappingSuggestionsResponseApi {/** Suggested custom_source_mappings entries */source_suggestions: SourceMappingSuggestionApi[]- /** Suggested campaign-name clusters (empty in v1) */+ /** campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real campaign. Near-ties are withheld, so an absent campaign may still be mappable by hand. */campaign_suggestions: CampaignMappingSuggestionApi[]/** All unmatched raw utm_source values worth reviewing */raw_unmatched_samples: RawUnmatchedSampleApi[]@@ -505,6 +509,21 @@ export interface UtmAlternativeSourceApi {event_count: number}+/**+ * * `fix_platform_urls` - fix_platform_urls+ * * `add_source_mapping` - add_source_mapping+ * * `switch_to_id_match` - switch_to_id_match+ * * `add_campaign_name_mapping` - add_campaign_name_mapping+ */+export type SuggestedActionsEnumApi = (typeof SuggestedActionsEnumApi)[keyof typeof SuggestedActionsEnumApi]++export const SuggestedActionsEnumApi = {+ FixPlatformUrls: 'fix_platform_urls',+ AddSourceMapping: 'add_source_mapping',+ SwitchToIdMatch: 'switch_to_id_match',+ AddCampaignNameMapping: 'add_campaign_name_mapping',+} as const+export interface UtmIssueApi {/** The UTM field with the issue (e.g. utm_campaign, utm_source) */field: string@@ -529,6 +548,10 @@ export interface UtmIssueApi {shared_with_integrations: string[]/** Pageviews that matched this campaign but carried no utm_source, on any issue kind */missing_source_count: number+ /** Recommended remediations, most-recommended first. fix_platform_urls cures the tagging bug itself; the others are workarounds that leave the bad URLs in place. */+ suggested_actions: SuggestedActionsEnumApi[]+ /** The orphaned utm_campaign value that looks like a typo of this campaign, when one was found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, including when several candidates tie and picking one could misattribute spend. */+ mapping_candidate: string}export interface CampaignAuditResultApi {diff --git a/products/marketing_analytics/frontend/generated/api.zod.schemas.ts b/products/marketing_analytics/frontend/generated/api.zod.schemas.tsindex d787d28caaf9..428f0d93e96b 100644--- a/products/marketing_analytics/frontend/generated/api.zod.schemas.ts+++ b/products/marketing_analytics/frontend/generated/api.zod.schemas.ts@@ -769,6 +769,9 @@ export const SourceMappingSuggestionApi = zod.object({suggested_target: zod.string().describe('Integration key it maps to'),suggested_target_display_name: zod.string().describe('Human-readable name of the suggested integration'),reason: zod.string().describe('Why this mapping is suggested'),+ event_count_30d: zod+ .number()+ .describe('Events carrying this raw utm_source in the window. Suggestions are ordered by it.'),})export type SourceMappingSuggestionApi = zod.input<typeof SourceMappingSuggestionApi>@@ -782,6 +785,9 @@ export const CampaignMappingSuggestionApi = zod.object({confidence: zod.number().describe('Confidence score for the clustering (0-1)'),method: zod.string().describe('Mapping method'),reason: zod.string().describe('Why these campaign values were clustered together'),+ event_count_30d: zod+ .number()+ .describe('Events across every raw value folded into this suggestion. Suggestions are ordered by it.'),})export type CampaignMappingSuggestionApi = zod.input<typeof CampaignMappingSuggestionApi>@@ -830,6 +836,9 @@ export const UtmMappingSuggestionsResponseApi = zod.object({.string().describe('Human-readable name of the suggested integration'),reason: zod.string().describe('Why this mapping is suggested'),+ event_count_30d: zod+ .number()+ .describe('Events carrying this raw utm_source in the window. Suggestions are ordered by it.'),})).describe('Suggested custom_source_mappings entries'),@@ -845,9 +854,16 @@ export const UtmMappingSuggestionsResponseApi = zod.object({confidence: zod.number().describe('Confidence score for the clustering (0-1)'),method: zod.string().describe('Mapping method'),reason: zod.string().describe('Why these campaign values were clustered together'),+ event_count_30d: zod+ .number()+ .describe(+ 'Events across every raw value folded into this suggestion. Suggestions are ordered by it.'+ ),}))- .describe('Suggested campaign-name clusters (empty in v1)'),+ .describe(+ 'campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real campaign. Near-ties are withheld, so an absent campaign may still be mappable by hand.'+ ),raw_unmatched_samples: zod.array(zod.object({@@ -914,6 +930,15 @@ export const UtmAlternativeSourceApi = zod.object({export type UtmAlternativeSourceApi = zod.input<typeof UtmAlternativeSourceApi>export type UtmAlternativeSourceApiOutput = zod.output<typeof UtmAlternativeSourceApi>+export const SuggestedActionsEnumApi = zod+ .enum(['fix_platform_urls', 'add_source_mapping', 'switch_to_id_match', 'add_campaign_name_mapping'])+ .describe(+ '\* `fix_platform_urls` - fix_platform_urls\n\* `add_source_mapping` - add_source_mapping\n\* `switch_to_id_match` - switch_to_id_match\n\* `add_campaign_name_mapping` - add_campaign_name_mapping'+ )++export type SuggestedActionsEnumApi = zod.input<typeof SuggestedActionsEnumApi>+export type SuggestedActionsEnumApiOutput = zod.output<typeof SuggestedActionsEnumApi>+export const UtmIssueApi = zod.object({field: zod.string().describe('The UTM field with the issue (e.g. utm_campaign, utm_source)'),severity: zod@@ -943,6 +968,22 @@ export const UtmIssueApi = zod.object({missing_source_count: zod.number().describe('Pageviews that matched this campaign but carried no utm_source, on any issue kind'),+ suggested_actions: zod+ .array(+ zod+ .enum(['fix_platform_urls', 'add_source_mapping', 'switch_to_id_match', 'add_campaign_name_mapping'])+ .describe(+ '\* `fix_platform_urls` - fix_platform_urls\n\* `add_source_mapping` - add_source_mapping\n\* `switch_to_id_match` - switch_to_id_match\n\* `add_campaign_name_mapping` - add_campaign_name_mapping'+ )+ )+ .describe(+ 'Recommended remediations, most-recommended first. fix_platform_urls cures the tagging bug itself; the others are workarounds that leave the bad URLs in place.'+ ),+ mapping_candidate: zod+ .string()+ .describe(+ 'The orphaned utm_campaign value that looks like a typo of this campaign, when one was found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, including when several candidates tie and picking one could misattribute spend.'+ ),})export type UtmIssueApi = zod.input<typeof UtmIssueApi>@@ -990,6 +1031,27 @@ export const CampaignAuditResultApi = zod.object({missing_source_count: zod.number().describe('Pageviews that matched this campaign but carried no utm_source, on any issue kind'),+ suggested_actions: zod+ .array(+ zod+ .enum([+ 'fix_platform_urls',+ 'add_source_mapping',+ 'switch_to_id_match',+ 'add_campaign_name_mapping',+ ])+ .describe(+ '\* `fix_platform_urls` - fix_platform_urls\n\* `add_source_mapping` - add_source_mapping\n\* `switch_to_id_match` - switch_to_id_match\n\* `add_campaign_name_mapping` - add_campaign_name_mapping'+ )+ )+ .describe(+ 'Recommended remediations, most-recommended first. fix_platform_urls cures the tagging bug itself; the others are workarounds that leave the bad URLs in place.'+ ),+ mapping_candidate: zod+ .string()+ .describe(+ 'The orphaned utm_campaign value that looks like a typo of this campaign, when one was found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, including when several candidates tie and picking one could misattribute spend.'+ ),})).describe('List of detected UTM configuration issues'),@@ -1096,6 +1158,27 @@ export const UtmAuditResponseApi = zod.object({.describe('Pageviews that matched this campaign but carried no utm_source, on any issue kind'),+ suggested_actions: zod+ .array(+ zod+ .enum([+ 'fix_platform_urls',+ 'add_source_mapping',+ 'switch_to_id_match',+ 'add_campaign_name_mapping',+ ])+ .describe(+ '\* `fix_platform_urls` - fix_platform_urls\n\* `add_source_mapping` - add_source_mapping\n\* `switch_to_id_match` - switch_to_id_match\n\* `add_campaign_name_mapping` - add_campaign_name_mapping'+ )+ )+ .describe(+ 'Recommended remediations, most-recommended first. fix_platform_urls cures the tagging bug itself; the others are workarounds that leave the bad URLs in place.'+ ),+ mapping_candidate: zod+ .string()+ .describe(+ 'The orphaned utm_campaign value that looks like a typo of this campaign, when one was found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, including when several candidates tie and picking one could misattribute spend.'+ ),})).describe('List of detected UTM configuration issues'),diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yamlindex 3d811bc96350..34e69e577b29 100644--- a/products/marketing_analytics/mcp/tools.yaml+++ b/products/marketing_analytics/mcp/tools.yaml@@ -104,14 +104,18 @@ tools:idempotent: truetitle: Suggest utm_source → integration mappingsdescription: >- USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings,- custom_source_mappings, unmatched / non-integrated UTM values, or the question "what utm_sources do I have- and which ad platform do they belong to?". Returns full_utm_source_catalogue (every utm_source value seen on- events in the window, matched + unmatched, with event count and the integration it resolves to),- source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw- facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values- like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical +- team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.+ USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source OR utm_campaign mappings,+ custom_source_mappings, campaign_name_mappings, unmatched / non-integrated UTM values, typo'd campaign+ names, or the question "what utm_sources do I have and which ad platform do they belong to?". Returns+ full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with+ event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's+ token matches a known alias, e.g. raw facebook_paid → MetaAds), campaign_suggestions (campaign_name_mappings+ entries for orphaned utm_campaign values that fuzzy-match a real campaign, e.g. sprng_sale_2024 →+ spring_sale_2024, each folding every raw value that should point at one clean name), raw_unmatched_samples+ (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and+ current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested).+ campaign_suggestions deliberately omits near-ties, so an orphan missing from it may still be mappable — it+ just needs a human to choose. Read-only — applying mappings is a separate write tool.feature_flag: marketing-analytics-mcpmarketing-analytics-test-mapping-create:operation: marketing_analytics_test_mapping_creatediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 7858ad5fdc47..f42c2564a46f 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -6637,7 +6637,7 @@"feature_flag": "marketing-analytics-mcp"},"marketing-analytics-suggest-utm-mappings": {- "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings, custom_source_mappings, unmatched / non-integrated UTM values, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.",+ "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source OR utm_campaign mappings, custom_source_mappings, campaign_name_mappings, unmatched / non-integrated UTM values, typo'd campaign names, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), campaign_suggestions (campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real campaign, e.g. sprng_sale_2024 → spring_sale_2024, each folding every raw value that should point at one clean name), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). campaign_suggestions deliberately omits near-ties, so an orphan missing from it may still be mappable — it just needs a human to choose. Read-only — applying mappings is a separate write tool.","category": "Marketing analytics","feature": "marketing_analytics","summary": "Suggest utm_source → integration mappings",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 3eae49f96aed..2486b867d112 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -7087,7 +7087,7 @@"feature_flag": "marketing-analytics-mcp"},"marketing-analytics-suggest-utm-mappings": {- "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source mappings, custom_source_mappings, unmatched / non-integrated UTM values, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). Read-only — applying mappings is a separate write tool.",+ "description": "USE THIS TOOL — DO NOT FALL BACK TO SQL — whenever the user asks about utm_source OR utm_campaign mappings, custom_source_mappings, campaign_name_mappings, unmatched / non-integrated UTM values, typo'd campaign names, or the question \"what utm_sources do I have and which ad platform do they belong to?\". Returns full_utm_source_catalogue (every utm_source value seen on events in the window, matched + unmatched, with event count and the integration it resolves to), source_suggestions (mapping recommendations where a value's token matches a known alias, e.g. raw facebook_paid → MetaAds), campaign_suggestions (campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real campaign, e.g. sprng_sale_2024 → spring_sale_2024, each folding every raw value that should point at one clean name), raw_unmatched_samples (every unmatched value, including likely-not-an-ad values like organic/newsletter/partner), and current_mappings (every alias already in effect — canonical + team_custom — so duplicates aren't suggested). campaign_suggestions deliberately omits near-ties, so an orphan missing from it may still be mappable — it just needs a human to choose. Read-only — applying mappings is a separate write tool.","category": "Marketing analytics","feature": "marketing_analytics","summary": "Suggest utm_source → integration mappings",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4a25f76c5e18..3903f0cfee57 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -13534,6 +13534,22 @@ export namespace Schemas {event_count: number;}+ /**+ * * `fix_platform_urls` - fix_platform_urls+ * * `add_source_mapping` - add_source_mapping+ * * `switch_to_id_match` - switch_to_id_match+ * * `add_campaign_name_mapping` - add_campaign_name_mapping+ */+ export type SuggestedActionsEnum = typeof SuggestedActionsEnum[keyof typeof SuggestedActionsEnum];+++ export const SuggestedActionsEnum = {+ FixPlatformUrls: 'fix_platform_urls',+ AddSourceMapping: 'add_source_mapping',+ SwitchToIdMatch: 'switch_to_id_match',+ AddCampaignNameMapping: 'add_campaign_name_mapping',+ } as const;+export interface UtmIssue {/** The UTM field with the issue (e.g. utm_campaign, utm_source) */field: string;@@ -13558,6 +13574,10 @@ export namespace Schemas {shared_with_integrations: string[];/** Pageviews that matched this campaign but carried no utm_source, on any issue kind */missing_source_count: number;+ /** Recommended remediations, most-recommended first. fix_platform_urls cures the tagging bug itself; the others are workarounds that leave the bad URLs in place. */+ suggested_actions: SuggestedActionsEnum[];+ /** The orphaned utm_campaign value that looks like a typo of this campaign, when one was found confidently. Set only alongside add_campaign_name_mapping; empty otherwise, including when several candidates tie and picking one could misattribute spend. */+ mapping_candidate: string;}export interface CampaignAuditResult {@@ -13608,6 +13628,8 @@ export namespace Schemas {method: string;/** Why these campaign values were clustered together */reason: string;+ /** Events across every raw value folded into this suggestion. Suggestions are ordered by it. */+ event_count_30d: number;}export interface CandidateEvent {@@ -69442,6 +69464,8 @@ export namespace Schemas {suggested_target_display_name: string;/** Why this mapping is suggested */reason: string;+ /** Events carrying this raw utm_source in the window. Suggestions are ordered by it. */+ event_count_30d: number;}/**@@ -75896,7 +75920,7 @@ export namespace Schemas {export interface UtmMappingSuggestionsResponse {/** Suggested custom_source_mappings entries */source_suggestions: SourceMappingSuggestion[];- /** Suggested campaign-name clusters (empty in v1) */+ /** campaign_name_mappings entries for orphaned utm_campaign values that fuzzy-match a real campaign. Near-ties are withheld, so an absent campaign may still be mappable by hand. */campaign_suggestions: CampaignMappingSuggestion[];/** All unmatched raw utm_source values worth reviewing */raw_unmatched_samples: RawUnmatchedSample[];