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(experiments): Log experiments settings changes to the activity log (#118549)

Juraj Majerikd5fd278d19ec
diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
index 4677859d7920..70a575055b1b 100644
--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx
@@ -17,6 +17,7 @@ import { Link } from 'lib/lemon-ui/Link'
import { CURRENCY_SYMBOL_TO_EMOJI_MAP, CURRENCY_SYMBOL_TO_NAME_MAP } from 'lib/utils/currency'
import { isObject } from 'lib/utils/guards'
import { pluralize } from 'lib/utils/strings'
+import { ExperimentsConfig } from 'scenes/settings/environment/experimentsConfigLogic'
import { urls } from 'scenes/urls'
import { CurrencyCode } from '~/queries/schema/schema-general'
@@ -158,8 +159,23 @@ function createFixedVerbValueHandler(
}
}
+function createExperimentsDefaultHandler(fieldName: string, format: (value: unknown) => string = String) {
+ return (change: ActivityChange): ChangeMapping | null => {
+ if (change.after === null || change.after === undefined) {
+ return { description: [<>cleared the {fieldName}</>] }
+ }
+ return {
+ description: [
+ <>
+ changed the {fieldName} to <em>{format(change.after)}</em>
+ </>,
+ ],
+ }
+ }
+}
+
const TEAM_PROPERTIES_MAPPING: Record<
- keyof TeamType | 'heatmaps_screenshot_allowed_hostnames',
+ keyof TeamType | keyof ExperimentsConfig | 'heatmaps_screenshot_allowed_hostnames',
(change: ActivityChange) => ChangeMapping | null
> = {
// API-related tokens
@@ -764,6 +780,43 @@ const TEAM_PROPERTIES_MAPPING: Record<
revenue_analytics_config: revenueAnalyticsConfigurationDescriber,
core_events_config: coreEventsConfigurationDescriber,
+ // Experiments defaults, written by the experiments_config endpoint and logged under the Team scope
+ default_experiment_stats_method: createExperimentsDefaultHandler('default statistical method for experiments'),
+ default_experiment_confidence_level: createExperimentsDefaultHandler(
+ 'default confidence level for experiments',
+ (value) => `${Math.round(Number(value) * 100)}%`
+ ),
+ default_minimum_detectable_effect: createExperimentsDefaultHandler(
+ 'default minimum detectable effect for experiments',
+ (value) => `${value}%`
+ ),
+ default_only_count_matured_users: createBooleanToggleHandler(
+ 'only counting matured users by default in experiments'
+ ),
+ default_cuped_enabled: createBooleanToggleHandler('CUPED by default for experiments'),
+ default_cuped_lookback_days: createExperimentsDefaultHandler('default CUPED lookback window', (value) =>
+ pluralize(Number(value), 'day')
+ ),
+ default_sequential_testing_enabled: createBooleanToggleHandler('sequential testing by default for experiments'),
+ default_sequential_tuning_parameter: createExperimentsDefaultHandler(
+ 'default tuning parameter for sequential testing'
+ ),
+ experiment_recalculation_times: (change) => {
+ if (!Array.isArray(change.after)) {
+ return { description: [<>reset the experiment recalculation time to the default</>] }
+ }
+ // Stored as HH:00:00 strings; the seconds carry no information.
+ const times = change.after.map((time: string) => time.slice(0, 5)).join(', ')
+ return {
+ description: [
+ <>
+ changed the experiment recalculation time to <em>{times} UTC</em>
+ </>,
+ ],
+ }
+ },
+ flag_cleanup_repository: createExperimentsDefaultHandler('default repository for experiment flag cleanup PRs'),
+
// Conversations
conversations_enabled: createBooleanToggleHandler('conversations'),
conversations_settings: () => {
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index 5454fe354700..4ccecb36927d 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -1467,6 +1467,40 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
config.refresh_from_db()
self.assertEqual(config.precomputation_enabled_set_by, TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)
+ def test_experiments_config_changes_are_logged_as_team_activity(self):
+ # The first read creates the config row with defaults, which is not a change anyone made.
+ self.client.get(f"/api/projects/{self.project.id}/experiments_config/")
+ team_activity = ActivityLog.objects.filter(team_id=self.project.id, scope="Team", item_id=str(self.project.id))
+ self.assertEqual(team_activity.count(), 0)
+
+ response = self.client.patch(
+ f"/api/projects/{self.project.id}/experiments_config/",
+ {"default_cuped_enabled": True, "experiment_precomputation_enabled": True},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ log = team_activity.get()
+ self.assertEqual(log.activity, "updated")
+ self.assertEqual(log.user, self.user)
+ assert log.detail is not None
+ # Precomputation is managed by PostHog, so only the customer's own setting is recorded.
+ self.assertEqual(
+ log.detail["changes"],
+ [{"type": "Team", "action": "changed", "field": "default_cuped_enabled", "before": False, "after": True}],
+ )
+
+ def test_experiments_config_created_with_non_default_values_is_logged(self):
+ # The Django admin creates the row and sets values in one save, so there is no update to diff.
+ TeamExperimentsConfig.objects.create(team=self.team, default_cuped_enabled=True)
+
+ log = ActivityLog.objects.get(team_id=self.team.id, scope="Team", item_id=str(self.team.id))
+ assert log.detail is not None
+ self.assertEqual(
+ log.detail["changes"],
+ [{"type": "Team", "action": "changed", "field": "default_cuped_enabled", "before": False, "after": True}],
+ )
+
def test_experiments_config_recalculation_times_write_and_clear(self):
response = self.client.patch(
f"/api/projects/{self.project.id}/experiments_config/",
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index f0d849ad3c17..9a8a14ecb961 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -36,6 +36,7 @@ model_activity:products.data_catalog.backend.activity_logging.handle_metric_acti
model_activity:products.data_quality.backend.activity_logging.handle_data_quality_check_activity
model_activity:products.data_tools.backend.activity_logging.handle_expression_activity
model_activity:products.experiments.backend.activity_logging.handle_experiment_change
+model_activity:products.experiments.backend.activity_logging.handle_team_experiments_config_change
model_activity:products.exports.backend.models.subscription.log_subscription_activity
model_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_change
model_activity:products.legal_documents.backend.signals.handle_legal_document_change
diff --git a/products/experiments/backend/activity_logging.py b/products/experiments/backend/activity_logging.py
index 20e0fbce5b99..9312766927f6 100644
--- a/products/experiments/backend/activity_logging.py
+++ b/products/experiments/backend/activity_logging.py
@@ -5,6 +5,7 @@ from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
from products.experiments.backend.models.web_experiment import WebExperiment
# Kept in sync with DERIVED_RUNNING_TIME_KEYS in
@@ -78,3 +79,46 @@ def handle_experiment_change(
activity=activity,
detail=Detail(changes=changes, name=after_update.name),
)
+
+
+# Precomputation is managed by PostHog (the auto-enrollment job and staff tooling) and has no
+# control in the settings UI, so its changes stay out of the customer's audit trail.
+PRECOMPUTATION_FIELDS = frozenset({"experiment_precomputation_enabled", "precomputation_enabled_set_by"})
+
+
+@mutable_receiver(model_activity_signal, sender=TeamExperimentsConfig)
+def handle_team_experiments_config_change(
+ sender: type[TeamExperimentsConfig],
+ scope: AuditableScope,
+ before_update: TeamExperimentsConfig | None,
+ after_update: TeamExperimentsConfig,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ if activity == "deleted":
+ return
+
+ # The row is created with defaults the first time anything reads the config, which is no
+ # decision a person made. The Django admin can also create it with non-default values in
+ # one save, so a new row is compared against the defaults instead of being skipped.
+ previous = before_update if before_update is not None else TeamExperimentsConfig(team=after_update.team)
+ changes = [
+ change
+ for change in changes_between("Team", previous=previous, current=after_update)
+ if change.field not in PRECOMPUTATION_FIELDS
+ ]
+
+ # Logged under the Team scope, with the team as the item, so the change sits next to the
+ # other project settings in the activity log and the team describer renders it.
+ log_activity(
+ organization_id=after_update.team.organization_id,
+ team_id=after_update.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=after_update.team_id,
+ scope="Team",
+ activity="updated",
+ detail=Detail(changes=changes, name=after_update.team.name),
+ )
diff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.py
index cfd857f53efe..ec90ea77a0f1 100644
--- a/products/experiments/backend/models/team_experiments_config.py
+++ b/products/experiments/backend/models/team_experiments_config.py
@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.organization import Organization
from posthog.models.team import Team
@@ -39,7 +40,7 @@ def validate_recalculation_times(value: object) -> None:
)
-class TeamExperimentsConfig(models.Model):
+class TeamExperimentsConfig(ModelActivityMixin, models.Model):
class PrecomputationEnabledSetBy(models.TextChoices):
MANUAL = "manual", "Manual"
AUTO = "auto", "Auto"