: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(experiments): read team settings in one query (#126254)
Anders1424e876c380
diff --git a/posthog/api/team/integration_config.py b/posthog/api/team/integration_config.pyindex f02d2228f9e7..b2fac437d1bc 100644--- a/posthog/api/team/integration_config.py+++ b/posthog/api/team/integration_config.py@@ -8,6 +8,7 @@ from django.utils import timezonefrom rest_framework import exceptions, request, response, serializersfrom posthog.event_usage import report_user_action+from posthog.exceptions import as_drf_validation_errorfrom posthog.models import Organization, Team, Userfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.logs_retention import (@@ -387,7 +388,7 @@ def handle_experiments_config(request: request.Request, team: Team) -> response.team_id=team.id, update=TeamExperimentsSettingsUpdate(**serializer.validated_data))except ExperimentValidationError as error:- raise serializers.ValidationError({error.field: [str(error)]} if error.field else [str(error)])+ raise as_drf_validation_error(error)else:experiments_settings = experiments_api.get_team_experiments_settings(team.id)diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.pyindex 784dd479dffd..821b43995668 100644--- a/products/experiments/backend/facade/api.py+++ b/products/experiments/backend/facade/api.py@@ -21,6 +21,7 @@ from posthog.schema import ExperimentEventExposureConfigfrom posthog.models.team import Teamfrom posthog.models.team.extensions import get_or_create_team_extension+from posthog.models.team.team import DEPRECATED_ATTRSfrom posthog.models.user import Userfrom products.experiments.backend.experiment_service import ExperimentService@@ -384,7 +385,18 @@ def list_precomputation_enabled_team_ids(team_ids: Collection[int] | None = Nonedef _team_experiments_config(team_id: int) -> TeamExperimentsConfig:- return get_or_create_team_extension(Team.objects.get(id=team_id), TeamExperimentsConfig)+ try:+ # Join the team because the activity log on every save and the repository check read `config.team`.+ # `select_related` builds the team columns from the model rather than through `TeamManager`, so re-apply+ # its defer. Without it every settings read and update loads the deprecated taxonomy columns, which TOAST+ # out to megabytes per team.+ return (+ TeamExperimentsConfig.objects.select_related("team")+ .defer(*(f"team__{attr}" for attr in DEPRECATED_ATTRS))+ .get(team_id=team_id)+ )+ except TeamExperimentsConfig.DoesNotExist:+ return get_or_create_team_extension(Team.objects.get(id=team_id), TeamExperimentsConfig)def set_precomputation_enabled(*, team_id: int, enabled: bool) -> None:diff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex b53eedc8a26b..07c44fc30b8f 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -283,6 +283,7 @@ class ExperimentValidationError(Exception):def __init__(self, message: str, *, field: str | None = None) -> None:super().__init__(message)+ self.message = message# The input field that the message is about, so that an HTTP boundary can report the error on that field.# None when the message is about the input as a whole.self.field = fielddiff --git a/products/experiments/backend/test/test_facade.py b/products/experiments/backend/test/test_facade.pyindex 34deefac332b..7b5ac23402a7 100644--- a/products/experiments/backend/test/test_facade.py+++ b/products/experiments/backend/test/test_facade.py@@ -24,7 +24,9 @@ from parameterized import parameterizedfrom posthog.models.organization import Organizationfrom posthog.models.team import Team+from posthog.models.team.team import DEPRECATED_ATTRSfrom posthog.models.user import User+from posthog.test.db_context_capturing import capture_db_queriesfrom posthog.test.persons import create_personfrom products.experiments.backend.facade import api, count_running_experiments_on_feature_flag_called, create_experiment@@ -635,7 +637,13 @@ class TestTeamExperimentsSettings(BaseTest):flag_cleanup_repository="posthog/posthog",)- assert api.get_team_experiments_settings(self.team.id) == TeamExperimentsSettings(+ with self.assertNumQueries(1), capture_db_queries() as queries:+ settings = api.get_team_experiments_settings(self.team.id)++ # A team join must keep the deprecated taxonomy columns deferred, as `TeamManager` does.+ selected = " ".join(query["sql"] for query in queries.captured_queries)+ assert [attr for attr in DEPRECATED_ATTRS if f'"{attr}"' in selected] == []+ assert settings == TeamExperimentsSettings(experiment_recalculation_times=("02:00:00", "14:00:00"),default_experiment_confidence_level=Decimal("0.90"),default_experiment_stats_method="frequentist",