: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): add the 24-month default events retention period (#128744)
Andy Zhao4bc304128633
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex 902621ce0d45..bfa6a7b814f7 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -108,9 +108,12 @@ export const defaultMocks: Mocks = {docs_url: 'https://posthog.com/docs/data/events-retention',project_retention_months: null,organization_retention_months: null,+ default_retention_months: 84,+ default_is_grandfathered: true,plan_retention_months: 84,min_retention_months: 1,max_retention_months: 84,+ retention_months_choices: [1, 3, 12, 24, 36, 60, 84],},'/api/projects/:team_id/annotations/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/event_definitions/': EMPTY_PAGINATED_RESPONSE,@@ -179,9 +182,12 @@ export const defaultMocks: Mocks = {'/api/organizations/:organization_id/roles/': EMPTY_PAGINATED_RESPONSE,'/api/organizations/:organization_id/events_retention_setting/': {organization_retention_months: null,+ default_retention_months: 84,+ default_is_grandfathered: true,plan_retention_months: 84,min_retention_months: 1,max_retention_months: 84,+ retention_months_choices: [1, 3, 12, 24, 36, 60, 84],},'/api/organizations/:organization_id/resource_access': EMPTY_PAGINATED_RESPONSE,'/api/organizations/:organization_id/members/': toPaginatedResponse([diff --git a/posthog/constants.py b/posthog/constants.pyindex 9fc83040dd8c..53bc247fb8c7 100644--- a/posthog/constants.py+++ b/posthog/constants.py@@ -59,6 +59,7 @@ class AvailableFeature(StrEnum):ORGANIZATION_APP_QUERY_CONCURRENCY_LIMIT = "organization_app_query_concurrency_limit"SESSION_REPLAY_DATA_RETENTION = "session_replay_data_retention"PRODUCT_ANALYTICS_DATA_RETENTION = "product_analytics_data_retention"+ PRODUCT_ANALYTICS_STANDARD_DATA_RETENTION = "product_analytics_standard_data_retention"LOGS_RETENTION_30D = "logs_retention_30d"AUDIT_LOGS = "audit_logs"APPROVALS = "approvals"diff --git a/posthog/models/team/event_retention.py b/posthog/models/team/event_retention.pyindex 5fd24888aaea..f69a73ca741d 100644--- a/posthog/models/team/event_retention.py+++ b/posthog/models/team/event_retention.py@@ -1,7 +1,10 @@+from collections.abc import Collection, Sequencefrom datetime import date-from typing import TYPE_CHECKING, Optional+from typing import Optional+from uuid import UUIDfrom django.conf import settings+from django.db import connectionfrom django.utils import timezoneimport posthoganalytics@@ -9,13 +12,11 @@ from dateutil.relativedelta import relativedeltafrom posthog.cloud_utils import is_cloudfrom posthog.constants import AvailableFeature-from posthog.models.events_retention_config import effective_events_retention-from posthog.models.organization import ProductFeature+from posthog.dataclasses import frozen+from posthog.models.events_retention_config import OrganizationEventsRetentionConfig, effective_events_retention+from posthog.models.organization import Organization, 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@@ -25,6 +26,9 @@ EVENTS_DATA_RETENTION_FLAG = "events-data-retention"# Billing entitlement key the sync job reconciles Team.event_retention_months against.EVENTS_DATA_RETENTION_FEATURE = AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION+STANDARD_DATA_RETENTION_FEATURE = AvailableFeature.PRODUCT_ANALYTICS_STANDARD_DATA_RETENTION+STANDARD_DEFAULT_PERIOD_MONTHS = 24+def should_enforce_events_retention(team_id: int) -> bool:"""Whether events-data-retention is enforced for this team — the cohort gate.@@ -52,9 +56,9 @@ def should_enforce_events_retention(team_id: int) -> bool:def events_retention_months_for_team(team: Optional[Team], team_id: Optional[int]) -> Optional[int]:"""Months of events retention to floor a query's events scans to, or None if retention isn't enforced.- The plan's window, shortened by the window set in project or organization settings. Computed once per query in- prepare_ast_for_printing. The cohort gate runs first and is DB-free, so non-cohort teams (the vast majority during- rollout) never hit Postgres here — only an enforced team triggers the lean field load.+ The period set in project or organization settings, never past the plan's, else the default. Computed once per+ query in prepare_ast_for_printing. The cohort gate runs first and is DB-free, so non-cohort teams (the vast majority+ during rollout) never hit Postgres here — only an enforced team triggers the lean field load."""if team_id is None:if team is None:@@ -65,27 +69,94 @@ def events_retention_months_for_team(team: Optional[Team], team_id: Optional[intreturn Noneif team is None:- team = Team.objects.filter(id=team_id).only("event_retention_months").first()+ team = Team.objects.filter(id=team_id).only("organization_id", "event_retention_months").first()if team is None:return None- plan_months = team.event_retention_months or DEFAULT_EVENT_RETENTION_MONTHS- configured_months = _configured_events_retention_months(team)- return min(plan_months, configured_months) if configured_months is not None else plan_months+ return _queryable_months(team)-_REQUEST_CACHED_CONFIGURED_RETENTION_ATTR = "_request_cached_configured_events_retention_months"+_REQUEST_CACHED_QUERYABLE_MONTHS_ATTR = "_request_cached_queryable_events_retention_months"-def _configured_events_retention_months(team: Team) -> int | None:- """Memoise the window set in settings on the team instance, which is request-scoped in practice.+def _queryable_months(team: Team) -> int:+ """Memoise the period on the team instance, which is request-scoped in practice.Every insight on a dashboard and every query it prints asks again, and each ask is a Postgres query."""- if not hasattr(team, _REQUEST_CACHED_CONFIGURED_RETENTION_ATTR):- configured = effective_events_retention(team_ids=[team.id])- setattr(team, _REQUEST_CACHED_CONFIGURED_RETENTION_ATTR, configured[0].months if configured else None)- return getattr(team, _REQUEST_CACHED_CONFIGURED_RETENTION_ATTR)+ if not hasattr(team, _REQUEST_CACHED_QUERYABLE_MONTHS_ATTR):+ setattr(team, _REQUEST_CACHED_QUERYABLE_MONTHS_ATTR, events_retention_periods([team])[team.id])+ return getattr(team, _REQUEST_CACHED_QUERYABLE_MONTHS_ATTR)+++@frozen+class TeamPlan:+ team_id: int+ organization_id: UUID+ plan_months: int+++def team_plan(team: Team) -> TeamPlan:+ return TeamPlan(+ team_id=team.id,+ organization_id=team.organization_id,+ plan_months=team.event_retention_months or DEFAULT_EVENT_RETENTION_MONTHS,+ )+++def default_period(plan_months: int, standard: bool, min_months: int | None) -> int:+ default = min(plan_months, STANDARD_DEFAULT_PERIOD_MONTHS) if standard else plan_months+ return min(plan_months, max(default, min_months)) if min_months is not None else default+++def events_retention_periods(teams: Sequence[Team]) -> dict[int, int]:+ return retention_periods([team_plan(team) for team in teams])+++def retention_periods(plans: Sequence[TeamPlan]) -> dict[int, int]:+ setting_months = {+ item.team_id: item.months for item in effective_events_retention(team_ids=[p.team_id for p in plans])+ }+ defaults = default_periods([plan for plan in plans if plan.team_id not in setting_months])+ return {+ plan.team_id: min(plan.plan_months, setting_months[plan.team_id])+ if plan.team_id in setting_months+ else defaults[plan.team_id]+ for plan in plans+ }+++def default_periods(teams: Sequence[TeamPlan]) -> dict[int, int]:+ shortened = {team.organization_id for team in teams if STANDARD_DEFAULT_PERIOD_MONTHS < team.plan_months}+ standard = _standard_retention_organization_ids(shortened) if shortened else set()+ min_months = _minimum_months(standard) if standard else {}+ return {+ team.team_id: default_period(+ team.plan_months, team.organization_id in standard, min_months.get(team.organization_id)+ )+ for team in teams+ }+++def _minimum_months(organization_ids: Collection[UUID]) -> dict[UUID, int]:+ return dict(+ OrganizationEventsRetentionConfig.objects.filter(+ organization_id__in=organization_ids, min_events_retention_months__isnull=False+ ).values_list("organization_id", "min_events_retention_months")+ )+++def _standard_retention_organization_ids(organization_ids: Collection[UUID]) -> set[UUID]:+ with connection.cursor() as cursor:+ cursor.execute(+ f"""+ SELECT id FROM {Organization._meta.db_table}+ WHERE id = ANY(%s::uuid[])+ AND EXISTS (SELECT 1 FROM unnest(available_product_features) AS feature WHERE feature->>'key' = %s)+ """,+ [list(organization_ids), str(STANDARD_DATA_RETENTION_FEATURE)],+ )+ return {organization_id for (organization_id,) in cursor.fetchall()}def events_retention_floor_date(team: Team, retention_months: int) -> date:@@ -118,11 +189,15 @@ def parse_events_feature_to_months(retention_feature: ProductFeature | None) ->return DEFAULT_EVENT_RETENTION_MONTHS-def organization_events_retention_months(organization: "Organization") -> int:+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:+def has_standard_retention(organization: Organization) -> bool:+ return organization.is_feature_available(STANDARD_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.diff --git a/posthog/models/team/test/test_event_retention.py b/posthog/models/team/test/test_event_retention.pyindex 7d48a8bebac9..352f70d72b71 100644--- a/posthog/models/team/test/test_event_retention.py+++ b/posthog/models/team/test/test_event_retention.py@@ -87,19 +87,21 @@ class TestReconcileOrganizationEventsRetention(BaseTest):class TestEventsRetentionMonthsForTeam(BaseTest):@parameterized.expand([- ("plan_window_only", None, 24),- ("shorter_set_window", 12, 12),- ("set_window_longer_than_a_downgraded_plan", 36, 24),+ ("plan_period_only", 24, None, 24),+ ("shorter_set_period", 24, 12, 12),+ ("set_period_longer_than_a_downgraded_plan", 24, 36, 24),+ ("set_period_on_a_plan_past_the_standard_default", 84, 36, 36),])def test_takes_the_shorter_of_the_plan_and_the_set_window(- self, _name: str, set_months: int | None, expected: int+ self, _name: str, plan_months: int, set_months: int | None, expected: int) -> None:- self.team.event_retention_months = 24+ self.team.event_retention_months = plan_monthsself.team.save()if set_months is not None:TeamEventsRetentionConfig.objects.create(team=self.team, events_retention_months=set_months)- assert events_retention_months_for_team(self.team, self.team.id) == expected+ with self.assertNumQueries(1):+ assert events_retention_months_for_team(self.team, self.team.id) == expectedwith self.assertNumQueries(0):assert events_retention_months_for_team(self.team, self.team.id) == expecteddiff --git a/products/product_analytics/backend/events_retention.py b/products/product_analytics/backend/events_retention.pyindex fc5400130adb..67ceb65b2f59 100644--- a/products/product_analytics/backend/events_retention.py+++ b/products/product_analytics/backend/events_retention.py@@ -13,11 +13,18 @@ from posthog.models.events_retention_config import ()from posthog.models.organization import Organizationfrom posthog.models.team import Team-from posthog.models.team.event_retention import organization_events_retention_months+from posthog.models.team.event_retention import (+ STANDARD_DEFAULT_PERIOD_MONTHS,+ default_period,+ has_standard_retention,+ organization_events_retention_months,+)from posthog.models.user import Userfrom products.product_analytics.backend.facade.contracts import OrganizationEventsRetention+RETENTION_MONTHS_CHOICES = (1, 3, 12, 24, 36, 60, 84)+def _report_retention_set(organization: Organization,@@ -77,12 +84,17 @@ def _report_retention_set(def organization_events_retention(organization: Organization) -> OrganizationEventsRetention:config = OrganizationEventsRetentionConfig.objects.filter(organization_id=organization.id).first()plan_months = organization_events_retention_months(organization)+ staff_min = config.min_events_retention_months if config else Nonestaff_max = config.max_events_retention_months if config else None+ standard = has_standard_retention(organization)return OrganizationEventsRetention(organization_months=config.default_events_retention_months if config else None,+ default_months=default_period(plan_months, standard, staff_min),+ default_is_grandfathered=not standard and plan_months > STANDARD_DEFAULT_PERIOD_MONTHS,plan_months=plan_months,- min_months=(config.min_events_retention_months if config else None) or 1,+ min_months=staff_min or 1,max_months=min(plan_months, staff_max) if staff_max else plan_months,+ months_choices=list(RETENTION_MONTHS_CHOICES),)@@ -95,7 +107,15 @@ def project_events_retention_months(team: Team) -> int | None:def _check_allowed(retention: OrganizationEventsRetention, months: int | None) -> None:- if months is not None and not retention.min_months <= months <= retention.max_months:+ if months is None:+ return+ if months not in retention.months_choices:+ *shorter, longest = retention.months_choices+ raise ValidationError(+ f"Events retention has to be {', '.join(map(str, shorter))} or {longest} months. "+ "Contact PostHog support to set another period."+ )+ if not retention.min_months <= months <= retention.max_months:raise ValidationError(f"Events retention has to be {describe_months_range(retention.min_months, retention.max_months)}.")diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex 6b396e416610..53a575ae60c4 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -192,12 +192,15 @@ class InsightDashboardContext:@dataclass(frozen=True)class OrganizationEventsRetention:- """The window an organization set for its projects, and the windows its admins can set, in months."""+ """The period an organization set for its projects, its default, and the periods its admins can set, in months."""organization_months: int | None+ default_months: int+ default_is_grandfathered: boolplan_months: intmin_months: intmax_months: int+ months_choices: list[int]@dataclass(frozen=True)diff --git a/products/product_analytics/backend/presentation/events_retention.py b/products/product_analytics/backend/presentation/events_retention.pyindex c15bb04cb5ff..84f6de84c049 100644--- a/products/product_analytics/backend/presentation/events_retention.py+++ b/products/product_analytics/backend/presentation/events_retention.py@@ -15,6 +15,7 @@ from posthog.models.team.event_retention import events_retention_floor_date, evefrom posthog.models.user import Userfrom posthog.permissions import OrganizationAdminWritePermissions+from products.product_analytics.backend.facade.contracts import OrganizationEventsRetentionfrom products.product_analytics.backend.facade.events_retention import (organization_events_retention,project_events_retention_months,@@ -43,7 +44,20 @@ class OrganizationEventsRetentionSerializer(serializers.Serializer):organization_retention_months = serializers.IntegerField(read_only=True,allow_null=True,- help_text="The window, in months, that every project without its own window uses. Null while the organization keeps events for its plan's window.",+ help_text="The period, in months, that every project without its own period uses. Null while those projects use the default period.",+ )+ default_retention_months = serializers.IntegerField(+ read_only=True,+ help_text="The period, in months, that projects use while no period is set for them or their organization. 24 months on current plans, never longer than the plan's period and never shorter than the shortest period an admin can set. Plans from before the 24-month default use the plan's period.",+ )+ default_is_grandfathered = serializers.BooleanField(+ read_only=True,+ help_text="Whether the default is longer than 24 months because the plan predates the 24-month default.",+ )+ retention_months_choices = serializers.ListField(+ child=serializers.IntegerField(),+ read_only=True,+ help_text="The periods, in months, an admin can choose from. A save also has to be between min_retention_months and max_retention_months. Only PostHog staff can set other periods.",)plan_retention_months = serializers.IntegerField(read_only=True,@@ -90,6 +104,18 @@ class EventsRetentionUpdateSerializer(serializers.Serializer):)+def _organization_fields(organization: OrganizationEventsRetention) -> dict[str, Any]:+ return {+ "organization_retention_months": organization.organization_months,+ "default_retention_months": organization.default_months,+ "default_is_grandfathered": organization.default_is_grandfathered,+ "retention_months_choices": organization.months_choices,+ "plan_retention_months": organization.plan_months,+ "min_retention_months": organization.min_months,+ "max_retention_months": organization.max_months,+ }++@extend_schema(tags=["events_retention"])class EventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "project"@@ -101,7 +127,6 @@ class EventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):retained_from = (events_retention_floor_date(self.team, retention_months) if retention_months is not None else None)- organization = organization_events_retention(self.organization)return Response(EventsRetentionSerializer({@@ -109,10 +134,7 @@ class EventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):"retained_from": retained_from,"docs_url": EVENTS_RETENTION_DOCS_URL,"project_retention_months": project_events_retention_months(self.team),- "organization_retention_months": organization.organization_months,- "plan_retention_months": organization.plan_months,- "min_retention_months": organization.min_months,- "max_retention_months": organization.max_months,+ **_organization_fields(organization_events_retention(self.organization)),}).data)@@ -165,15 +187,9 @@ class OrganizationEventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSepermission_classes = [OrganizationAdminWritePermissions]def _retention_response(self) -> Response:- organization = organization_events_retention(self.organization)return Response(OrganizationEventsRetentionSerializer(- {- "organization_retention_months": organization.organization_months,- "plan_retention_months": organization.plan_months,- "min_retention_months": organization.min_months,- "max_retention_months": organization.max_months,- }+ _organization_fields(organization_events_retention(self.organization))).data)@@ -181,8 +197,8 @@ class OrganizationEventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSeoperation_id="organization_events_retention_retrieve",summary="Get the organization's events retention window",description=(- "Returns the events retention window that every project without its own window uses, and the range an "- "organization admin can set."+ "Returns the events retention period that every project without its own period uses, the default period "+ "while none is set, and the range an organization admin can set."),responses={200: OrganizationEventsRetentionSerializer},)diff --git a/products/product_analytics/backend/tests/api/test_events_retention.py b/products/product_analytics/backend/tests/api/test_events_retention.pyindex 4e84a7127777..b845ee74753c 100644--- a/products/product_analytics/backend/tests/api/test_events_retention.py+++ b/products/product_analytics/backend/tests/api/test_events_retention.py@@ -34,11 +34,13 @@ class TestEventsRetentionAPI(APIBaseTest):def organization_url(self) -> str:return f"/api/organizations/{self.organization.id}/events_retention_setting/"- def _set_plan_years(self, years: int) -> None:+ def _set_plan_years(self, years: int, standard: bool = False) -> None:+ standard_feature = [{"key": "product_analytics_standard_data_retention"}] if standard else []Organization.objects.filter(pk=self.organization.pk).update(available_product_features=[{"key": "product_analytics_data_retention", "limit": years, "unit": "years"},{"key": "access_control", "name": "Access control"},+ *standard_feature,])@@ -77,11 +79,39 @@ class TestEventsRetentionAPI(APIBaseTest):"docs_url": "https://posthog.com/docs/data/events-retention","project_retention_months": None,"organization_retention_months": None,+ "default_retention_months": 12,+ "default_is_grandfathered": False,"plan_retention_months": 12,"min_retention_months": 1,"max_retention_months": 12,+ "retention_months_choices": [1, 3, 12, 24, 36, 60, 84],}+ @parameterized.expand(+ [+ ("standard_plan_defaults_to_24_months", True, None, 24, False),+ ("grandfathered_plan_defaults_to_its_whole_period", False, None, 84, True),+ ("staff_minimum_raises_the_standard_default", True, 36, 36, False),+ ]+ )+ def test_reports_the_default_period(+ self, _name: str, standard: bool, staff_min: int | None, expected_months: int, grandfathered: bool+ ) -> None:+ self._set_plan_years(7, standard=standard)+ self.team.event_retention_months = 84+ self.team.save()+ if staff_min is not None:+ OrganizationEventsRetentionConfig.objects.create(+ organization=self.organization, min_events_retention_months=staff_min+ )++ project = self.client.get(self.url()).json()+ organization = self.client.get(self.organization_url()).json()++ assert (project["retention_months"], project["default_retention_months"]) == (expected_months, expected_months)+ assert (organization["default_retention_months"], organization["max_retention_months"]) == (expected_months, 84)+ assert organization["default_is_grandfathered"] is grandfathered+@override_settings(EVENTS_DATA_RETENTION_ENFORCED=False)def test_reports_no_window_until_retention_is_enforced(self) -> None:response = self.client.get(self.url())@@ -96,11 +126,11 @@ class TestEventsRetentionAPI(APIBaseTest):organization=self.organization, default_events_retention_months=12)- response = self.client.post(self.url(), {"retention_months": 6}, format="json")+ response = self.client.post(self.url(), {"retention_months": 3}, format="json")assert response.status_code == status.HTTP_200_OK- assert response.json()["retention_months"] == 6- assert response.json()["project_retention_months"] == 6+ assert response.json()["retention_months"] == 3+ assert response.json()["project_retention_months"] == 3assert ActivityLog.objects.filter(team_id=self.team.id, scope="Team", activity="updated").exists()response = self.client.post(self.url(), {"retention_months": None}, format="json")@@ -114,7 +144,8 @@ class TestEventsRetentionAPI(APIBaseTest):[("longer_than_the_plan", "organization_admin", 36, status.HTTP_400_BAD_REQUEST),("shorter_than_the_staff_minimum", "organization_admin", 3, status.HTTP_400_BAD_REQUEST),- ("only_a_project_admin", "project_admin", 6, status.HTTP_403_FORBIDDEN),+ ("not_one_of_the_choices", "organization_admin", 18, status.HTTP_400_BAD_REQUEST),+ ("only_a_project_admin", "project_admin", 12, status.HTTP_403_FORBIDDEN),])def test_rejects_a_project_window(self, _name: str, level: str, months: int, expected_status: int) -> None:@@ -136,9 +167,12 @@ class TestEventsRetentionAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"organization_retention_months": 12,+ "default_retention_months": 24,+ "default_is_grandfathered": False,"plan_retention_months": 24,"min_retention_months": 1,"max_retention_months": 24,+ "retention_months_choices": [1, 3, 12, 24, 36, 60, 84],}assert self.client.get(self.url()).json()["retention_months"] == 12assert ActivityLog.objects.filter(@@ -153,8 +187,8 @@ class TestEventsRetentionAPI(APIBaseTest):@parameterized.expand([- ("longer_than_the_staff_maximum", "organization_admin", 18, status.HTTP_400_BAD_REQUEST),- ("only_a_project_admin", "project_admin", 6, status.HTTP_403_FORBIDDEN),+ ("longer_than_the_staff_maximum", "organization_admin", 24, status.HTTP_400_BAD_REQUEST),+ ("only_a_project_admin", "project_admin", 12, status.HTTP_403_FORBIDDEN),])def test_rejects_an_organization_window(self, _name: str, level: str, months: int, expected_status: int) -> None:@@ -218,7 +252,7 @@ class TestEventsRetentionAPI(APIBaseTest):self.client.credentials(**headers)with patch("posthoganalytics.capture") as capture:- for before, after in [(None, 6), (6, 12), (12, None)]:+ for before, after in [(None, 3), (3, 12), (12, None)]:capture.reset_mock()with self.captureOnCommitCallbacks(execute=True):response = self.client.post(url, {"retention_months": after}, format="json")@@ -257,10 +291,10 @@ class TestEventsRetentionAPI(APIBaseTest):url = self.url() if scope == "project" else self.organization_url()with patch("posthoganalytics.capture"), self.captureOnCommitCallbacks(execute=True):- response = self.client.post(url, {"retention_months": 6}, format="json", HTTP_REFERER="https://[")+ response = self.client.post(url, {"retention_months": 3}, format="json", HTTP_REFERER="https://[")assert response.status_code == status.HTTP_200_OK- assert response.json()[f"{scope}_retention_months"] == 6+ assert response.json()[f"{scope}_retention_months"] == 3@parameterized.expand([("project",), ("organization",)])def test_does_not_track_rolled_back_retention_changes(self, scope: str) -> None:@@ -269,7 +303,7 @@ class TestEventsRetentionAPI(APIBaseTest):with patch("posthoganalytics.capture") as capture, self.captureOnCommitCallbacks(execute=True):with transaction.atomic():- response = self.client.post(url, {"retention_months": 6}, format="json")+ response = self.client.post(url, {"retention_months": 3}, format="json")assert response.status_code == status.HTTP_200_OKassert not any(call.kwargs.get("event") == "events retention set" for call in capture.call_args_list)transaction.set_rollback(True)@@ -300,11 +334,11 @@ class TestEventsRetentionAPI(APIBaseTest):with patch("posthoganalytics.capture") as capture, self.captureOnCommitCallbacks(execute=True):if scope == "project":set_project_events_retention(- self.team, 6, user=self.user, was_impersonated=False, analytics_properties=properties+ self.team, 3, user=self.user, was_impersonated=False, analytics_properties=properties)else:set_organization_events_retention(- self.organization, 6, user=self.user, was_impersonated=False, analytics_properties=properties+ self.organization, 3, user=self.user, was_impersonated=False, analytics_properties=properties)properties["$ai_trace_id"] = "changed after save"@@ -317,7 +351,7 @@ class TestEventsRetentionAPI(APIBaseTest):assert captured["mcp_client_name"] == "client"assert captured["scope"] == scopeassert captured["organization_id"] == str(self.organization.id)- assert captured["retention_months"] == 6+ assert captured["retention_months"] == 3assert captured["previous_retention_months"] is Noneassert captured["was_impersonated"] is Falseassert "$mcp_conversation_id" not in captureddiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 4837b5fc04d8..6f1f4ffab906 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -9,10 +9,16 @@*/export interface OrganizationEventsRetentionApi {/**- * The window, in months, that every project without its own window uses. Null while the organization keeps events for its plan's window.+ * The period, in months, that every project without its own period uses. Null while those projects use the default period.* @nullable*/readonly organization_retention_months: number | null+ /** The period, in months, that projects use while no period is set for them or their organization. 24 months on current plans, never longer than the plan's period and never shorter than the shortest period an admin can set. Plans from before the 24-month default use the plan's period. */+ readonly default_retention_months: number+ /** Whether the default is longer than 24 months because the plan predates the 24-month default. */+ readonly default_is_grandfathered: boolean+ /** The periods, in months, an admin can choose from. A save also has to be between min_retention_months and max_retention_months. Only PostHog staff can set other periods. */+ readonly retention_months_choices: readonly number[]/** The longest window the organization's plan allows, in months. */readonly plan_retention_months: number/** The shortest window an admin can set, in months. */@@ -236,10 +242,16 @@ export interface ElementValueApi {export interface EventsRetentionApi {/**- * The window, in months, that every project without its own window uses. Null while the organization keeps events for its plan's window.+ * The period, in months, that every project without its own period uses. Null while those projects use the default period.* @nullable*/readonly organization_retention_months: number | null+ /** The period, in months, that projects use while no period is set for them or their organization. 24 months on current plans, never longer than the plan's period and never shorter than the shortest period an admin can set. Plans from before the 24-month default use the plan's period. */+ readonly default_retention_months: number+ /** Whether the default is longer than 24 months because the plan predates the 24-month default. */+ readonly default_is_grandfathered: boolean+ /** The periods, in months, an admin can choose from. A save also has to be between min_retention_months and max_retention_months. Only PostHog staff can set other periods. */+ readonly retention_months_choices: readonly number[]/** The longest window the organization's plan allows, in months. */readonly plan_retention_months: number/** The shortest window an admin can set, in months. */diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.tsindex 96d724c7d533..f91789b0edfd 100644--- a/products/product_analytics/frontend/generated/api.ts+++ b/products/product_analytics/frontend/generated/api.ts@@ -86,7 +86,7 @@ export const getOrganizationEventsRetentionRetrieveUrl = (organizationId: string}/**- * Returns the events retention window that every project without its own window uses, and the range an organization admin can set.+ * Returns the events retention period that every project without its own period uses, the default period while none is set, and the range an organization admin can set.* @summary Get the organization's events retention window*/export const organizationEventsRetentionRetrieve = async (diff --git a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.tsindex d13428646fcc..2a6506415489 100644--- a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts+++ b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts@@ -19,6 +19,7 @@ const RETENTION = {plan_retention_months: 84,min_retention_months: 1,max_retention_months: 84,+ retention_months_choices: [1, 3, 12, 24, 36, 60, 84],}describe('dataRetentionBannerLogic', () => {diff --git a/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsxindex b55b1b2b4445..47dfa95cf893 100644--- a/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx+++ b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx@@ -25,9 +25,12 @@ const retentionMocks = (): ReturnType<typeof mswDecorator> => {const organization: OrganizationEventsRetentionApi = {organization_retention_months: organizationMonths,+ default_retention_months: 36,+ default_is_grandfathered: true,plan_retention_months: 36,min_retention_months: 1,max_retention_months: 36,+ retention_months_choices: [1, 3, 12, 24, 36, 60, 84],}const project: EventsRetentionApi = {...organization,diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a279b2222506..a890fe5fcaf9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42496,10 +42496,16 @@ export namespace Schemas {export interface EventsRetention {/**- * The window, in months, that every project without its own window uses. Null while the organization keeps events for its plan's window.+ * The period, in months, that every project without its own period uses. Null while those projects use the default period.* @nullable*/readonly organization_retention_months: number | null;+ /** The period, in months, that projects use while no period is set for them or their organization. 24 months on current plans, never longer than the plan's period and never shorter than the shortest period an admin can set. Plans from before the 24-month default use the plan's period. */+ readonly default_retention_months: number;+ /** Whether the default is longer than 24 months because the plan predates the 24-month default. */+ readonly default_is_grandfathered: boolean;+ /** The periods, in months, an admin can choose from. A save also has to be between min_retention_months and max_retention_months. Only PostHog staff can set other periods. */+ readonly retention_months_choices: readonly number[];/** The longest window the organization's plan allows, in months. */readonly plan_retention_months: number;/** The shortest window an admin can set, in months. */@@ -70011,10 +70017,16 @@ export namespace Schemas {export interface OrganizationEventsRetention {/**- * The window, in months, that every project without its own window uses. Null while the organization keeps events for its plan's window.+ * The period, in months, that every project without its own period uses. Null while those projects use the default period.* @nullable*/readonly organization_retention_months: number | null;+ /** The period, in months, that projects use while no period is set for them or their organization. 24 months on current plans, never longer than the plan's period and never shorter than the shortest period an admin can set. Plans from before the 24-month default use the plan's period. */+ readonly default_retention_months: number;+ /** Whether the default is longer than 24 months because the plan predates the 24-month default. */+ readonly default_is_grandfathered: boolean;+ /** The periods, in months, an admin can choose from. A save also has to be between min_retention_months and max_retention_months. Only PostHog staff can set other periods. */+ readonly retention_months_choices: readonly number[];/** The longest window the organization's plan allows, in months. */readonly plan_retention_months: number;/** The shortest window an admin can set, in months. */