: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
fix(marketing): preserve unrelated settings on partial updates (#98501)
Javier Bahamondes255fdfb6e226
diff --git a/docs/internal/marketing-analytics-configuration-writes.md b/docs/internal/marketing-analytics-configuration-writes.mdnew file mode 100644index 000000000000..d16775e2d36a--- /dev/null+++ b/docs/internal/marketing-analytics-configuration-writes.md@@ -0,0 +1,5 @@+# Marketing configuration writes++Settings updates send only the changed field and refresh the Marketing configuration under a row lock, preserving unrelated concurrent changes.++Explicit conversion-goal list updates still replace the list; simultaneous edits to that same list are not merged.diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.test.tsnew file mode 100644index 000000000000..f0139e66abb3--- /dev/null+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.test.ts@@ -0,0 +1,25 @@+import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { initKeaTests } from '~/test/init'++import { marketingAnalyticsSettingsLogic } from './marketingAnalyticsSettingsLogic'++describe('marketing settings partial updates', () => {+ beforeEach(() => initKeaTests())++ it('does not submit goals when changing the test-account filter', async () => {+ const logic = marketingAnalyticsSettingsLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic, () => logic.actions.updateFilterTestAccounts(true))+ .toDispatchActions([+ teamLogic.actionCreators.updateCurrentTeam({+ marketing_analytics_config: { filter_test_accounts: true },+ }),+ ])+ .toFinishAllListeners()+ logic.unmount()+ })+})diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.tsindex 02321cf102e2..b326d3b254e0 100644--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsSettingsLogic.ts@@ -544,23 +544,23 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLog],}),listeners(({ actions, values }) => {- const updateCurrentTeam = (): void => {+ const updateCurrentTeam = (field: keyof MarketingAnalyticsConfig): void => {if (values.marketingAnalyticsConfig) {- const payload = { marketing_analytics_config: values.marketingAnalyticsConfig }+ const payload = { marketing_analytics_config: { [field]: values.marketingAnalyticsConfig[field] } }actions.updateCurrentTeam(payload)}}const trackSourceConfigured = (): void => {- updateCurrentTeam()+ updateCurrentTeam('sources_map')actions.addProductIntent({product_type: ProductKey.MARKETING_ANALYTICS,intent_context: ProductIntentContext.MARKETING_ANALYTICS_SOURCE_CONFIGURED,})}- const trackSettingsUpdated = (): void => {- updateCurrentTeam()+ const trackSettingsUpdated = (field: keyof MarketingAnalyticsConfig): void => {+ updateCurrentTeam(field)actions.addProductIntent({product_type: ProductKey.MARKETING_ANALYTICS,intent_context: ProductIntentContext.MARKETING_ANALYTICS_SETTINGS_UPDATED,@@ -569,16 +569,16 @@ export const marketingAnalyticsSettingsLogic = kea<marketingAnalyticsSettingsLogreturn {updateSourceMapping: trackSourceConfigured,- updateConversionGoals: trackSettingsUpdated,- addOrUpdateConversionGoal: trackSettingsUpdated,- removeConversionGoal: trackSettingsUpdated,- updateAttributionWindowDays: trackSettingsUpdated,- updateAttributionMode: trackSettingsUpdated,+ updateConversionGoals: () => trackSettingsUpdated('conversion_goals'),+ addOrUpdateConversionGoal: () => trackSettingsUpdated('conversion_goals'),+ removeConversionGoal: () => trackSettingsUpdated('conversion_goals'),+ updateAttributionWindowDays: () => trackSettingsUpdated('attribution_window_days'),+ updateAttributionMode: () => trackSettingsUpdated('attribution_mode'),// Persist only: this one is a dashboard filter, not a trip to the settings screen.- updateFilterTestAccounts: () => updateCurrentTeam(),- updateCampaignNameMappings: trackSettingsUpdated,- updateCustomSourceMappings: trackSettingsUpdated,- updateCampaignFieldPreferences: trackSettingsUpdated,+ updateFilterTestAccounts: () => updateCurrentTeam('filter_test_accounts'),+ updateCampaignNameMappings: () => trackSettingsUpdated('campaign_name_mappings'),+ updateCustomSourceMappings: () => trackSettingsUpdated('custom_source_mappings'),+ updateCampaignFieldPreferences: () => trackSettingsUpdated('campaign_field_preferences'),testMapping: async ({ tableId, sourceMap }) => {try {const response = await api.create(diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 4ad452ce8e00..86c65a1b26ea 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -803,7 +803,9 @@ class TeamMarketingAnalyticsConfigSerializer(serializers.ModelSerializer, UserAcinternal_value["_campaign_field_preferences"] = internal_value["campaign_field_preferences"]return internal_value+ @transaction.atomicdef update(self, instance, validated_data):+ instance.refresh_from_db(from_queryset=TeamMarketingAnalyticsConfig.objects.select_for_update())# Handle sources_map with partial updatesif "sources_map" in validated_data:new_sources_map = validated_data["sources_map"]diff --git a/products/marketing_analytics/backend/test_api_conversion_goals.py b/products/marketing_analytics/backend/test_api_conversion_goals.pyindex 0be68ed418d9..fdb1c712986b 100644--- a/products/marketing_analytics/backend/test_api_conversion_goals.py+++ b/products/marketing_analytics/backend/test_api_conversion_goals.py@@ -1,8 +1,15 @@-from posthog.test.base import APIBaseTest+from concurrent.futures import ThreadPoolExecutor+from queue import Queue+from time import monotonic++from posthog.test.base import APIBaseTest, NonAtomicBaseTestfrom unittest.mock import AsyncMock, patch+from django.db import close_old_connections, connection, transaction+from parameterized import parameterized+from posthog.api.team import TeamMarketingAnalyticsConfigSerializerfrom posthog.constants import AvailableFeaturefrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import OrganizationMembership@@ -60,6 +67,18 @@ class TestConversionGoalWrites(APIBaseTest):def stored_goals(self) -> list[dict]:return TeamMarketingAnalyticsConfig.objects.get(team=self.team).conversion_goals+ def test_stale_settings_save_preserves_new_goals(self) -> None:+ stale_config = self.team.marketing_analytics_config+ response = self.create_goal("Purchases")+ self.assertEqual(response.status_code, 201)+ goals = self.stored_goals()++ TeamMarketingAnalyticsConfigSerializer().update(stale_config, {"filter_test_accounts": True})++ stale_config.refresh_from_db()+ self.assertTrue(stale_config.filter_test_accounts)+ self.assertEqual(stale_config.conversion_goals, goals)+def test_create_appends_without_touching_existing_goals(self):first = self.create_goal("Sign ups").json()["goal"]response = self.create_goal("Purchases", event="purchase")@@ -430,3 +449,44 @@ class TestConversionGoalIdIsOneName(APIBaseTest):delete = self.client.delete(f"{self.base_url}/{goal_id}/delete")assert (update.status_code, delete.status_code) == (200, 200), (update.json(), delete.json())+++class TestConcurrentMarketingSettingsWrites(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_settings_wait_for_goal_write_and_preserve_it(self) -> None:+ config = self.team.marketing_analytics_config+ backend_pid: Queue[int] = Queue()++ def save_settings() -> None:+ close_old_connections()+ try:+ with connection.cursor() as cursor:+ cursor.execute("SET statement_timeout = '10s'")+ cursor.execute("SELECT pg_backend_pid()")+ backend_pid.put(cursor.fetchone()[0])+ TeamMarketingAnalyticsConfigSerializer().update(config, {"filter_test_accounts": True})+ finally:+ close_old_connections()++ goals = [{**goal_payload("Purchases", conversion_goal_id="purchase-goal"), "name": "Purchases"}]+ with ThreadPoolExecutor(max_workers=1) as executor:+ with transaction.atomic():+ locked = TeamMarketingAnalyticsConfig.objects.select_for_update().get(pk=config.pk)+ pending = executor.submit(save_settings)+ pid = backend_pid.get(timeout=10)+ deadline = monotonic() + 10+ with connection.cursor() as cursor:+ while True:+ cursor.execute("SELECT cardinality(pg_blocking_pids(%s)) > 0", [pid])+ if cursor.fetchone()[0]:+ break+ self.assertFalse(pending.done(), "settings finished before the goal transaction committed")+ self.assertLess(monotonic(), deadline, "settings did not wait for the configuration lock")+ locked.conversion_goals = goals+ locked.save(update_fields=["_conversion_goals"])+ pending.result(timeout=10)++ config.refresh_from_db()+ self.assertTrue(config.filter_test_accounts)+ self.assertEqual(config.conversion_goals, goals)