Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(marketing-analytics): apply setup operations atomically, with an undo (#81225)

Javier Bahamondes9bccb93c6ffa
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index e39d055b08b4..7e2a4c9820b0 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -55,6 +55,19 @@ from products.marketing_analytics.backend.services.event_suggestions import sugg
from products.marketing_analytics.backend.services.mapping_suggester import suggest_utm_mappings
from products.marketing_analytics.backend.services.marketing_diagnostic import get_marketing_diagnostic
from products.marketing_analytics.backend.services.setup_plan import get_setup_plan
+from products.marketing_analytics.backend.services.setup_types import (
+ APPLICABLE_OPS,
+ NAVIGATE_OPS,
+ AddCampaignNameMapping,
+ AddCustomSourceMapping,
+ ApplyOp,
+ CreateConversionGoal,
+ DeleteConversionGoal,
+ RemoveCampaignNameMapping,
+ RemoveCustomSourceMapping,
+ SetCampaignFieldPreference,
+ UpdateConversionGoal,
+)
from products.marketing_analytics.backend.services.types import SUGGESTED_ACTION_CHOICES, UTM_ISSUE_KIND_CHOICES
from products.marketing_analytics.backend.services.utm_audit import run_utm_audit
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -247,6 +260,28 @@ _CONVERSION_GOAL_ADAPTER: TypeAdapter[ConversionGoalFilter1 | ConversionGoalFilt
)
+_SUM_MATHS = frozenset({"sum"})
+
+
+def _revenue_goal_error(goal: dict[str, Any]) -> str | None:
+ """Why this goal can't claim to carry revenue, or None if it can.
+
+ `counts_as_revenue` on its own changes nothing in the query: `get_select_field`
+ only sums when `math` is a sum type, and `_build_sum_select` returns a literal 0
+ without a `math_property`. So the flag alone produces a ROAS column that is either
+ a conversion count divided by spend, or a row of zeros — both of which look like
+ answers. Nothing validated this before, on any of the three write paths.
+ """
+ if not goal.get("counts_as_revenue"):
+ return None
+ math = str(goal.get("math") or "")
+ if math not in _SUM_MATHS:
+ return f"counts_as_revenue needs math='sum' so the amount is summed rather than counted; got {math or 'none'}."
+ if not goal.get("math_property"):
+ return "counts_as_revenue needs math_property naming the field that holds the amount."
+ return None
+
+
class ConversionGoalWrittenList(PydanticRootModel):
"""List wrapper for OpenAPI schema generation - the response carries every configured goal."""
@@ -715,13 +750,36 @@ class SetupPlanQuerySerializer(serializers.Serializer):
_SETUP_PLAN_CACHE_SECONDS = 60
+def _setup_plan_version_key(team_id: int) -> str:
+ return f"marketing_analytics:setup_plan_version:{team_id}"
+
+
def _setup_plan_cache_key(team_id: int, user_id: int, date_from: str) -> str:
# Keyed on the window because the same team asking about a different range is a
- # different question, and on the user because the plan is built from HogQL queries
- # run as them — `execute_hogql_query(..., user=user)` applies warehouse access
- # control, so two users can legitimately see different campaigns and spend. A
- # team-wide entry would serve the first caller's view to everyone.
- return f"marketing_analytics:setup_plan:{team_id}:{user_id}:{date_from}"
+ # different question, and on the user because the plan is built from HogQL run as
+ # them — `execute_hogql_query(..., user=user)` applies warehouse access control, so
+ # two users can legitimately see different campaigns and spend. The version segment
+ # is what makes invalidation possible; see `_invalidate_setup_plan_cache`.
+ version = cache.get(_setup_plan_version_key(team_id), 0)
+ return f"marketing_analytics:setup_plan:{team_id}:{version}:{user_id}:{date_from}"
+
+
+def _invalidate_setup_plan_cache(team_id: int) -> None:
+ """Orphan every cached plan for a team by bumping its version.
+
+ A bump rather than a delete because entries are keyed by window and by user as well,
+ and we know neither set. Bumping also covers everyone at once, which is what an
+ applied change calls for — the config it was built from is gone for all of them.
+ Orphaned entries cost nothing: they age out on their own TTL and nothing can reach
+ them again.
+ """
+ key = _setup_plan_version_key(team_id)
+ try:
+ cache.incr(key)
+ except ValueError:
+ # No counter yet. `None` = no expiry: a version that aged out would start
+ # serving the pre-bump entries again, though only until their own TTL runs out.
+ cache.set(key, 1, None)
class SuggestionSerializer(serializers.Serializer):
@@ -804,6 +862,193 @@ class SetupPlanResponseSerializer(serializers.Serializer):
summary = serializers.CharField(help_text="One-line summary of the plan")
+_SETUP_OPS_ADAPTER: TypeAdapter[list[ApplyOp]] = TypeAdapter(list[ApplyOp])
+
+# Applicable ops the apply endpoint doesn't implement yet. `set_source_column_mapping`
+# and `set_customer_analytics_event` both need work that belongs with their own
+# features — the former an inverse for "this table had no mapping at all", the latter
+# the project-admin check its fields carry. Rejecting them loudly beats silently
+# accepting an op that does nothing.
+_UNIMPLEMENTED_OPS = frozenset({"set_source_column_mapping", "set_customer_analytics_event"})
+
+
+def _apply_setup_op(config: TeamMarketingAnalyticsConfig, op: ApplyOp) -> dict[str, Any] | None:
+ """Apply one op in place and return the op that reverses it, or None if it was a
+ no-op (re-applying an existing mapping, for instance — idempotent for MCP retries).
+
+ Mutations go through the model's property setters so the existing validators run.
+ """
+ if isinstance(op, AddCustomSourceMapping):
+ mappings = {key: list(values) for key, values in (config.custom_source_mappings or {}).items()}
+ existing = mappings.setdefault(op.integration, [])
+ if op.raw_utm_source in existing:
+ return None
+ existing.append(op.raw_utm_source)
+ config.custom_source_mappings = mappings
+ return RemoveCustomSourceMapping(integration=op.integration, raw_utm_source=op.raw_utm_source).model_dump(
+ mode="json"
+ )
+
+ if isinstance(op, RemoveCustomSourceMapping):
+ mappings = {key: list(values) for key, values in (config.custom_source_mappings or {}).items()}
+ existing = mappings.get(op.integration, [])
+ if op.raw_utm_source not in existing:
+ return None
+ existing.remove(op.raw_utm_source)
+ if not existing:
+ mappings.pop(op.integration, None)
+ else:
+ mappings[op.integration] = existing
+ config.custom_source_mappings = mappings
+ return AddCustomSourceMapping(integration=op.integration, raw_utm_source=op.raw_utm_source).model_dump(
+ mode="json"
+ )
+
+ if isinstance(op, SetCampaignFieldPreference):
+ preferences = {key: dict(value) for key, value in (config.campaign_field_preferences or {}).items()}
+ # Absent means "campaign_name" (the documented default), so restoring the
+ # default explicitly is equivalent to restoring absence.
+ previous = preferences.get(op.integration, {}).get("match_field", "campaign_name")
+ if previous == op.match_field:
+ return None
+ preferences[op.integration] = {"match_field": op.match_field}
+ config.campaign_field_preferences = preferences
+ return SetCampaignFieldPreference(integration=op.integration, match_field=previous).model_dump(mode="json")
+
+ if isinstance(op, AddCampaignNameMapping):
+ # Named apart from `mappings` above: this one is two levels deep
+ # (integration -> clean name -> raw values), and sharing the name would hide that.
+ campaign_mappings = _clone_campaign_mappings(config)
+ per_integration = campaign_mappings.setdefault(op.integration, {})
+ existing = per_integration.setdefault(op.clean_name, [])
+ added = [value for value in op.raw_values if value not in existing]
+ if not added:
+ return None
+ existing.extend(added)
+ config.campaign_name_mappings = campaign_mappings
+ # Undo removes only what this op added, so a value that was already mapped
+ # survives the undo.
+ return RemoveCampaignNameMapping(
+ integration=op.integration, clean_name=op.clean_name, raw_values=added
+ ).model_dump(mode="json")
+
+ if isinstance(op, RemoveCampaignNameMapping):
+ campaign_mappings = _clone_campaign_mappings(config)
+ per_integration = campaign_mappings.get(op.integration, {})
+ existing = per_integration.get(op.clean_name, [])
+ removed = [value for value in op.raw_values if value in existing]
+ if not removed:
+ return None
+ per_integration[op.clean_name] = [value for value in existing if value not in removed]
+ if not per_integration[op.clean_name]:
+ per_integration.pop(op.clean_name, None)
+ if not per_integration:
+ campaign_mappings.pop(op.integration, None)
+ config.campaign_name_mappings = campaign_mappings
+ return AddCampaignNameMapping(
+ integration=op.integration, clean_name=op.clean_name, raw_values=removed
+ ).model_dump(mode="json")
+
+ if isinstance(op, CreateConversionGoal):
+ goals = list(config.conversion_goals)
+ goal = dict(op.goal)
+ if op.restore and goal.get("conversion_goal_id"):
+ if any(existing.get("conversion_goal_id") == goal["conversion_goal_id"] for existing in goals):
+ raise serializers.ValidationError({"ops": "That conversion goal already exists."})
+ else:
+ goal["conversion_goal_id"] = str(uuid.uuid4())
+ try:
+ validated = _CONVERSION_GOAL_ADAPTER.validate_python(goal)
+ except PydanticValidationError as e:
+ raise serializers.ValidationError({"ops": _readable_pydantic_errors(e)})
+ revenue_error = _revenue_goal_error(goal)
+ if revenue_error:
+ raise serializers.ValidationError({"ops": revenue_error})
+ stored = validated.model_dump(exclude_none=True, mode="json")
+ goals.append(stored)
+ config._conversion_goals = goals
+ return DeleteConversionGoal(conversion_goal_id=stored["conversion_goal_id"]).model_dump(mode="json")
+
+ if isinstance(op, UpdateConversionGoal):
+ goals = list(config.conversion_goals)
+ index = _index_of_goal(goals, op.conversion_goal_id)
+ before = dict(goals[index])
+ merged = {**before, **op.patch}
+ try:
+ validated = _CONVERSION_GOAL_ADAPTER.validate_python(merged)
+ except PydanticValidationError as e:
+ raise serializers.ValidationError({"ops": _readable_pydantic_errors(e)})
+ # The merged goal, not the patch: flipping `counts_as_revenue` on a goal that
+ # counts rows is exactly the state to reject, and the patch alone can't see it.
+ revenue_error = _revenue_goal_error(merged)
+ if revenue_error:
+ raise serializers.ValidationError({"ops": revenue_error})
+ goals[index] = validated.model_dump(exclude_none=True, mode="json")
+ config._conversion_goals = goals
+ # Undo restores only the keys this patch touched, so a concurrent change to
+ # another field isn't reverted along with it.
+ return UpdateConversionGoal(
+ conversion_goal_id=op.conversion_goal_id,
+ patch={key: before.get(key) for key in op.patch},
+ ).model_dump(mode="json")
+
+ if isinstance(op, DeleteConversionGoal):
+ goals = list(config.conversion_goals)
+ removed = goals.pop(_index_of_goal(goals, op.conversion_goal_id))
+ config._conversion_goals = goals
+ # `restore=True` keeps the original id so the undo puts back the same goal
+ # rather than a copy. Position is not restored — goals are keyed by id and
+ # name, not order.
+ return CreateConversionGoal(goal=removed, restore=True).model_dump(mode="json")
+
+ raise serializers.ValidationError({"ops": f"'{op.op}' is not a supported operation."})
+
+
+def _clone_campaign_mappings(config: TeamMarketingAnalyticsConfig) -> dict[str, dict[str, list[str]]]:
+ return {
+ integration: {clean: list(raws) for clean, raws in per_integration.items()}
+ for integration, per_integration in (config.campaign_name_mappings or {}).items()
+ }
+
+
+def _index_of_goal(goals: list[dict], conversion_goal_id: str) -> int:
+ for index, goal in enumerate(goals):
+ if goal.get("conversion_goal_id") == conversion_goal_id:
+ return index
+ raise NotFound(f"No conversion goal with id '{conversion_goal_id}'.")
+
+
+class ApplySetupOpsSerializer(serializers.Serializer):
+ ops = serializers.ListField(
+ child=serializers.JSONField(),
+ allow_empty=False,
+ help_text=(
+ "Operations to apply, in order. Send `apply` payloads returned verbatim by setup_plan — "
+ "never hand-craft one. Navigate-only ops (open_oauth, open_source_wizard, open_settings, "
+ "fix_platform_urls) are rejected: they describe something a browser or a human does."
+ ),
+ )
+ # Shadows `Field.source`, DRF's attribute-mapping name — same as on SuggestionSerializer.
+ source = serializers.ChoiceField( # type: ignore[assignment]
+ choices=["setup_tab", "apply_all_safe", "mcp"],
+ required=False,
+ default="setup_tab",
+ help_text="Where the request came from, recorded in the activity log",
+ )
+
+
+class ApplySetupOpsResponseSerializer(serializers.Serializer):
+ applied = serializers.ListField(child=serializers.JSONField(), help_text="The operations that were applied")
+ undo_ops = serializers.ListField(
+ child=serializers.JSONField(),
+ help_text=(
+ "Operations that reverse this batch, in the order they should be sent. Computed server-side "
+ "from the pre-change state — POST them back to undo."
+ ),
+ )
+ marketing_analytics_config = serializers.JSONField(help_text="The config as it now stands")
+
+
class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
# `marketing_analytics` is gated by the API scope of the same name and inherits
# RBAC from `web_analytics` (see RESOURCE_INHERITANCE_MAP). Custom @action methods
@@ -1243,6 +1488,102 @@ class MarketingAnalyticsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+ @validated_request(
+ request_serializer=ApplySetupOpsSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=ApplySetupOpsResponseSerializer,
+ description="The applied operations and the ops that reverse them",
+ ),
+ 400: OpenApiResponse(description="An operation was malformed, unsupported, or not applicable"),
+ 404: OpenApiResponse(description="The marketing-analytics-setup feature flag is off for this team"),
+ },
+ summary="Apply setup operations",
+ description=(
+ "Apply one or more setup operations from the setup plan, atomically. Either every operation "
+ "lands or none does — a partially-applied batch has no well-defined undo. Returns `undo_ops`, "
+ "computed from the pre-change state, which can be POSTed back to reverse the batch. Only send "
+ "`apply` payloads returned by setup_plan."
+ ),
+ )
+ @action(methods=["POST"], detail=False, url_path="apply_setup_ops", required_scopes=["marketing_analytics:write"])
+ def apply_setup_ops(self, request: Request, *args, **kwargs) -> Response:
+ # Same gate as setup_plan: the ops only come from a plan, so an unreleased
+ # read side means there is nothing legitimate to apply.
+ if not _setup_enabled(self.team):
+ raise NotFound("Marketing analytics setup is not enabled for this project.")
+
+ # Every op here writes a field the team PATCH puts in TEAM_CONFIG_ADMIN_FIELDS_SET,
+ # and the goal ops write the same rows the sibling endpoints admin-gate. Without
+ # this, `marketing_analytics:write` — which resolves to `editor`, what every
+ # project member has — would be a way around both.
+ self._require_project_admin()
+
+ raw_ops = request.validated_data["ops"]
+ try:
+ ops = _SETUP_OPS_ADAPTER.validate_python(raw_ops)
+ except PydanticValidationError as e:
+ raise serializers.ValidationError({"ops": _readable_pydantic_errors(e)})
+
+ for op in ops:
+ if op.op in NAVIGATE_OPS:
+ raise serializers.ValidationError(
+ {"ops": f"'{op.op}' is not applicable — it describes something the browser or a human does."}
+ )
+ if op.op in _UNIMPLEMENTED_OPS:
+ raise serializers.ValidationError({"ops": f"'{op.op}' is not supported by this endpoint yet."})
+ if op.op not in APPLICABLE_OPS:
+ raise serializers.ValidationError({"ops": f"'{op.op}' is not a supported operation."})
+
+ # One lock for the whole batch. The alternative — the frontend PATCHing the
+ # whole config blob per suggestion — loses updates as soon as two apply
+ # in sequence from one stale client snapshot, or a teammate edits in another tab.
+ with transaction.atomic():
+ config = self._locked_config()
+ undo_ops: list[dict[str, Any]] = []
+ for op in ops:
+ # None means the op was already satisfied — re-adding an existing
+ # mapping is a success, not a failure, so MCP retries are safe.
+ inverse = _apply_setup_op(config, op)
+ if inverse is not None:
+ undo_ops.append(inverse)
+ config.save()
+
+ # Reversed: undoing a batch means unwinding it from the last change back.
+ undo_ops.reverse()
+
+ # The config the plan was built from no longer exists, so any cached plan is
+ # stale by definition. Without this, applying a change and reloading serves the
+ # pre-change plan for up to a minute — the suggestion you just fixed still
+ # sitting there, which reads as the apply having silently failed.
+ _invalidate_setup_plan_cache(self.team.pk)
+
+ # `_update_marketing_analytics_config` in posthog/api/team.py only diffs
+ # sources_map / attribution_window_days / attribution_mode into the team
+ # activity log, so mapping and goal changes made here would otherwise leave no
+ # trace at all. This is the interim record; wiring `log_activity` properly is a
+ # follow-up.
+ logger.info(
+ "marketing_setup_ops_applied",
+ team_id=self.team.pk,
+ user_id=request.user.pk,
+ source=request.validated_data["source"],
+ ops=[op.op for op in ops],
+ )
+ return Response(
+ {
+ "applied": [op.model_dump(mode="json") for op in ops],
+ "undo_ops": undo_ops,
+ "marketing_analytics_config": {
+ "sources_map": config.sources_map,
+ "conversion_goals": config.conversion_goals,
+ "custom_source_mappings": config.custom_source_mappings,
+ "campaign_name_mappings": config.campaign_name_mappings,
+ "campaign_field_preferences": config.campaign_field_preferences,
+ },
+ }
+ )
+
@action(methods=["POST"], detail=False, url_path="test_mapping")
def test_mapping(self, request: Request, *args, **kwargs) -> Response:
serializer = TestMappingSerializer(data=request.data)
diff --git a/products/marketing_analytics/backend/services/setup_types.py b/products/marketing_analytics/backend/services/setup_types.py
index 8b87e55d126c..302f639a5f91 100644
--- a/products/marketing_analytics/backend/services/setup_types.py
+++ b/products/marketing_analytics/backend/services/setup_types.py
@@ -127,6 +127,15 @@ class AddCustomSourceMapping(_Op):
raw_utm_source: str
+class RemoveCustomSourceMapping(_Op):
+ """Inverse of `add_custom_source_mapping`. Exists so the apply endpoint can return a
+ real undo op rather than asking the client to reconstruct prior state."""
+
+ op: Literal["remove_custom_source_mapping"] = "remove_custom_source_mapping"
+ integration: str
+ raw_utm_source: str
+
+
class SetCampaignFieldPreference(_Op):
op: Literal["set_campaign_field_preference"] = "set_campaign_field_preference"
integration: str
@@ -140,10 +149,23 @@ class AddCampaignNameMapping(_Op):
raw_values: list[str] = Field(min_length=1)
+class RemoveCampaignNameMapping(_Op):
+ """Inverse of `add_campaign_name_mapping`."""
+
+ op: Literal["remove_campaign_name_mapping"] = "remove_campaign_name_mapping"
+ integration: str
+ clean_name: str
+ raw_values: list[str] = Field(min_length=1)
+
+
class CreateConversionGoal(_Op):
op: Literal["create_conversion_goal"] = "create_conversion_goal"
# Validated against `ConversionGoalFilter` by the apply endpoint, which owns that adapter.
goal: dict[str, Any]
+ # Set only on an undo op, to put back the goal a delete removed under its original
+ # id. A fresh create always gets a server-assigned id; honouring a client-supplied
+ # one would let callers pick ids and collide.
+ restore: bool = False
class UpdateConversionGoal(_Op):
@@ -209,8 +231,10 @@ class FixPlatformUrls(_Op):
ApplyOp = Annotated[
AddCustomSourceMapping
+ | RemoveCustomSourceMapping
| SetCampaignFieldPreference
| AddCampaignNameMapping
+ | RemoveCampaignNameMapping
| CreateConversionGoal
| UpdateConversionGoal
| DeleteConversionGoal
@@ -226,8 +250,10 @@ ApplyOp = Annotated[
APPLICABLE_OPS: frozenset[str] = frozenset(
{
"add_custom_source_mapping",
+ "remove_custom_source_mapping",
"set_campaign_field_preference",
"add_campaign_name_mapping",
+ "remove_campaign_name_mapping",
"create_conversion_goal",
"update_conversion_goal",
"delete_conversion_goal",
diff --git a/products/marketing_analytics/backend/test_api_apply_setup_ops.py b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
new file mode 100644
index 000000000000..21ac8f78e999
--- /dev/null
+++ b/products/marketing_analytics/backend/test_api_apply_setup_ops.py
@@ -0,0 +1,490 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from posthog.constants import AvailableFeature
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
+
+from ee.models.rbac.access_control import AccessControl
+
+_FLAG_TARGET = "products.marketing_analytics.backend.api.feature_enabled_or_false"
+
+SCHEMA_MAP = {"utm_campaign_name": "utm_campaign", "utm_source_name": "utm_source"}
+
+
+def goal_payload(name: str, event: str = "sign_up", **extra) -> dict:
+ return {"kind": "EventsNode", "event": event, "conversion_goal_name": name, "schema_map": SCHEMA_MAP, **extra}
+
+
+class TestApplySetupOps(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops"
+ cache.clear()
+ # Applying writes the same admin-gated config fields the team PATCH protects.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ flag = patch(_FLAG_TARGET, return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+
+ def apply(self, *ops, source="setup_tab"):
+ return self.client.post(self.url, {"ops": list(ops), "source": source}, format="json")
+
+ def config(self) -> TeamMarketingAnalyticsConfig:
+ return TeamMarketingAnalyticsConfig.objects.get(team=self.team)
+
+ # --- mapping ops -------------------------------------------------------
+
+ def test_adds_a_custom_source_mapping_and_returns_its_inverse(self):
+ response = self.apply({"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"})
+
+ assert response.status_code == 200, response.json()
+ assert self.config().custom_source_mappings == {"MetaAds": ["fb-ads"]}
+ assert response.json()["undo_ops"] == [
+ {"op": "remove_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}
+ ]
+
+ def test_undo_ops_round_trip_back_to_the_original_state(self):
+ add = {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}
+ undo = self.apply(add).json()["undo_ops"]
+
+ self.client.post(self.url, {"ops": undo}, format="json")
+
+ assert self.config().custom_source_mappings == {}
+
+ def test_reapplying_an_existing_mapping_is_a_no_op_success(self):
+ add = {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}
+ self.apply(add)
+
+ response = self.apply(add)
+
+ # Idempotent so an MCP retry can't fail or produce a duplicate...
+ assert response.status_code == 200
+ assert self.config().custom_source_mappings == {"MetaAds": ["fb-ads"]}
+ # ...and contributes no undo, so undoing doesn't remove the original.
+ assert response.json()["undo_ops"] == []
+
+ def test_switches_the_campaign_match_field_and_restores_the_previous_one(self):
+ response = self.apply(
+ {"op": "set_campaign_field_preference", "integration": "GoogleAds", "match_field": "campaign_id"}
+ )
+
+ assert self.config().campaign_field_preferences == {"GoogleAds": {"match_field": "campaign_id"}}
+ # Absent means campaign_name, so the inverse restores that explicitly.
+ assert response.json()["undo_ops"] == [
+ {"op": "set_campaign_field_preference", "integration": "GoogleAds", "match_field": "campaign_name"}
+ ]
+
+ def test_setting_the_field_preference_it_already_has_is_a_no_op(self):
+ response = self.apply(
+ {"op": "set_campaign_field_preference", "integration": "GoogleAds", "match_field": "campaign_name"}
+ )
+
+ assert response.json()["undo_ops"] == []
+
+ def test_campaign_name_mapping_undo_only_removes_what_it_added(self):
+ self.apply(
+ {
+ "op": "add_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "spring_sale",
+ "raw_values": ["sprng_sale"],
+ }
+ )
+
+ response = self.apply(
+ {
+ "op": "add_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "spring_sale",
+ "raw_values": ["sprng_sale", "spring_sle"],
+ }
+ )
+
+ assert self.config().campaign_name_mappings == {"GoogleAds": {"spring_sale": ["sprng_sale", "spring_sle"]}}
+ # Only the newly added value, so undoing doesn't strip the pre-existing one.
+ assert response.json()["undo_ops"] == [
+ {
+ "op": "remove_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "spring_sale",
+ "raw_values": ["spring_sle"],
+ }
+ ]
+
+ def test_removing_the_last_raw_value_prunes_the_empty_keys(self):
+ add = {
+ "op": "add_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "spring_sale",
+ "raw_values": ["sprng_sale"],
+ }
+ undo = self.apply(add).json()["undo_ops"]
+
+ self.client.post(self.url, {"ops": undo}, format="json")
+
+ # No `{"GoogleAds": {"spring_sale": []}}` litter left behind.
+ assert self.config().campaign_name_mappings == {}
+
+ # --- conversion goal ops ----------------------------------------------
+
+ def test_creates_a_goal_with_a_server_assigned_id(self):
+ response = self.apply({"op": "create_conversion_goal", "goal": goal_payload("Sign ups")})
+
+ goals = self.config().conversion_goals
+ assert [g["conversion_goal_name"] for g in goals] == ["Sign ups"]
+ assert goals[0]["conversion_goal_id"]
+ assert response.json()["undo_ops"] == [
+ {"op": "delete_conversion_goal", "conversion_goal_id": goals[0]["conversion_goal_id"]}
+ ]
+
+ def test_a_non_restore_create_ignores_a_client_supplied_id(self):
+ # Otherwise a caller could pick ids and collide with an existing goal.
+ response = self.apply(
+ {"op": "create_conversion_goal", "goal": goal_payload("Sign ups", conversion_goal_id="pick-me")}
+ )
+
+ assert response.status_code == 200
+ assert self.config().conversion_goals[0]["conversion_goal_id"] != "pick-me"
+
+ def test_deleting_and_undoing_restores_the_same_goal_id(self):
+ self.apply({"op": "create_conversion_goal", "goal": goal_payload("Sign ups")})
+ goal_id = self.config().conversion_goals[0]["conversion_goal_id"]
+
+ undo = self.apply({"op": "delete_conversion_goal", "conversion_goal_id": goal_id}).json()["undo_ops"]
+ assert self.config().conversion_goals == []
+
+ self.client.post(self.url, {"ops": undo}, format="json")
+
+ restored = self.config().conversion_goals
+ # Same id, not a copy — anything referencing the goal keeps working.
+ assert [g["conversion_goal_id"] for g in restored] == [goal_id]
+
+ def test_update_undo_restores_only_the_patched_keys(self):
+ # Already summing a property, so the `counts_as_revenue` patch below is a legal
+ # one. The field is incidental here — the assertion is about the undo's shape.
+ self.apply(
+ {"op": "create_conversion_goal", "goal": goal_payload("Sign ups", math="sum", math_property="revenue")}
+ )
+ goal_id = self.config().conversion_goals[0]["conversion_goal_id"]
+
+ response = self.apply(
+ {"op": "update_conversion_goal", "conversion_goal_id": goal_id, "patch": {"counts_as_revenue": True}}
+ )
+
+ assert self.config().conversion_goals[0]["counts_as_revenue"] is True
+ undo = response.json()["undo_ops"][0]
+ assert undo["op"] == "update_conversion_goal"
+ assert set(undo["patch"]) == {"counts_as_revenue"}
+
+ def test_updating_a_missing_goal_is_a_404(self):
+ response = self.apply(
+ {"op": "update_conversion_goal", "conversion_goal_id": "nope", "patch": {"counts_as_revenue": True}}
+ )
+
+ assert response.status_code == 404
+
+ # --- batch semantics ---------------------------------------------------
+
+ def test_applies_a_batch_and_returns_undo_in_reverse_order(self):
+ response = self.apply(
+ {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"},
+ {"op": "set_campaign_field_preference", "integration": "GoogleAds", "match_field": "campaign_id"},
+ source="apply_all_safe",
+ )
+
+ assert response.status_code == 200
+ undo = response.json()["undo_ops"]
+ # Unwind last change first.
+ assert [op["op"] for op in undo] == ["set_campaign_field_preference", "remove_custom_source_mapping"]
+
+ def test_one_bad_op_rolls_back_the_whole_batch(self):
+ # A partially-applied batch has no well-defined undo, so nothing may commit.
+ response = self.apply(
+ {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"},
+ {"op": "update_conversion_goal", "conversion_goal_id": "nope", "patch": {"counts_as_revenue": True}},
+ )
+
+ assert response.status_code == 404
+ assert self.config().custom_source_mappings == {}
+
+ def test_returns_the_resulting_config(self):
+ response = self.apply({"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb"})
+
+ config = response.json()["marketing_analytics_config"]
+ assert config["custom_source_mappings"] == {"MetaAds": ["fb"]}
+ assert "conversion_goals" in config
+
+ # --- rejections --------------------------------------------------------
+
+ def test_rejects_navigate_only_ops(self):
+ response = self.apply({"op": "open_oauth", "kind": "google-ads"})
+
+ assert response.status_code == 400
+ assert "not applicable" in str(response.json())
+
+ def test_rejects_fix_platform_urls_which_is_advice(self):
+ response = self.apply(
+ {
+ "op": "fix_platform_urls",
+ "integration": "GoogleAds",
+ "campaign_name": "spring",
+ "expected_utm_campaign": "spring",
+ "expected_utm_source": "google",
+ }
+ )
+
+ assert response.status_code == 400
+
+ def test_rejects_an_unknown_op(self):
+ response = self.apply({"op": "drop_everything"})
+
+ assert response.status_code == 400
+
+ def test_rejects_an_op_with_unexpected_keys(self):
+ # extra="forbid" — a malformed or hallucinated op must fail at the boundary
+ # rather than being applied with defaults filled in.
+ response = self.apply(
+ {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb", "sneaky": 1}
+ )
+
+ assert response.status_code == 400
+
+ def test_rejects_ops_not_implemented_yet(self):
+ response = self.apply(
+ {"op": "set_customer_analytics_event", "field": "activity_event", "event_node": {"kind": "EventsNode"}}
+ )
+
+ assert response.status_code == 400
+ assert "not supported by this endpoint yet" in str(response.json())
+
+ def test_rejects_an_empty_batch(self):
+ response = self.client.post(self.url, {"ops": []}, format="json")
+
+ assert response.status_code == 400
+
+ def test_requires_authentication(self):
+ self.client.logout()
+
+ response = self.apply({"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb"})
+
+ assert response.status_code in (401, 403)
+
+ # --- removal ops as the setup plan emits them --------------------------
+
+ def test_removes_a_broken_campaign_mapping_and_can_put_it_back(self):
+ # End-to-end for the plan's only subtractive suggestion: the exact op shape
+ # `_bad_mapping_suggestion` produces has to survive the round trip.
+ self.apply(
+ {
+ "op": "add_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "deleted_campaign",
+ "raw_values": ["old_utm"],
+ }
+ )
+
+ response = self.apply(
+ {
+ "op": "remove_campaign_name_mapping",
+ "integration": "GoogleAds",
+ "clean_name": "deleted_campaign",
+ "raw_values": ["old_utm"],
+ }
+ )
+
+ assert response.status_code == 200, response.json()
+ assert self.config().campaign_name_mappings == {}
+
+ self.client.post(self.url, {"ops": response.json()["undo_ops"]}, format="json")
+ assert self.config().campaign_name_mappings == {"GoogleAds": {"deleted_campaign": ["old_utm"]}}
+
+ def test_removes_a_wrong_platform_source_mapping(self):
+ self.apply({"op": "add_custom_source_mapping", "integration": "GoogleAds", "raw_utm_source": "facebook"})
+
+ response = self.apply(
+ {"op": "remove_custom_source_mapping", "integration": "GoogleAds", "raw_utm_source": "facebook"}
+ )
+
+ assert response.status_code == 200
+ assert self.config().custom_source_mappings == {}
+
+ def test_creates_the_count_only_goal_the_plan_proposes(self):
+ # The plan sends an empty conversion_goal_id; the server assigns the real one.
+ response = self.apply(
+ {
+ "op": "create_conversion_goal",
+ "goal": {
+ "kind": "EventsNode",
+ "event": "purchase_completed",
+ "name": "purchase_completed",
+ "conversion_goal_id": "",
+ "conversion_goal_name": "purchase_completed",
+ "math": "total",
+ "schema_map": {
+ "utm_campaign_name": "utm_campaign",
+ "utm_source_name": "utm_source",
+ "timestamp_field": "timestamp",
+ "distinct_id_field": "distinct_id",
+ },
+ },
+ }
+ )
+
+ assert response.status_code == 200, response.json()
+ goals = self.config().conversion_goals
+ assert [g["conversion_goal_name"] for g in goals] == ["purchase_completed"]
+ assert goals[0]["conversion_goal_id"]
+
+
+class TestRevenueGoalConsistencyViaOps(APIBaseTest):
+ """The same rule as the conversion-goal endpoints, on the op path. This one matters
+ most: it's the path an LLM writes through, and `counts_as_revenue` is the single flag
+ where a wrong value produces a plausible revenue number rather than an error."""
+
+ def setUp(self):
+ super().setUp()
+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops"
+ cache.clear()
+ # Applying writes the same admin-gated config fields the team PATCH protects.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ flag = patch(_FLAG_TARGET, return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+
+ def apply(self, *ops):
+ return self.client.post(self.url, {"ops": list(ops), "source": "setup_tab"}, format="json")
+
+ def config(self) -> TeamMarketingAnalyticsConfig:
+ return TeamMarketingAnalyticsConfig.objects.get(team=self.team)
+
+ def test_rejects_creating_a_revenue_goal_that_counts_rows(self):
+ response = self.apply(
+ {"op": "create_conversion_goal", "goal": goal_payload("Revenue", counts_as_revenue=True, math="total")}
+ )
+
+ assert response.status_code == 400, response.json()
+ assert self.config().conversion_goals == []
+
+ def test_accepts_a_revenue_goal_with_an_amount(self):
+ response = self.apply(
+ {
+ "op": "create_conversion_goal",
+ "goal": goal_payload("Revenue", counts_as_revenue=True, math="sum", math_property="revenue"),
+ }
+ )
+
+ assert response.status_code == 200, response.json()
+ assert len(self.config().conversion_goals) == 1
+
+ def test_rejects_patching_the_flag_onto_a_counting_goal(self):
+ created = self.apply({"op": "create_conversion_goal", "goal": goal_payload("Signups", math="total")})
+ goal_id = self.config().conversion_goals[0]["conversion_goal_id"]
+ assert created.status_code == 200
+
+ response = self.apply(
+ {"op": "update_conversion_goal", "conversion_goal_id": goal_id, "patch": {"counts_as_revenue": True}}
+ )
+
+ # Validated against the merged goal, not the patch: the patch alone is one
+ # harmless-looking boolean.
+ assert response.status_code == 400, response.json()
+ assert self.config().conversion_goals[0].get("counts_as_revenue") is not True
+
+ def test_a_rejected_goal_does_not_land_half_a_batch(self):
+ # Batch atomicity has to hold for this rejection too, or a plausible-looking
+ # ROAS goal gets in alongside whatever else was in the request.
+ response = self.apply(
+ {"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"},
+ {"op": "create_conversion_goal", "goal": goal_payload("Revenue", counts_as_revenue=True, math="total")},
+ )
+
+ assert response.status_code == 400, response.json()
+ assert self.config().custom_source_mappings == {}
+
+
+class TestApplySetupOpsFeatureFlag(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops"
+ cache.clear()
+
+ def test_the_endpoint_is_absent_when_the_flag_is_off(self):
+ # The ops only ever come from a plan, so an unreleased read side means there is
+ # nothing legitimate to apply — and a write that lands anyway would be a config
+ # change from a surface the user cannot see.
+ with patch(_FLAG_TARGET, return_value=False):
+ response = self.client.post(
+ self.url,
+ {"ops": [{"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}]},
+ format="json",
+ )
+
+ assert response.status_code == 404
+ assert TeamMarketingAnalyticsConfig.objects.get(team=self.team).custom_source_mappings == {}
+
+
+class TestApplySetupOpsRequiresProjectAdmin(APIBaseTest):
+ """`marketing_analytics:write` resolves to `editor` (web_analytics' default level via
+ RESOURCE_INHERITANCE_MAP), which every project member has. Without an explicit admin
+ check this endpoint is a way around both the team PATCH gate on
+ marketing_analytics_config and the admin check the sibling goal endpoints carry."""
+
+ def setUp(self):
+ super().setUp()
+ self.url = f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops"
+ cache.clear()
+ flag = patch(_FLAG_TARGET, return_value=True)
+ flag.start()
+ self.addCleanup(flag.stop)
+
+ def _demote_to_member(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="project", resource_id=self.team.id, access_level="member"
+ )
+
+ def test_a_member_cannot_delete_a_conversion_goal(self):
+ # The identical write is admin-only on conversion_goals/<id>/delete.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ created = self.client.post(
+ self.url,
+ {"ops": [{"op": "create_conversion_goal", "goal": goal_payload("Sign ups")}]},
+ format="json",
+ )
+ assert created.status_code == 200, created.json()
+ goal_id = TeamMarketingAnalyticsConfig.objects.get(team=self.team).conversion_goals[0]["conversion_goal_id"]
+
+ self._demote_to_member()
+ response = self.client.post(
+ self.url,
+ {"ops": [{"op": "delete_conversion_goal", "conversion_goal_id": goal_id}]},
+ format="json",
+ )
+
+ assert response.status_code == 403, response.json()
+ assert len(TeamMarketingAnalyticsConfig.objects.get(team=self.team).conversion_goals) == 1
+
+ def test_a_member_cannot_write_a_source_mapping(self):
+ # Not covered by a sibling endpoint, but marketing_analytics_config as a whole
+ # sits in TEAM_CONFIG_ADMIN_FIELDS_SET, so the PATCH path refuses this too.
+ self._demote_to_member()
+
+ response = self.client.post(
+ self.url,
+ {"ops": [{"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}]},
+ format="json",
+ )
+
+ assert response.status_code == 403, response.json()
+ assert TeamMarketingAnalyticsConfig.objects.get(team=self.team).custom_source_mappings == {}
diff --git a/products/marketing_analytics/backend/test_api_setup_plan.py b/products/marketing_analytics/backend/test_api_setup_plan.py
index 3fb8e6096253..2603adc29bca 100644
--- a/products/marketing_analytics/backend/test_api_setup_plan.py
+++ b/products/marketing_analytics/backend/test_api_setup_plan.py
@@ -3,7 +3,7 @@ from unittest.mock import patch
from django.core.cache import cache
-from posthog.models.organization import Organization
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -192,6 +192,9 @@ class TestSetupPlanCaching(APIBaseTest):
# locmem persists across tests in a process; a leaked entry would make these
# pass or fail depending on ordering.
cache.clear()
+ # Two of these invalidate through apply_setup_ops, which requires project admin.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
flag = patch(_FLAG_TARGET, return_value=True)
flag.start()
self.addCleanup(flag.stop)
@@ -226,6 +229,25 @@ class TestSetupPlanCaching(APIBaseTest):
assert build.call_count == 2
+ def test_applying_ops_invalidates_the_cache(self):
+ # Otherwise applying a change and reloading serves the pre-change plan, with the
+ # suggestion you just fixed still sitting there — which reads as a failed apply.
+ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:
+ self.client.get(self.url)
+
+ self.client.post(
+ f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops",
+ {
+ "ops": [{"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}],
+ "source": "setup_tab",
+ },
+ format="json",
+ )
+
+ self.client.get(self.url)
+
+ assert build.call_count == 2
+
def test_one_users_plan_is_not_served_to_another(self):
"""The plan is built from HogQL run as the caller, and `execute_hogql_query`
applies warehouse access control from that user — so a shared entry would serve
@@ -240,6 +262,30 @@ class TestSetupPlanCaching(APIBaseTest):
assert build.call_count == 2
+ def test_one_teams_invalidation_does_not_evict_another(self):
+ other = Team.objects.create(organization=self.organization, name="second")
+ other_url = f"/api/projects/{other.pk}/marketing_analytics/setup_plan"
+
+ with patch(_PLAN_TARGET, return_value=_clean_plan()) as build:
+ self.client.get(self.url)
+ self.client.get(other_url)
+ assert build.call_count == 2
+
+ self.client.post(
+ f"/api/projects/{self.team.pk}/marketing_analytics/apply_setup_ops",
+ {
+ "ops": [{"op": "add_custom_source_mapping", "integration": "MetaAds", "raw_utm_source": "fb-ads"}],
+ "source": "setup_tab",
+ },
+ format="json",
+ )
+
+ self.client.get(self.url)
+ self.client.get(other_url)
+
+ # Only this team rebuilt; the other team's entry was untouched.
+ assert build.call_count == 3
+
def test_one_teams_plan_is_not_served_to_another(self):
other = Team.objects.create(organization=self.organization, name="second")
diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index 1990f935420e..42d018e633a0 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,39 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * * `setup_tab` - setup_tab
+ * * `apply_all_safe` - apply_all_safe
+ * * `mcp` - mcp
+ */
+export type ApplySetupOpsSourceEnumApi = (typeof ApplySetupOpsSourceEnumApi)[keyof typeof ApplySetupOpsSourceEnumApi]
+
+export const ApplySetupOpsSourceEnumApi = {
+ SetupTab: 'setup_tab',
+ ApplyAllSafe: 'apply_all_safe',
+ Mcp: 'mcp',
+} as const
+
+export interface ApplySetupOpsApi {
+ /** Operations to apply, in order. Send `apply` payloads returned verbatim by setup_plan — never hand-craft one. Navigate-only ops (open_oauth, open_source_wizard, open_settings, fix_platform_urls) are rejected: they describe something a browser or a human does. */
+ ops: unknown[]
+ /** Where the request came from, recorded in the activity log
+ *
+ * * `setup_tab` - setup_tab
+ * * `apply_all_safe` - apply_all_safe
+ * * `mcp` - mcp */
+ source?: ApplySetupOpsSourceEnumApi
+}
+
+export interface ApplySetupOpsResponseApi {
+ /** The operations that were applied */
+ applied: unknown[]
+ /** Operations that reverse this batch, in the order they should be sent. Computed server-side from the pre-change state — POST them back to undo. */
+ undo_ops: unknown[]
+ /** The config as it now stands */
+ marketing_analytics_config: unknown
+}
+
/**
* * `EventsNode` - EventsNode
* * `ActionsNode` - ActionsNode
diff --git a/products/marketing_analytics/frontend/generated/api.ts b/products/marketing_analytics/frontend/generated/api.ts
index 7af25f8c35e5..6a805122cf6f 100644
--- a/products/marketing_analytics/frontend/generated/api.ts
+++ b/products/marketing_analytics/frontend/generated/api.ts
@@ -9,6 +9,8 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ ApplySetupOpsApi,
+ ApplySetupOpsResponseApi,
ConversionGoalWriteApi,
ConversionGoalWriteResponseApi,
ConversionGoalsListResponseApi,
@@ -29,6 +31,27 @@ import type {
UtmMappingSuggestionsResponseApi,
} from './api.schemas'
+export const getMarketingAnalyticsApplySetupOpsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/marketing_analytics/apply_setup_ops/`
+}
+
+/**
+ * Apply one or more setup operations from the setup plan, atomically. Either every operation lands or none does — a partially-applied batch has no well-defined undo. Returns `undo_ops`, computed from the pre-change state, which can be POSTed back to reverse the batch. Only send `apply` payloads returned by setup_plan.
+ * @summary Apply setup operations
+ */
+export const marketingAnalyticsApplySetupOpsCreate = async (
+ projectId: string,
+ applySetupOpsApi: ApplySetupOpsApi,
+ options?: RequestInit
+): Promise<ApplySetupOpsResponseApi> => {
+ return apiMutator<ApplySetupOpsResponseApi>(getMarketingAnalyticsApplySetupOpsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(applySetupOpsApi),
+ })
+}
+
export const getMarketingAnalyticsConversionGoalsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/marketing_analytics/conversion_goals/`
}
diff --git a/products/marketing_analytics/frontend/generated/api.zod.ts b/products/marketing_analytics/frontend/generated/api.zod.ts
index d396a4507993..69fe3bf8b1f6 100644
--- a/products/marketing_analytics/frontend/generated/api.zod.ts
+++ b/products/marketing_analytics/frontend/generated/api.zod.ts
@@ -9,6 +9,27 @@
*/
import * as zod from 'zod'
+/**
+ * Apply one or more setup operations from the setup plan, atomically. Either every operation lands or none does — a partially-applied batch has no well-defined undo. Returns `undo_ops`, computed from the pre-change state, which can be POSTed back to reverse the batch. Only send `apply` payloads returned by setup_plan.
+ * @summary Apply setup operations
+ */
+export const marketingAnalyticsApplySetupOpsCreateBodySourceDefault = `setup_tab`
+
+export const MarketingAnalyticsApplySetupOpsCreateBody = /* @__PURE__ */ zod.object({
+ ops: zod
+ .array(zod.unknown())
+ .describe(
+ 'Operations to apply, in order. Send `apply` payloads returned verbatim by setup_plan — never hand-craft one. Navigate-only ops (open_oauth, open_source_wizard, open_settings, fix_platform_urls) are rejected: they describe something a browser or a human does.'
+ ),
+ source: zod
+ .enum(['setup_tab', 'apply_all_safe', 'mcp'])
+ .describe('\* `setup_tab` - setup_tab\n\* `apply_all_safe` - apply_all_safe\n\* `mcp` - mcp')
+ .default(marketingAnalyticsApplySetupOpsCreateBodySourceDefault)
+ .describe(
+ 'Where the request came from, recorded in the activity log\n\n\* `setup_tab` - setup_tab\n\* `apply_all_safe` - apply_all_safe\n\* `mcp` - mcp'
+ ),
+})
+
/**
* Change one conversion goal in place. Fields you send are merged into the stored goal, the rest are kept, and the goal keeps its position in the list. Sending a different `kind` replaces the goal instead, since the shapes don't share their fields.
* @summary Update conversion goal
diff --git a/products/marketing_analytics/mcp/tools.yaml b/products/marketing_analytics/mcp/tools.yaml
index cb7553fae098..3766fa3f5e1e 100644
--- a/products/marketing_analytics/mcp/tools.yaml
+++ b/products/marketing_analytics/mcp/tools.yaml
@@ -9,6 +9,9 @@ feature: marketing_analytics
url_prefix: /marketing
ui_apps: {}
tools:
+ marketing-analytics-apply-setup-ops-create:
+ operation: marketing_analytics_apply_setup_ops_create
+ enabled: false
marketing-analytics-conversion-goals:
operation: marketing_analytics_conversion_goals_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e5572a8f99f6..44b526f0a3da 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9773,6 +9773,40 @@ export namespace Schemas {
config?: unknown;
}
+ /**
+ * * `setup_tab` - setup_tab
+ * * `apply_all_safe` - apply_all_safe
+ * * `mcp` - mcp
+ */
+ export type ApplySetupOpsSourceEnum = typeof ApplySetupOpsSourceEnum[keyof typeof ApplySetupOpsSourceEnum];
+
+
+ export const ApplySetupOpsSourceEnum = {
+ SetupTab: 'setup_tab',
+ ApplyAllSafe: 'apply_all_safe',
+ Mcp: 'mcp',
+ } as const;
+
+ export interface ApplySetupOps {
+ /** Operations to apply, in order. Send `apply` payloads returned verbatim by setup_plan — never hand-craft one. Navigate-only ops (open_oauth, open_source_wizard, open_settings, fix_platform_urls) are rejected: they describe something a browser or a human does. */
+ ops: unknown[];
+ /** Where the request came from, recorded in the activity log
+ *
+ * * `setup_tab` - setup_tab
+ * * `apply_all_safe` - apply_all_safe
+ * * `mcp` - mcp */
+ source?: ApplySetupOpsSourceEnum;
+ }
+
+ export interface ApplySetupOpsResponse {
+ /** The operations that were applied */
+ applied: unknown[];
+ /** Operations that reverse this batch, in the order they should be sent. Computed server-side from the pre-change state — POST them back to undo. */
+ undo_ops: unknown[];
+ /** The config as it now stands */
+ marketing_analytics_config: unknown;
+ }
+
export interface ApprovalPolicy {
readonly id: string;
/** @maxLength 128 */