: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(tracing): serialize retention updates (#108170)
Paul D'Ambra83177daf94f8
diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 83782f8be39d..1353b0e56458 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -328,12 +328,7 @@ class TeamTracingConfigSerializer(serializers.ModelSerializer):if error:raise exceptions.ValidationError(error)- # Traces reuse the Logs retention entitlement.- required_feature = required_logs_retention_feature(value)- if required_feature and (organization is None or not organization.is_feature_available(required_feature)):- raise exceptions.PermissionDenied(- f"This organization does not have permission to set traces retention to {value} days."- )+ _check_traces_retention_entitlement(value, organization)throttle_error = retention_update_throttle_error(self.instance.retention_last_updated if self.instance is not None else None@@ -362,7 +357,24 @@ def handle_tracing_config(request: request.Request, team: Team) -> response.Respconfig, data=request.data, partial=True, context={"request": request, "team": team})serializer.is_valid(raise_exception=True)- serializer.save()+ with transaction.atomic():+ locked_config = TeamTracingConfig.objects.select_for_update().get(team=team)+ retention = serializer.validated_data.get("retention_days")+ if retention is not None and retention != locked_config.retention_days:+ throttle_error = retention_update_throttle_error(locked_config.retention_last_updated)+ if throttle_error:+ raise exceptions.ValidationError({"retention_days": throttle_error})+ if locked_config.retention_days != config.retention_days:+ # Entitlement resets do not set retention_last_updated, so the throttle cannot see them.+ raise exceptions.ValidationError(+ {"retention_days": "Retention changed. Reload the settings and retry."}+ )+ # Billing can revoke the entitlement after validation read the organization.+ _check_traces_retention_entitlement(+ retention, Organization.objects.only("available_product_features").get(id=team.organization_id)+ )+ serializer.instance = locked_config+ serializer.save()return response.Response(serializer.data)return response.Response(TeamTracingConfigSerializer(config).data)@@ -1435,6 +1447,15 @@ def _custom_retention_flag_enabled(organization: Organization | None, user: Any,return _flag_enabled_for_caller(LOGS_CUSTOM_RETENTION_FLAG, organization, user, team)+def _check_traces_retention_entitlement(days: int, organization: Organization | None) -> None:+ # Traces reuse the Logs retention entitlement.+ required_feature = required_logs_retention_feature(days)+ if required_feature and (organization is None or not organization.is_feature_available(required_feature)):+ raise exceptions.PermissionDenied(+ f"This organization does not have permission to set traces retention to {days} days."+ )++def _custom_logs_retention_enabled(serializer: serializers.BaseSerializer, team: Team | None) -> bool:request = serializer.context.get("request")return _custom_retention_flag_enabled(diff --git a/posthog/api/test/test_team_tracing_config.py b/posthog/api/test/test_team_tracing_config.pyindex e7ba685aabc4..ea8843a925f6 100644--- a/posthog/api/test/test_team_tracing_config.py+++ b/posthog/api/test/test_team_tracing_config.py@@ -1,14 +1,18 @@+from datetime import timedelta+from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.db import connectionfrom django.test import SimpleTestCase+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.team import TRACES_RETENTION_FLAG, TeamTracingConfigSerializerfrom posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, Team+from posthog.models import Organization, OrganizationMembership, Teamfrom posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.logs_retention import DEFAULT_LOGS_RETENTION_DAYS, reset_revoked_logs_retention@@ -21,7 +25,7 @@ from products.tracing.backend.facade.team_extension import ()# Both routes resolve to the same handler — /api/projects/ is canonical, /api/environments/-# remains as the back-compat alias. See `handle_tracing_config` in posthog/api/team.py.+# remains as the back-compat alias. See `handle_tracing_config`.URL_PREFIXES = [("projects", "api/projects"), ("environments", "api/environments")]DEFAULT_CONFIG = {@@ -225,13 +229,22 @@ class TestTeamTracingConfigRetention(APIBaseTest):]self.organization.save()- def test_patch_free_tier_records_the_update_time(self):- response = self.client.patch(self.url, {"retention_days": 14}, format="json")+ def test_patch_evaluates_the_flag_outside_the_transaction(self) -> None:+ self._grant_30d_retention()+ transaction_depth = len(connection.savepoint_ids)++ def flag_enabled(*args: object, **kwargs: object) -> bool:+ self.assertEqual(len(connection.savepoint_ids), transaction_depth)+ return True++ with patch("posthog.api.team.posthog_feature_flag_enabled", side_effect=flag_enabled) as mock_flag:+ response = self.client.patch(self.url, {"retention_days": 30}, format="json")self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertGreater(mock_flag.call_count, 0)config = get_or_create_team_extension(self.team, TeamTracingConfig)config.refresh_from_db()- self.assertEqual(config.retention_days, 14)+ self.assertEqual(config.retention_days, 30)def test_paid_tier_requires_the_org_entitlement(self):denied = self.client.patch(self.url, {"retention_days": 30}, format="json")@@ -261,14 +274,56 @@ class TestTeamTracingConfigRetention(APIBaseTest):response = self.client.patch(self.url, {"retention_days": 17}, format="json")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- def test_second_change_within_24_hours_is_refused(self):+ @parameterized.expand([(False,), (True,)])+ def test_second_change_within_24_hours_is_refused(self, stale_config: bool) -> None:self._grant_30d_retention()+ config = get_or_create_team_extension(self.team, TeamTracingConfig)self.assertEqual(self.client.patch(self.url, {"retention_days": 30}, format="json").status_code, 200)- second = self.client.patch(self.url, {"retention_days": 14}, format="json")+ if not stale_config:+ config.refresh_from_db()+ with patch("posthog.api.team.get_or_create_team_extension", return_value=config):+ second = self.client.patch(self.url, {"retention_days": 14}, format="json")self.assertEqual(second.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("once per 24 hours", str(second.json()))+ def test_concurrent_entitlement_reset_is_not_overwritten(self) -> None:+ self._grant_30d_retention()+ self.assertEqual(self.client.patch(self.url, {"retention_days": 30}, format="json").status_code, 200)++ TeamTracingConfig.objects.filter(team=self.team).update(+ retention_last_updated=timezone.now() - timedelta(hours=25)+ )+ snapshot = get_or_create_team_extension(self.team, TeamTracingConfig)+ snapshot.refresh_from_db()++ # An entitlement reset lands after the read and leaves retention_last_updated alone.+ TeamTracingConfig.objects.filter(team=self.team).update(retention_days=DEFAULT_TRACES_RETENTION_DAYS)++ with patch("posthog.api.team.get_or_create_team_extension", return_value=snapshot):+ response = self.client.patch(self.url, {"retention_days": 30}, format="json")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("Reload the settings and retry", str(response.json()))++ config = get_or_create_team_extension(self.team, TeamTracingConfig)+ config.refresh_from_db()+ self.assertEqual(config.retention_days, DEFAULT_TRACES_RETENTION_DAYS)++ def test_entitlement_revoked_after_validation_is_refused(self) -> None:+ self._grant_30d_retention()++ def revoke_during_validation(flag: str, *args: object, **kwargs: object) -> bool:+ Organization.objects.filter(id=self.organization.id).update(available_product_features=[])+ return flag == TRACES_RETENTION_FLAG++ with patch("posthog.api.team.posthog_feature_flag_enabled", side_effect=revoke_during_validation):+ response = self.client.patch(self.url, {"retention_days": 30}, format="json")+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.json())++ config = get_or_create_team_extension(self.team, TeamTracingConfig)+ config.refresh_from_db()+ self.assertEqual(config.retention_days, DEFAULT_TRACES_RETENTION_DAYS)+def test_an_unrelated_update_is_not_throttled(self):self._grant_30d_retention()self.assertEqual(self.client.patch(self.url, {"retention_days": 30}, format="json").status_code, 200)diff --git a/posthog/models/team/logs_retention.py b/posthog/models/team/logs_retention.pyindex dd506ccc8675..c308736e697d 100644--- a/posthog/models/team/logs_retention.py+++ b/posthog/models/team/logs_retention.py@@ -3,6 +3,7 @@ from collections.abc import Sequencefrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING+from django.db import transactionfrom django.utils import timezonefrom django.utils.dateparse import parse_datetime@@ -93,6 +94,26 @@ def reset_span_retention_rules(rules: list["TracesRetentionRule"], *, batch_sizeTracesRetentionRule.objects.unscoped().bulk_update(rules, ["config", "version"], batch_size=batch_size)+def _reset_traces_retention_period(organization: Organization) -> int:+ # Imported here so the tracing product stays off this module's import path.+ from products.tracing.backend.facade.team_extension import TeamTracingConfig # noqa: PLC0415++ with transaction.atomic():+ # Lock every config, not only paid ones: a retention update in flight holds its row lock,+ # so this waits for it and then sees the period it saved.+ configs = TeamTracingConfig.objects.select_for_update(of=("self",)).filter(team__organization=organization)+ paid_configs = [+ config+ for config in configs.only("team_id", "retention_days")+ if config.retention_days > DEFAULT_LOGS_RETENTION_DAYS+ ]+ for config in paid_configs:+ config.retention_days = DEFAULT_LOGS_RETENTION_DAYS+ if paid_configs:+ TeamTracingConfig.objects.bulk_update(paid_configs, ["retention_days"])+ return len(paid_configs)++def reset_revoked_logs_retention(organization: Organization, revoked_feature_keys: set[str]) -> int:"""Reset team Logs retention to the default when its required feature was revoked.@@ -122,16 +143,8 @@ def reset_revoked_logs_retention(organization: Organization, revoked_feature_key# Imported here so the tracing product stays off this module's import path.from products.tracing.backend.facade.retention import TracesRetentionRule # noqa: PLC0415- from products.tracing.backend.facade.team_extension import TeamTracingConfig # noqa: PLC0415# Traces reuse the Logs entitlement, so their default period and span rules are reset with it.- tracing_configs = list(- TeamTracingConfig.objects.filter(- team__organization=organization, retention_days__gt=DEFAULT_LOGS_RETENTION_DAYS- ).only("team_id", "retention_days")- )- for config in tracing_configs:- config.retention_days = DEFAULT_LOGS_RETENTION_DAYS# The organization spans several environments, so this read is deliberately unscoped.span_rules = list(TracesRetentionRule.objects.unscoped()@@ -141,19 +154,18 @@ def reset_revoked_logs_retention(organization: Organization, revoked_feature_keyif teams:Team.objects.bulk_update(teams, ["logs_settings"])- if tracing_configs:- TeamTracingConfig.objects.bulk_update(tracing_configs, ["retention_days"])+ tracing_configs_reset = _reset_traces_retention_period(organization)if rules:reset_logs_retention_rules(rules)if span_rules:reset_span_retention_rules(span_rules)- if teams or rules or tracing_configs or span_rules:+ if teams or rules or tracing_configs_reset or span_rules:logger.info("Logs retention reset after entitlement revocation",organization_id=str(organization.id),teams_reset=len(teams),rules_reset=len(rules),- tracing_configs_reset=len(tracing_configs),+ tracing_configs_reset=tracing_configs_reset,span_rules_reset=len(span_rules),)return len(teams)