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.

fix(onboarding): stop concurrent team patches clobbering completion (#73000)

Fernando Gomes1a98fe2cd283
diff --git a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
index d0236bfe2743..b22b6669054f 100644
--- a/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
+++ b/frontend/src/scenes/onboarding/legacy/onboardingLogic.tsx
@@ -784,9 +784,6 @@ export const onboardingLogic = kea<onboardingLogicType>([
tickedTaskIds.add(id)
}
}
- if (setup && tickedTaskIds.size > 0) {
- setup.actions.markTaskAsCompleted(Array.from(tickedTaskIds))
- }
for (const productKey of visitedProducts) {
actions.recordProductIntentOnboardingComplete({ product_type: productKey as ProductKey })
}
@@ -802,6 +799,12 @@ export const onboardingLogic = kea<onboardingLogicType>([
completed_snippet_onboarding: true,
has_completed_onboarding_for: completedMap,
})
+ // Tick setup tasks only after the completion PATCH has committed. Firing this
+ // concurrently raced two team PATCHes against each other, and the stale
+ // onboarding_tasks write could erase the just-saved completion fields.
+ if (setup && tickedTaskIds.size > 0) {
+ setup.actions.markTaskAsCompleted(Array.from(tickedTaskIds))
+ }
setQuickstartAsDefaultHomepageOnce(previouslyOnboardedMap)
} catch {
// The completion update failed, so leave the user's homepage untouched
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 5f1a0619805e..eb6db5a4ebac 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -76,6 +76,7 @@ from posthog.models.team.event_retention import should_enforce_events_retention
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.setup_tasks import SetupTaskId
from posthog.models.team.team import CURRENCY_CODE_CHOICES, Team
+from posthog.models.team.team_caching import set_team_in_cache
from posthog.models.team.util import actions_that_require_current_team
from posthog.models.utils import UUIDT
from posthog.permissions import (
@@ -1199,25 +1200,43 @@ class ProjectBackwardCompatSerializer(
validated_data, team.conversations_enabled, team.conversations_settings
)
- should_team_be_saved_too = False
+ # Persist only the fields this request changes. A full-row save() writes back every
+ # column from this request's snapshot of the team, so two concurrent PATCHes clobber
+ # each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
+ # erased `has_completed_onboarding_for` and reverted `completed_snippet_onboarding`,
+ # bouncing freshly onboarded users back into onboarding.
+ updated_team_fields = []
+ updated_project_fields = []
for attr, value in validated_data.items():
if attr not in self.Meta.team_passthrough_fields:
# This attr is a Project field
setattr(instance, attr, value)
+ updated_project_fields.append(attr)
else:
# This attr is actually on the Project's passthrough Team
- should_team_be_saved_too = True
setattr(team, attr, value)
+ updated_team_fields.append(attr)
if "name" in validated_data:
# Keep Team.name mirroring Project.name: surfaces like the organization's teams
# list and the app context still read the name off the Team row
- should_team_be_saved_too = True
team.name = validated_data["name"]
-
- instance.save()
- if should_team_be_saved_too:
- team.save()
+ updated_team_fields.append("name")
+
+ if updated_project_fields:
+ instance.save(update_fields=updated_project_fields)
+ if updated_team_fields:
+ # auto_now fields only refresh when included in update_fields
+ team.save(update_fields=[*updated_team_fields, "updated_at"])
+ # Snapshot before the cache refresh below so the audit diff only reflects this
+ # request's writes, not fields a concurrent request changed.
+ team_after_update = team.__dict__.copy()
+ if updated_team_fields:
+ # The in-memory team may hold stale values for fields a concurrent request
+ # changed, and the post-save receiver has already cached that snapshot. Reload
+ # and re-cache so the team cache reflects the merged row.
+ team.refresh_from_db()
+ set_team_in_cache(team.api_token, team)
if "proactive_tasks_enabled" in validated_data:
if validated_data["proactive_tasks_enabled"]:
@@ -1234,7 +1253,6 @@ class ProjectBackwardCompatSerializer(
source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
).delete()
- team_after_update = team.__dict__.copy()
project_after_update = instance.__dict__.copy()
team_changes = dict_changes_between("Team", team_before_update, team_after_update, use_field_exclusions=True)
project_changes = dict_changes_between(
diff --git a/posthog/api/team.py b/posthog/api/team.py
index f9a3d1fda6c5..fb2d0703f6d2 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -57,6 +57,7 @@ from posthog.models.team.event_retention import should_enforce_events_retention
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.team.setup_tasks import SetupTaskId
from posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCY
+from posthog.models.team.team_caching import set_team_in_cache
from posthog.models.team.util import actions_that_require_current_team
from posthog.models.utils import UUIDT
from posthog.permissions import (
@@ -1624,7 +1625,26 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
**validated_data["modifiers"],
}
- updated_team = super().update(instance, validated_data)
+ # Persist only the fields this request changes. A full-row save() writes back every
+ # column from this request's snapshot of the team, so two concurrent PATCHes clobber
+ # each other — e.g. an `onboarding_tasks` PATCH racing the onboarding-completion PATCH
+ # erased `has_completed_onboarding_for` and reverted `completed_snippet_onboarding`,
+ # bouncing freshly onboarded users back into onboarding.
+ for attr, value in validated_data.items():
+ setattr(instance, attr, value)
+ if validated_data:
+ # auto_now fields only refresh when included in update_fields
+ instance.save(update_fields=[*validated_data.keys(), "updated_at"])
+ # Snapshot before the cache refresh below so the audit diff only reflects this
+ # request's writes, not fields a concurrent request changed.
+ after_update = instance.__dict__.copy()
+ if validated_data:
+ # The in-memory instance may hold stale values for fields a concurrent request
+ # changed, and the post-save receiver has already cached that snapshot. Reload
+ # and re-cache so the team cache reflects the merged row.
+ instance.refresh_from_db()
+ set_team_in_cache(instance.api_token, instance)
+ updated_team = instance
if "proactive_tasks_enabled" in validated_data:
# Backward compat for old proactive tasks enabled field, remove after February 2026
@@ -1642,7 +1662,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,
).delete()
- changes = dict_changes_between("Team", before_update, updated_team.__dict__, use_field_exclusions=True)
+ changes = dict_changes_between("Team", before_update, after_update, use_field_exclusions=True)
log_activity(
organization_id=cast(UUIDT, instance.organization_id),
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 7fe7bc3e64a4..84065a321b81 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -1249,6 +1249,29 @@ def team_api_test_factory():
team=self.team,
)
+ def test_concurrent_team_patches_do_not_clobber_each_other(self) -> None:
+ # Simulates two racing PATCHes: the second request loaded the team before the
+ # first one committed. With a full-row save, the second write reverts the first
+ # request's onboarding-completion fields; with update_fields it must not.
+ stale_team = Team.objects.get(pk=self.team.pk)
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/",
+ {"completed_snippet_onboarding": True, "has_completed_onboarding_for": {"product_analytics": True}},
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ with patch.object(Project, "passthrough_team", property(lambda _self: stale_team)):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/",
+ {"session_recording_opt_in": True},
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ self.team.refresh_from_db()
+ assert self.team.completed_snippet_onboarding is True
+ assert self.team.has_completed_onboarding_for == {"product_analytics": True}
+ assert self.team.session_recording_opt_in is True
+
@patch("posthog.api.project.report_user_action")
@patch("posthog.api.team.report_user_action")
def test_can_complete_product_onboarding(