: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
feat(retention): reconcile team retention on entitlement change (#78557)
Andy Zhao4383db56b3f8
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 63bcaa1382cd..4e5620dcbaaa 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -21,6 +21,10 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organizationfrom posthog.models.organization import OrganizationMembership, OrganizationUsageInfo+from posthog.models.team.event_retention import (+ organization_events_retention_months,+ reconcile_organization_events_retention,+)from posthog.models.team.logs_retention import reset_revoked_logs_retentionfrom posthog.models.user import User@@ -267,9 +271,16 @@ class BillingManager:previous_feature_keys = {feature.get("key") for feature in (organization.available_product_features or []) if feature}+ previous_retention_months = organization_events_retention_months(organization)organization.available_product_features = available_product_featuresorganization.save()+ if (+ available_product_features+ and organization_events_retention_months(organization) != previous_retention_months+ ):+ reconcile_organization_events_retention(organization)+# Only reset on a non-empty list: the retention reset is not self-healing, so an# empty error-path response must not permanently downgrade team settings.if available_product_features:@@ -500,6 +511,7 @@ class BillingManager:available_product_features = data.get("available_product_features", None)revoked_feature_keys: set[str] = set()+ events_retention_changed = False# An empty list is deliberately ignored: this runs on hot paths (get_billing, usage# reports) and a partial or error-path billing response must not downgrade the org.# Genuine cancellations still send the (non-empty) free-tier feature list.@@ -509,7 +521,9 @@ class BillingManager:}new_feature_keys = {feature.get("key") for feature in available_product_features if feature}revoked_feature_keys = previous_feature_keys - new_feature_keys+ previous_retention_months = organization_events_retention_months(organization)organization.available_product_features = data["available_product_features"]+ events_retention_changed = organization_events_retention_months(organization) != previous_retention_monthsorg_modified = Truenever_drop_data = cast(bool | None, data.get("never_drop_data"))@@ -545,6 +559,9 @@ class BillingManager:if org_modified:organization.save()+ if events_retention_changed:+ reconcile_organization_events_retention(organization)+if revoked_feature_keys:reset_revoked_logs_retention(organization, revoked_feature_keys)diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex b46e306baa18..dc78961c56ee 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -18,6 +18,7 @@ from rest_framework.exceptions import NotAuthenticatedfrom posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.models.organization import Organization, OrganizationMembership+from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom ee.billing.billing_manager import (@@ -424,6 +425,29 @@ class TestBillingManager(BaseTest):assert organization.available_product_features == [{"key": "surveys", "name": "Surveys"}]assert self.team.logs_settings == {"retention_days": 14}+ @patch("ee.billing.billing_manager.requests.get")+ def test_update_available_product_features_reconciles_events_retention(self, mock_get: MagicMock):+ organization = self.organization+ Team.objects.filter(pk=self.team.pk).update(event_retention_months=84)++ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ mock_get.return_value.status_code = 200+ mock_get.return_value.json.return_value = {+ "available_product_features": [+ {"key": "product_analytics_data_retention", "name": "Data retention", "limit": 1, "unit": "year"}+ ]+ }++ BillingManager(license).update_available_product_features(organization)++ self.team.refresh_from_db()+ assert self.team.event_retention_months == 12+@patch("ee.billing.billing_manager.update_org_billing_quotas", side_effect=Exception("Redis unavailable"))def test_update_org_details_saves_org_fields_before_recomputing_existing_quota_limits(self, update_org_billing_quotas_mock: MagicMockdiff --git a/posthog/models/team/event_retention.py b/posthog/models/team/event_retention.pyindex 73e7ab89054d..52f1b0a4a929 100644--- a/posthog/models/team/event_retention.py+++ b/posthog/models/team/event_retention.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import TYPE_CHECKING, Optionalfrom django.conf import settings@@ -9,6 +9,9 @@ from posthog.constants import AvailableFeaturefrom posthog.models.organization import ProductFeaturefrom posthog.models.team.team import Team+if TYPE_CHECKING:+ from posthog.models.organization import Organization+# Grandfather default: existing teams keep 7 years (84 months) until billing assigns a shorter window.DEFAULT_EVENT_RETENTION_MONTHS = 84@@ -89,3 +92,21 @@ def parse_events_feature_to_months(retention_feature: ProductFeature | None) -># Events retention is a months/years concept; an unexpected unit (e.g. days) grandfathers rather than# introducing a lossy day→month conversion.return DEFAULT_EVENT_RETENTION_MONTHS+++def organization_events_retention_months(organization: "Organization") -> int:+ return parse_events_feature_to_months(organization.get_available_feature(EVENTS_DATA_RETENTION_FEATURE))+++def reconcile_organization_events_retention(organization: "Organization") -> int:+ """Align the org's teams with its entitlement-derived retention window; returns teams updated.++ Re-reads the persisted entitlement so overlapping billing syncs can't apply a stale in-memory snapshot.+ """+ organization.refresh_from_db(fields=["available_product_features"])+ target_months = organization_events_retention_months(organization)+ return (+ Team.objects.filter(organization=organization)+ .exclude(event_retention_months=target_months)+ .update(event_retention_months=target_months)+ )diff --git a/posthog/models/team/test/test_event_retention.py b/posthog/models/team/test/test_event_retention.pyindex db04d078f9eb..940e63dad3ff 100644--- a/posthog/models/team/test/test_event_retention.py+++ b/posthog/models/team/test/test_event_retention.py@@ -1,9 +1,12 @@from typing import cast+from posthog.test.base import BaseTest+from parameterized import parameterized-from posthog.models.organization import ProductFeature-from posthog.models.team.event_retention import parse_events_feature_to_months+from posthog.models.organization import Organization, ProductFeature+from posthog.models.team.event_retention import parse_events_feature_to_months, reconcile_organization_events_retention+from posthog.models.team.team import Teamclass TestParseEventsFeatureToMonths:@@ -28,3 +31,39 @@ class TestParseEventsFeatureToMonths:)def test_parse(self, feature: dict | None, expected: int) -> None:assert parse_events_feature_to_months(cast(ProductFeature | None, feature)) == expected+++class TestReconcileOrganizationEventsRetention(BaseTest):+ def _set_retention_feature(self, limit: int, unit: str) -> None:+ Organization.objects.filter(pk=self.organization.pk).update(+ available_product_features=[{"key": "product_analytics_data_retention", "limit": limit, "unit": unit}]+ )+ self.organization.refresh_from_db()++ def test_updates_all_mismatched_teams(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other")+ Team.objects.filter(pk__in=[self.team.pk, other_team.pk]).update(event_retention_months=84)+ self._set_retention_feature(1, "year")++ assert reconcile_organization_events_retention(self.organization) == 2++ self.team.refresh_from_db()+ other_team.refresh_from_db()+ assert self.team.event_retention_months == 12+ assert other_team.event_retention_months == 12++ def test_no_write_when_already_aligned(self) -> None:+ self._set_retention_feature(7, "years")+ Team.objects.filter(pk=self.team.pk).update(event_retention_months=84)++ assert reconcile_organization_events_retention(self.organization) == 0++ def test_reconciles_from_persisted_entitlement_not_snapshot(self) -> None:+ Team.objects.filter(pk=self.team.pk).update(event_retention_months=84)+ stale_org = Organization.objects.get(pk=self.organization.pk)+ self._set_retention_feature(1, "year")++ assert reconcile_organization_events_retention(stale_org) == 1++ self.team.refresh_from_db()+ assert self.team.event_retention_months == 12