: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
perf(scoping): skip the team read in root team saves that leave the team out (#127510)
Julian Bez3384b0971cbf
diff --git a/posthog/models/scoping/test_root_mixin.py b/posthog/models/scoping/test_root_mixin.pyindex 53b563d7e1d2..0e7e6254b0ac 100644--- a/posthog/models/scoping/test_root_mixin.py+++ b/posthog/models/scoping/test_root_mixin.py@@ -9,16 +9,24 @@ save() rewrite from the parent — and that the CI introspection (which isan isinstance check on the manager named `objects` in `_meta.managers_map`)recognises all three adoption styles: the two mixins and an ad-hoc`objects = TeamScopedManager()`.++`TestRootTeamMixinSave` covers when `RootTeamMixin.save()` rewrites a child team to its parent."""from types import SimpleNamespace+from posthog.test.base import BaseTest+from django.db import modelsfrom django.test import SimpleTestCase+from parameterized import parameterized+from posthog.models.scoping.manager import TeamScopedManagerfrom posthog.models.scoping.product_mixin import ProductTeamModelfrom posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.team import Team+from posthog.models.user_home_settings import UserHomeSettingsfrom posthog.models.utils import RootTeamManager, RootTeamMixin@@ -85,3 +93,40 @@ class TestFailClosedIntrospection(SimpleTestCase):))self.assertFalse(self._objects_is_team_scoped(stub)) # type: ignore[arg-type]+++class TestRootTeamMixinSave(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.child = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")++ def test_insert_on_a_child_team_stores_the_parent(self) -> None:+ home = UserHomeSettings.objects.create(team=self.child, user=self.user)++ assert home.team_id == self.team.id++ @parameterized.expand(+ [+ ("full_save", None),+ ("team_in_update_fields", ["team"]),+ ("team_id_in_update_fields", ["team_id"]),+ ]+ )+ def test_save_that_writes_the_team_stores_the_parent(self, _name: str, update_fields: list[str] | None) -> None:+ home = UserHomeSettings.objects.create(team=self.team, user=self.user)+ home.team = self.child++ home.save(update_fields=update_fields)++ assert UserHomeSettings.objects.get(pk=home.pk).team_id == self.team.id++ @parameterized.expand([("list", lambda: ["tabs"]), ("iterator", lambda: iter(["tabs"]))])+ def test_partial_update_without_the_team_does_not_load_it(self, _name: str, update_fields) -> None:+ created = UserHomeSettings.objects.create(team=self.team, user=self.user)+ home = UserHomeSettings.objects.get(pk=created.pk)+ home.tabs = [{"id": "home"}]++ home.save(update_fields=update_fields())++ assert not UserHomeSettings.team.is_cached(home)+ assert UserHomeSettings.objects.get(pk=home.pk).tabs == [{"id": "home"}]diff --git a/posthog/models/utils.py b/posthog/models/utils.pyindex 56a0b4812c18..62490f7b9318 100644--- a/posthog/models/utils.py+++ b/posthog/models/utils.py@@ -451,6 +451,14 @@ class RootTeamMixin(models.Model):abstract = Truedef save(self, *args: Any, **kwargs: Any) -> None:+ # A partial update that leaves the team out cannot change it, so it skips the team read.+ # In a loop over rows that did not load the team, that read costs one query per row.+ if kwargs.get("update_fields") is not None:+ # Django accepts any iterable here, so read it once and pass the same values on.+ kwargs["update_fields"] = update_fields = list(kwargs["update_fields"])+ if not {"team", "team_id"} & set(update_fields):+ super().save(*args, **kwargs)+ returnif hasattr(self, "team") and self.team and hasattr(self.team, "parent_team") and self.team.parent_team: # type: ignoreself.team = self.team.parent_team # type: ignoresuper().save(*args, **kwargs)