: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): let admins set how long events are kept (#124387)
Andy Zhaoc686e53bbfe7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cce3fead8baf..65914ed77a3e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15411,9 +15411,9 @@ snapshots:scenes-app-settings-environment--settings-environment-privacy--light:hash: v1.k794b7964.e1c7844809613d3fe37e3e3d4d46fc2e9efa7ab0bbd170a3c981295129b089c8.SY2vq7tzOv8Jw0PMzFNoraGb8cphm66m69_hQy4IVPwscenes-app-settings-environment--settings-environment-product-analytics--dark:- hash: v1.k794b7964.f62dae4445da300fa3979596decf449fb3abd5e02ccbe9f36debe98295465da1.9lh-azJ0s62MU-I1WYgw1jYHPOnXXbUX7kypaJFt_7I+ hash: v1.k794b7964.dd04af270d8b0c8161ffda4fab72869eb095b88316b7c2a5355dce22601e520e.vSprt7Y_3PFLl7xVjOxSxaiEXGbvZW-kIUy0_ELUwYEscenes-app-settings-environment--settings-environment-product-analytics--light:- hash: v1.k794b7964.dd07ab91a688091e7e5d6e220333985666c22685aeb699993ba1dcf77e02b550.3L1R_lE5gIqwQE_wT3oUEaybpxehFmeBFjRTdPu85EE+ hash: v1.k794b7964.3a09be20d660e9ff27d0fe7b378344f60738e86ff2f8f8e5f9959e5b460bca0c.7x06Tz9NE7yWPbrKo0aPjNkOtsHIrhWYDVebhKvu_CIscenes-app-settings-environment--settings-environment-replay--dark:hash: v1.k794b7964.75a2bd5b932d561b14f51c304c6ffaa20099c8231d70e98a66c42b3db1944c5c.iDVxspFr0p6xcUytwbMaWOkXRbeRDWhqLkC9FLab9z4scenes-app-settings-environment--settings-environment-replay--light:@@ -15430,6 +15430,22 @@ snapshots:hash: v1.k794b7964.dfaec7406aaa0bf55cf59b389b41a167cdf2fe3e090ecb2b1afd84c6be07affb.4LG7d0X6LMp1TMccke9WIMH7Jfy5gMcnytaH1iarfRAscenes-app-settings-environment--settings-environment-web-analytics--light:hash: v1.k794b7964.b4553dbb84a15391496c2edb32b37890962415241c5e65720176f96aaf9a6c79.e3XURvfm-ojSu2iaXmrhEHQPltapWYsUAWZQktCPSpk+ scenes-app-settings-events-retention--organization-with-window--dark:+ hash: v1.k794b7964.590456a7c33a470ea9ff4c24e944cb4788db20bda989ee4d9ba4f4de493f455a.Jisn6ZhWvAbOuITAEJArRXz7VITk6SqMlCaVaDTzd9A+ scenes-app-settings-events-retention--organization-with-window--light:+ hash: v1.k794b7964.6ceab57d3c2b5cfc45926bb347da12aff69189df7b61ffa59be5ff7943864e44.VUEXVuvYsL-uwVqw92v_2UMfvU2NOscdQ6h600_Xqn8+ scenes-app-settings-events-retention--organization-without-window--dark:+ hash: v1.k794b7964.b9ab252b1de3932da24dbbca690ef96ff87afdff992e737200eb530461ac2842.kSWJZkouRaHtSv-P3WvoWXM0MIdi1-gjjbWDnsTkoNw+ scenes-app-settings-events-retention--organization-without-window--light:+ hash: v1.k794b7964.aa70a345eee42b7d86118921393e0437f1ac8e8490087e8f28014ed717ce74a0.EstIEwAYjRB1vKjSziH_JX830M2lOjNe6M62_tF36fg+ scenes-app-settings-events-retention--project-using-organization-window--dark:+ hash: v1.k794b7964.bf5587730c42a2b73855238ee40f498994e4e876ec7cb983b175cf23dc02cd62.JksxVy9-zRdEYYPR7TcDlymGaeufm3ERJC5zOgVmIDQ+ scenes-app-settings-events-retention--project-using-organization-window--light:+ hash: v1.k794b7964.b634a9c5a3f9da024b8b2ac4a43e75d190206bdbad6cedf2945c6651f4e63459.hcAr1WGa3hs6SGZzlsm2LgiAmSaMMSbBZMNDeIPiWhE+ scenes-app-settings-events-retention--project-with-own-window--dark:+ hash: v1.k794b7964.75be029e0fec0ce60a40ba3ce392ecb8f1229caa2b36de18c0988f5972358224.7AKIj8bBPZ4GxGxkSz4OFkL2ecqRb2pQAtQDPuz9mKI+ scenes-app-settings-events-retention--project-with-own-window--light:+ hash: v1.k794b7964.d592697a1ed9083c5d81f6edb5c37cd27cb11788f924afe89da8cba612721cdc.oRuG2Nik5jxq_FHrFkpHdj4Zp7eQsViF169yTMkBJpAscenes-app-settings-identity-provider-configuration--oidc--dark:hash: v1.k794b7964.1177527533a6ec000b396e1ee39627722226aed5cbab11759198dbbc2d72dcb3.NqKVUNSdSz-yE-r1M5EiEIaPRbQwBbyjCAf7rSSi9Doscenes-app-settings-identity-provider-configuration--oidc--light:@@ -15475,13 +15491,13 @@ snapshots:scenes-app-settings-organization--settings-organization-danger-zone--light:hash: v1.k794b7964.ec8a0cdfdb2ca359ac431b9ecdcde4b10253077c1193816d2f8754f32501c2c7.oUWhWgl8T0sa5sjqOJulNyPzepG-NB7pNf29UC8k-Vwscenes-app-settings-organization--settings-organization-details--dark:- hash: v1.k794b7964.2a394715ace756bd71b576c33b9978f7be37553244ba87530cc1b8705e279194.O75eDbI7GY6b2GM5NZ3UNTPuXQiIyJ3byBmWotKxvj8+ hash: v1.k794b7964.7f72c65e2acc5eecca4563b9bee90b769f16955589e10770423bb6b48ff01e20.tV1OPipK7ONLU8gH1c3UaqF9hi2ePtbcIgM4-MneppYscenes-app-settings-organization--settings-organization-details--light:- hash: v1.k794b7964.e2ab700c695b4ef335bf697481e23abe8372347cfcfc7f2d5a7c99adea5757b6.p7QZaUK67nHkFLMYCJEGMVpT_LmgA8E4SvjdUPigpUg+ hash: v1.k794b7964.a054f7143276e4629af0c35e69547594a8f6d3d07671661864ce34881870d871.-Kz6S_0INXWjZFU51gT1V541WPloReIokLK2B9-wcmgscenes-app-settings-organization--settings-organization-details-with-member-notice--dark:- hash: v1.k794b7964.8c5fe6988aa5addb020933f5ca4a982f80319d571b18713c09a31371b3b9bfcd.1szW5Vss4AteyRge4UMOG5ml897tQoftP9FmyE9ECTc+ hash: v1.k794b7964.736a88488a5f68ddc39f6ae77e1169d8d5227f87466aa3cc73e768ac31af299c.dc4eXpmGm1AV67QmeI0i0wDffuIKFNBy8RQehb2aUTcscenes-app-settings-organization--settings-organization-details-with-member-notice--light:- hash: v1.k794b7964.c167baba9508e3089ae3f67589950dffe3b87215c9a90be69716ef9ae5b1c241.B-2KlHDDXhevGdch1piUVt5eChxpRoFtqZR_oN7n4gc+ hash: v1.k794b7964.ac520db2d857c7f2b1d1852b8b9808acf773dcd524d3d11f009a4ade08bc6c3f.nM3o_l5gw10VT8Cz2Khw9_zhRWMkeZ2vbmjYGbpZQpMscenes-app-settings-organization--settings-organization-members--dark:hash: v1.k794b7964.59fbd54b1fc509d09ebe1dd12c0b35fc5c6a108bd43ea15558433efcfdca3069.eVLGy89l4vFSN0SwtUjoWF-DM2mCTg1thvM1mIGMHxoscenes-app-settings-organization--settings-organization-members--light:@@ -15543,9 +15559,9 @@ snapshots:scenes-app-settings-project--settings-project-logs-read-only--light:hash: v1.k794b7964.e234f3e555bcb083ca96f00005f91ccccf94941d371c71497162169077ec1022.jNkdKOK2KaEq2T2jksEoVtN5Nupa3FuJLTe-npm0RIMscenes-app-settings-project--settings-project-product-analytics--dark:- hash: v1.k794b7964.55a2942fe5990ba6522fc4a1247be7e2025c8b2cff730931763f75d082ca479c.h271dk04z5sJeX_KS51-X6r--1aWgtaKibQoWKZyWho+ hash: v1.k794b7964.94b2a06b0405b59d4c3f0a182061c9d7f35fe8614485044747d998b2dc01aac3.38mX27k4TM0U-dLHqfmXR3jDB55dmEjfsVMZRLwpUzwscenes-app-settings-project--settings-project-product-analytics--light:- hash: v1.k794b7964.b3e77f33f6e21c42bb1a621cfd531d2c951cd253728dd3655ac9c14b4805ed09.ubyz0IIOOPANbWUssQENGtPOIJB71tchxVw8FqgGIuw+ hash: v1.k794b7964.2cba73fbfff5f57b9d0878dadf66c433a51e605694dea99d95a1516e57bd472d.sg-a0Y2Oe4BNb4xmJncNZZh4Uy4_IZo-nnvPbYx9shMscenes-app-settings-project--settings-project-replay--dark:hash: v1.k794b7964.75a2bd5b932d561b14f51c304c6ffaa20099c8231d70e98a66c42b3db1944c5c.hFKhHnq_0DJCTSK279p74iDSdix-fCrR2AhDTM19ft8scenes-app-settings-project--settings-project-replay--light:diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex 5e62c81b12dc..dc776c13e832 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -102,6 +102,16 @@ export const defaultMocks: Mocks = {'/api/projects/:team_id/my_notifications/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/tasks/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/actions/': EMPTY_PAGINATED_RESPONSE,+ '/api/projects/:team_id/events_retention/': {+ retention_months: null,+ retained_from: null,+ docs_url: 'https://posthog.com/docs/data/events-retention',+ project_retention_months: null,+ organization_retention_months: null,+ plan_retention_months: 84,+ min_retention_months: 1,+ max_retention_months: 84,+ },'/api/projects/:team_id/annotations/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/event_definitions/': EMPTY_PAGINATED_RESPONSE,'/api/projects/:team_id/data_catalog/metrics/': EMPTY_PAGINATED_RESPONSE,@@ -167,6 +177,12 @@ export const defaultMocks: Mocks = {},],'/api/organizations/:organization_id/roles/': EMPTY_PAGINATED_RESPONSE,+ '/api/organizations/:organization_id/events_retention_setting/': {+ organization_retention_months: null,+ plan_retention_months: 84,+ min_retention_months: 1,+ max_retention_months: 84,+ },'/api/organizations/:organization_id/resource_access': EMPTY_PAGINATED_RESPONSE,'/api/organizations/:organization_id/members/': toPaginatedResponse([MOCK_DEFAULT_ORGANIZATION_MEMBER,diff --git a/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx b/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsxindex ad26ddbb8405..f2f55cb137c2 100644--- a/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx+++ b/frontend/src/scenes/dashboard/DashboardRetentionBanner.tsx@@ -2,14 +2,13 @@ import { useActions, useValues } from 'kea'import { LemonBanner } from '@posthog/lemon-ui'-import { urls } from 'scenes/urls'-import { dataRetentionBannerLogic } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'import { dashboardLogic } from './dashboardLogic'export const DashboardRetentionBanner = (): JSX.Element | null => {const { showRetentionBanner, retentionPeriodLabel } = useValues(dashboardLogic)+ const { retentionBannerAction } = useValues(dataRetentionBannerLogic)const { snooze } = useActions(dataRetentionBannerLogic)if (!showRetentionBanner || !retentionPeriodLabel) {@@ -17,12 +16,7 @@ export const DashboardRetentionBanner = (): JSX.Element | null => {}return (- <LemonBanner- type="warning"- className="mt-4 mb-2"- onClose={snooze}- action={{ children: 'Upgrade plan', to: urls.organizationBilling() }}- >+ <LemonBanner type="warning" className="mt-4 mb-2" onClose={snooze} action={retentionBannerAction ?? undefined}>Some insights on this dashboard have date ranges that go beyond your {retentionPeriodLabel} data retention,so events older than that aren't included.</LemonBanner>diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex d077056147b0..72e11d184fb7 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -78,6 +78,8 @@ import { FeatureFlagRequestBlocklist } from 'products/feature_flags/frontend/Feaimport { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlerting/LogsAlertingSection'import { LogsMetricRulesSection } from 'products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection'import { LogsSamplingSection } from 'products/logs/frontend/components/LogsSampling/LogsSamplingSection'+import { OrganizationEventsRetentionSetting } from 'products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting'+import { ProjectEventsRetentionSetting } from 'products/product_analytics/frontend/settings/ProjectEventsRetentionSetting'import { TracingRetentionSettingsBlock } from 'products/tracing/frontend/components/TracingRetention/TracingRetentionSettings'import { HeatmapCaptureSettings } from 'products/web_analytics/frontend/heatmaps/components/HeatmapCaptureSettings'import { HeatmapScreenshotCookieSettings } from 'products/web_analytics/frontend/heatmaps/components/HeatmapScreenshotCookieSettings'@@ -1407,6 +1409,12 @@ export const SETTINGS_MAP: SettingSection[] = [component: <PathCleaningFiltersConfig />,keywords: ['url', 'regex', 'normalize', 'path analysis'],},+ {+ id: 'project-events-retention',+ title: 'Events retention',+ component: <ProjectEventsRetentionSetting />,+ keywords: ['events', 'retention', 'deletion', 'delete', 'months', 'compliance'],+ },{id: 'human-friendly-comparison-periods',title: 'Human friendly comparison periods',@@ -2334,6 +2342,12 @@ export const SETTINGS_MAP: SettingSection[] = [component: <OrgIPAnonymizationDefault />,keywords: ['ip', 'anonymize', 'gdpr', 'privacy', 'geolocation'],},+ {+ id: 'organization-events-retention',+ title: 'Events retention',+ component: <OrganizationEventsRetentionSetting />,+ keywords: ['events', 'retention', 'deletion', 'delete', 'months', 'compliance'],+ },{id: 'organization-member-notice',title: 'Member notice',diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 11fa1ff065be..e5ceef8dabb0 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -245,6 +245,7 @@ export type SettingId =| 'organization-default-role'| 'organization-delete'| 'organization-display-name'+ | 'organization-events-retention'| 'organization-experiment-stats-method'| 'organization-id'| 'organization-integrations-list'@@ -272,6 +273,7 @@ export type SettingId =| 'posthog-mcp-configure'| 'profile-picture'| 'project-delete'+ | 'project-events-retention'| 'project-move'| 'realtime-notifications'| 'replay'diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsxindex b03e9b40c018..5e6e1d08f519 100644--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx@@ -172,7 +172,8 @@ const TEAM_PROPERTIES_MAPPING: Record<| keyof ExperimentsConfig| 'heatmaps_screenshot_allowed_hostnames'| 'conversations_signing_secret'- | 'conversations_signing_secret_previous',+ | 'conversations_signing_secret_previous'+ | 'events_retention_months',(change: ActivityChange) => ChangeMapping | null> = {// API-related tokens@@ -448,6 +449,19 @@ const TEAM_PROPERTIES_MAPPING: Record<return { description: descriptions }},+ // Events retention+ events_retention_months: (change) => ({+ description: [+ change.after === null ? (+ <>removed the project's events retention window</>+ ) : (+ <>+ set the events retention window to <em>{String(change.after)} months</em>+ </>+ ),+ ],+ }),+// Logslogs_settings: () => {return { description: [<>updated logs settings</>] }diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.pyindex a4d99784af4f..a77b084320d7 100644--- a/posthog/dags/tests/test_deletes.py+++ b/posthog/dags/tests/test_deletes.py@@ -702,7 +702,7 @@ def _teams_with_13_and_18_months() -> tuple[Team, Team, Team]:organization = Organization.objects.create(name="Retention")thirteen = Team.objects.create(organization=organization, name="13 months")eighteen = Team.objects.create(organization=organization, name="18 months")- no_retention = Team.objects.create(organization=organization, name="No retention")+ no_retention = Team.objects.create(organization=organization, name="No retention", event_retention_months=12)TeamEventsRetentionConfig.objects.create(team=thirteen, events_retention_months=13)TeamEventsRetentionConfig.objects.create(team=eighteen, events_retention_months=18)return thirteen, eighteen, no_retentiondiff --git a/posthog/models/events_retention_config.py b/posthog/models/events_retention_config.pyindex 940d33b02e20..3b34ee1c6cc6 100644--- a/posthog/models/events_retention_config.py+++ b/posthog/models/events_retention_config.py@@ -1,3 +1,4 @@+from collections.abc import Sequencefrom datetime import datetimefrom uuid import UUID@@ -25,7 +26,7 @@ def _months_field(help_text: str) -> models.PositiveSmallIntegerField:class OrganizationEventsRetentionConfig(models.Model):- """Staff-only events deletion settings for an organization. No customer-facing serializer may write this model."""+ """Events deletion settings for an organization. Staff set the range, and organization admins set the default."""# db_constraint=False: a real FK constraint would take a SHARE ROW EXCLUSIVE# lock on posthog_organization (a hot table) while migrating.@@ -81,7 +82,7 @@ class OrganizationEventsRetentionConfig(models.Model):]def clean(self) -> None:- _lock_organization_retention(self.organization_id)+ lock_organization_retention(self.organization_id)low, default, high = (self.min_events_retention_months,self.default_events_retention_months,@@ -109,7 +110,7 @@ class OrganizationEventsRetentionConfig(models.Model):class TeamEventsRetentionConfig(models.Model):- """Staff-only events deletion setting for a team. No customer-facing serializer may write this model."""+ """Events deletion setting for a team. Organization admins set it within the organization's range."""team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, db_constraint=False)events_retention_months = _months_field(@@ -129,7 +130,7 @@ class TeamEventsRetentionConfig(models.Model):def clean(self) -> None:if self.events_retention_months is None:return- _lock_organization_retention(self.team.organization_id)+ lock_organization_retention(self.team.organization_id)org_config = OrganizationEventsRetentionConfig.objects.filter(organization_id=self.team.organization_id).first()if org_config is None:return@@ -140,7 +141,7 @@ class TeamEventsRetentionConfig(models.Model):)-def _lock_organization_retention(organization_id: object) -> None:+def lock_organization_retention(organization_id: object) -> None:# Django admin validates and saves a change form in one transaction, so this lock holds until the# save commits. A team value check and its organization's range check then cannot both read# stale values and pass. The lock key is the organization, not its hot posthog_organization row.@@ -172,11 +173,12 @@ class TeamEventsRetention:months: int-def effective_events_retention() -> list[TeamEventsRetention]:+def effective_events_retention(team_ids: Sequence[int] | None = None) -> list[TeamEventsRetention]:"""Every team with an effective events retention: its own value, else its organization's default."""team_table = Team._meta.db_tableteam_config_table = TeamEventsRetentionConfig._meta.db_tableorg_config_table = OrganizationEventsRetentionConfig._meta.db_table+ team_filter = "AND team.id = ANY(%s)" if team_ids is not None else ""with connection.cursor() as cursor:cursor.execute(f"""@@ -187,8 +189,10 @@ def effective_events_retention() -> list[TeamEventsRetention]:LEFT JOIN {team_config_table} AS team_config ON team_config.team_id = team.idLEFT JOIN {org_config_table} AS org_config ON org_config.organization_id = team.organization_idWHERE COALESCE(team_config.events_retention_months, org_config.default_events_retention_months) IS NOT NULL+ {team_filter}ORDER BY team.organization_id, team.id- """+ """,+ [list(team_ids)] if team_ids is not None else [],)return [TeamEventsRetention(organization_id=organization_id, team_id=team_id, months=months)diff --git a/posthog/models/team/event_retention.py b/posthog/models/team/event_retention.pyindex 7a0c347e0e5e..5fd24888aaea 100644--- a/posthog/models/team/event_retention.py+++ b/posthog/models/team/event_retention.py@@ -9,6 +9,7 @@ from dateutil.relativedelta import relativedeltafrom posthog.cloud_utils import is_cloudfrom posthog.constants import AvailableFeature+from posthog.models.events_retention_config import effective_events_retentionfrom posthog.models.organization import ProductFeaturefrom posthog.models.team.team import Team@@ -51,9 +52,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.- 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 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."""if team_id is None:if team is None:@@ -68,7 +69,23 @@ def events_retention_months_for_team(team: Optional[Team], team_id: Optional[intif team is None:return None- return team.event_retention_months or DEFAULT_EVENT_RETENTION_MONTHS+ 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+++_REQUEST_CACHED_CONFIGURED_RETENTION_ATTR = "_request_cached_configured_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.++ 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)def events_retention_floor_date(team: Team, retention_months: int) -> date:diff --git a/posthog/models/team/test/test_event_retention.py b/posthog/models/team/test/test_event_retention.pyindex 600a098f422a..7d48a8bebac9 100644--- a/posthog/models/team/test/test_event_retention.py+++ b/posthog/models/team/test/test_event_retention.py@@ -3,12 +3,18 @@ from typing import castfrom posthog.test.base import BaseTest+from django.test import override_settingsfrom django.utils import timezonefrom parameterized import parameterized+from posthog.models.events_retention_config import TeamEventsRetentionConfigfrom 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.event_retention import (+ events_retention_months_for_team,+ parse_events_feature_to_months,+ reconcile_organization_events_retention,+)from posthog.models.team.team import Team@@ -75,3 +81,25 @@ class TestReconcileOrganizationEventsRetention(BaseTest):self.team.refresh_from_db()assert self.team.event_retention_months == 12+++@override_settings(EVENTS_DATA_RETENTION_ENFORCED=True)+class TestEventsRetentionMonthsForTeam(BaseTest):+ @parameterized.expand(+ [+ ("plan_window_only", None, 24),+ ("shorter_set_window", 12, 12),+ ("set_window_longer_than_a_downgraded_plan", 36, 24),+ ]+ )+ def test_takes_the_shorter_of_the_plan_and_the_set_window(+ self, _name: str, set_months: int | None, expected: int+ ) -> None:+ self.team.event_retention_months = 24+ self.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(0):+ assert events_retention_months_for_team(self.team, self.team.id) == expecteddiff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 594686bb86b7..ec1078394677 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -221,6 +221,8 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.notebooks.backend.presentation.views.reusable_widget.ReusableWidgetViewSet","products.notifications.backend.presentation.views.NotificationsViewSet","products.product_analytics.backend.presentation.events_retention.EventsRetentionViewSet",+ # Returns the organization's one retention setting, not a page of rows.+ "products.product_analytics.backend.presentation.events_retention.OrganizationEventsRetentionViewSet","products.product_analytics.backend.presentation.insight.InsightViewSet","products.product_tours.backend.api.product_tour.ProductTourViewSet","products.replay_vision.backend.api.observations.ReplayObservationViewSet",diff --git a/products/product_analytics/backend/events_retention.py b/products/product_analytics/backend/events_retention.pynew file mode 100644index 000000000000..ae7993113860--- /dev/null+++ b/products/product_analytics/backend/events_retention.py@@ -0,0 +1,111 @@+from django.core.exceptions import ValidationError+from django.db import transaction++from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.events_retention_config import (+ OrganizationEventsRetentionConfig,+ TeamEventsRetentionConfig,+ describe_months_range,+ lock_organization_retention,+)+from posthog.models.organization import Organization+from posthog.models.team import Team+from posthog.models.team.event_retention import organization_events_retention_months+from posthog.models.user import User++from products.product_analytics.backend.facade.contracts import OrganizationEventsRetention+++def organization_events_retention(organization: Organization) -> OrganizationEventsRetention:+ config = OrganizationEventsRetentionConfig.objects.filter(organization_id=organization.id).first()+ plan_months = organization_events_retention_months(organization)+ staff_max = config.max_events_retention_months if config else None+ return OrganizationEventsRetention(+ organization_months=config.default_events_retention_months if config else None,+ plan_months=plan_months,+ min_months=(config.min_events_retention_months if config else None) or 1,+ max_months=min(plan_months, staff_max) if staff_max else plan_months,+ )+++def project_events_retention_months(team: Team) -> int | None:+ return (+ TeamEventsRetentionConfig.objects.filter(team_id=team.id)+ .values_list("events_retention_months", flat=True)+ .first()+ )+++def _check_allowed(retention: OrganizationEventsRetention, months: int | None) -> None:+ if months is not None and 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)}."+ )+++def set_organization_events_retention(+ organization: Organization, months: int | None, *, user: User, was_impersonated: bool+) -> None:+ with transaction.atomic():+ # Lock before reading, because save() writes the staff range too and must not write back a stale one.+ lock_organization_retention(organization.id)+ config = OrganizationEventsRetentionConfig.objects.filter(organization_id=organization.id).first()+ before = config.default_events_retention_months if config else None+ if months == before:+ return+ _check_allowed(organization_events_retention(organization), months)+ config = config or OrganizationEventsRetentionConfig(organization_id=organization.id)+ config.default_events_retention_months = months+ config.full_clean()+ if months is None and config.min_events_retention_months is None and config.max_events_retention_months is None:+ config.delete()+ else:+ config.save()++ log_activity(+ organization_id=organization.id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ scope="Organization",+ item_id=str(organization.id),+ activity="updated",+ detail=Detail(+ name=organization.name,+ changes=[+ Change(type="Organization", action="changed", field="events retention", before=before, after=months)+ ],+ ),+ )+++def set_project_events_retention(team: Team, months: int | None, *, user: User, was_impersonated: bool) -> None:+ with transaction.atomic():+ config = TeamEventsRetentionConfig.objects.filter(team_id=team.id).first()+ before = config.events_retention_months if config else None+ if months == before:+ return+ _check_allowed(organization_events_retention(team.organization), months)+ if months is None:+ TeamEventsRetentionConfig.objects.filter(team_id=team.id).delete()+ else:+ config = config or TeamEventsRetentionConfig(team=team)+ config.events_retention_months = months+ config.full_clean()+ config.save()++ log_activity(+ organization_id=team.organization_id,+ team_id=team.id,+ user=user,+ was_impersonated=was_impersonated,+ scope="Team",+ item_id=team.id,+ activity="updated",+ detail=Detail(+ name=team.name,+ changes=[+ Change(type="Team", action="changed", field="events_retention_months", before=before, after=months)+ ],+ ),+ )diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex a9bb0078780e..82977a4c7e9a 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -182,3 +182,13 @@ class InsightDashboardContext:filters: dict[str, Any]tile_filters: dict[str, Any] | None = Nonevariables: dict[str, Any] | None = None+++@dataclass(frozen=True)+class OrganizationEventsRetention:+ """The window an organization set for its projects, and the windows its admins can set, in months."""++ organization_months: int | None+ plan_months: int+ min_months: int+ max_months: intdiff --git a/products/product_analytics/backend/facade/events_retention.py b/products/product_analytics/backend/facade/events_retention.pynew file mode 100644index 000000000000..ebf42e79047f--- /dev/null+++ b/products/product_analytics/backend/facade/events_retention.py@@ -0,0 +1,36 @@+"""+Events retention settings for organizations and projects.++The windows set here are the ones the monthly events cleanup deletes by, so a saved window deletes events.+"""++from posthog.models.organization import Organization+from posthog.models.team import Team+from posthog.models.user import User++from products.product_analytics.backend import events_retention+from products.product_analytics.backend.facade.contracts import OrganizationEventsRetention+++def organization_events_retention(organization: Organization) -> OrganizationEventsRetention:+ """The organization's window and the range its admins can set."""+ return events_retention.organization_events_retention(organization)+++def project_events_retention_months(team: Team) -> int | None:+ """The window set for this project, or None while it uses the organization's window."""+ return events_retention.project_events_retention_months(team)+++def set_organization_events_retention(+ organization: Organization, months: int | None, *, user: User, was_impersonated: bool+) -> None:+ """Set or clear the organization's window. Raises a Django ValidationError for a window outside the range."""+ events_retention.set_organization_events_retention(+ organization, months, user=user, was_impersonated=was_impersonated+ )+++def set_project_events_retention(team: Team, months: int | None, *, user: User, was_impersonated: bool) -> None:+ """Set or clear the project's window. Raises a Django ValidationError for a window outside the range."""+ events_retention.set_project_events_retention(team, months, user=user, was_impersonated=was_impersonated)diff --git a/products/product_analytics/backend/presentation/events_retention.py b/products/product_analytics/backend/presentation/events_retention.pyindex cc01d46d83d1..f61338900698 100644--- a/products/product_analytics/backend/presentation/events_retention.py+++ b/products/product_analytics/backend/presentation/events_retention.py@@ -1,18 +1,52 @@-from typing import Any+from typing import Any, cast-from drf_spectacular.utils import extend_schema, extend_schema_serializer-from rest_framework import serializers, viewsets+from django.core.exceptions import ValidationError as DjangoValidationError++from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_serializer+from rest_framework import exceptions, serializers, viewsetsfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.helpers.impersonation import is_impersonatedfrom posthog.models.team.event_retention import events_retention_floor_date, events_retention_months_for_team+from posthog.models.user import User+from posthog.permissions import OrganizationAdminWritePermissions++from products.product_analytics.backend.facade.events_retention import (+ organization_events_retention,+ project_events_retention_months,+ set_organization_events_retention,+ set_project_events_retention,+)EVENTS_RETENTION_DOCS_URL = "https://posthog.com/docs/data/events-retention"@extend_schema_serializer(many=False)-class EventsRetentionSerializer(serializers.Serializer):+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.",+ )+ plan_retention_months = serializers.IntegerField(+ read_only=True,+ help_text="The longest window the organization's plan allows, in months.",+ )+ min_retention_months = serializers.IntegerField(+ read_only=True,+ help_text="The shortest window an admin can set, in months.",+ )+ max_retention_months = serializers.IntegerField(+ read_only=True,+ help_text="The longest window an admin can set, in months. Never longer than the plan's window.",+ )+++@extend_schema_serializer(many=False)+class EventsRetentionSerializer(OrganizationEventsRetentionSerializer):retention_months = serializers.IntegerField(read_only=True,allow_null=True,@@ -27,34 +61,143 @@ class EventsRetentionSerializer(serializers.Serializer):read_only=True,help_text="Where the events retention policy is documented.",)+ project_retention_months = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="The window, in months, set for this project. Null while the project uses the organization's window.",+ )+++class EventsRetentionUpdateSerializer(serializers.Serializer):+ retention_months = serializers.IntegerField(+ allow_null=True,+ min_value=1,+ help_text="The window in months. Events older than this are deleted on the next monthly cleanup and can't be restored. Null removes the window.",+ )@extend_schema(tags=["events_retention"])class EventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "project"pagination_class = None+ permission_classes = [OrganizationAdminWritePermissions]++ def _retention_response(self) -> Response:+ retention_months = events_retention_months_for_team(self.team, self.team_id)+ 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(+ {+ "retention_months": retention_months,+ "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,+ }+ ).data+ )@extend_schema(operation_id="events_retention_retrieve",summary="Get the events retention window for a project",description=(- "Returns how far back events stay queryable for this project. The window comes from the "- "organization's plan and is read-only. Both window fields are null while no retention window "+ "Returns how far back events stay queryable for this project, the windows set for the project and its "+ "organization, and the range an admin can set. Both window fields are null while no retention window ""applies to the project."),responses={200: EventsRetentionSerializer},)def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:- retention_months = events_retention_months_for_team(self.team, self.team_id)- retained_from = (- events_retention_floor_date(self.team, retention_months) if retention_months is not None else None- )+ return self._retention_response()++ @validated_request(+ EventsRetentionUpdateSerializer,+ operation_id="events_retention_update",+ summary="Set the events retention window for a project",+ description=(+ "Sets how long this project keeps events, overriding the organization's window. Events older than the "+ "window are deleted on the next monthly cleanup and can't be restored. Organization admins only."+ ),+ responses={+ 200: OpenApiResponse(response=EventsRetentionSerializer, description="The project's new window."),+ 400: OpenApiResponse(description="The window is outside the range an admin can set."),+ 403: OpenApiResponse(description="The user isn't an organization admin."),+ },+ )+ def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ try:+ set_project_events_retention(+ self.team,+ request.validated_data["retention_months"],+ user=cast(User, request.user),+ was_impersonated=is_impersonated(request),+ )+ except DjangoValidationError as error:+ raise exceptions.ValidationError(error.messages) from error+ return self._retention_response()+++@extend_schema(tags=["events_retention"])+class OrganizationEventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):+ scope_object = "organization"+ pagination_class = None+ permission_classes = [OrganizationAdminWritePermissions]++ def _retention_response(self) -> Response:+ organization = organization_events_retention(self.organization)return Response(- EventsRetentionSerializer(+ OrganizationEventsRetentionSerializer({- "retention_months": retention_months,- "retained_from": retained_from,- "docs_url": EVENTS_RETENTION_DOCS_URL,+ "organization_retention_months": organization.organization_months,+ "plan_retention_months": organization.plan_months,+ "min_retention_months": organization.min_months,+ "max_retention_months": organization.max_months,}).data)++ @extend_schema(+ operation_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."+ ),+ responses={200: OrganizationEventsRetentionSerializer},+ )+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._retention_response()++ @validated_request(+ EventsRetentionUpdateSerializer,+ operation_id="organization_events_retention_update",+ summary="Set the organization's events retention window",+ description=(+ "Sets how long every project without its own window keeps events. Events older than the window are "+ "deleted on the next monthly cleanup and can't be restored. Organization admins only."+ ),+ responses={+ 200: OpenApiResponse(+ response=OrganizationEventsRetentionSerializer, description="The organization's new window."+ ),+ 400: OpenApiResponse(description="The window is outside the range an admin can set."),+ 403: OpenApiResponse(description="The user isn't an organization admin."),+ },+ )+ def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ try:+ set_organization_events_retention(+ self.organization,+ request.validated_data["retention_months"],+ user=cast(User, request.user),+ was_impersonated=is_impersonated(request),+ )+ except DjangoValidationError as error:+ raise exceptions.ValidationError(error.messages) from error+ return self._retention_response()diff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.pyindex 0a706162a987..679af2fa8c50 100644--- a/products/product_analytics/backend/routes.py+++ b/products/product_analytics/backend/routes.py@@ -2,7 +2,10 @@ from posthog.api import sharingfrom posthog.api.routing import RouterRegistryimport products.alerts.backend.presentation.views.alert as alert-from products.product_analytics.backend.presentation.events_retention import EventsRetentionViewSet+from products.product_analytics.backend.presentation.events_retention import (+ EventsRetentionViewSet,+ OrganizationEventsRetentionViewSet,+)from products.product_analytics.backend.presentation.insight import InsightViewSetfrom products.product_analytics.backend.presentation.insight_variable import InsightVariableViewSetfrom products.product_analytics.backend.presentation.paths_v2 import PathsV2ViewSet@@ -48,3 +51,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_events_retention",["team_id"],)++ # Not "events_retention": the schema generator marks an organization path that repeats a project path as a+ # deprecated duplicate and leaves it out of the generated client.+ routers.organizations.register(+ r"events_retention_setting",+ OrganizationEventsRetentionViewSet,+ "organization_events_retention_setting",+ ["organization_id"],+ )diff --git a/products/product_analytics/backend/tests/api/test_events_retention.py b/products/product_analytics/backend/tests/api/test_events_retention.pyindex 95f5486d4f3c..7774ec6f17b8 100644--- a/products/product_analytics/backend/tests/api/test_events_retention.py+++ b/products/product_analytics/backend/tests/api/test_events_retention.py@@ -6,12 +6,49 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.models import Organization+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig+from posthog.models.organization import OrganizationMembership++from products.access_control.backend.facade.testing import create_access_control+@override_settings(EVENTS_DATA_RETENTION_ENFORCED=True)class TestEventsRetentionAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self._set_plan_years(2)+ self.team.event_retention_months = 24+ self.team.save()+def url(self) -> str:return f"/api/projects/{self.team.id}/events_retention/"+ def organization_url(self) -> str:+ return f"/api/organizations/{self.organization.id}/events_retention_setting/"++ def _set_plan_years(self, years: int) -> None:+ 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"},+ ]+ )++ def _set_membership(self, level: str) -> None:+ if level == "organization_admin":+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ else:+ create_access_control(+ team_id=self.team.id,+ resource="project",+ resource_id=str(self.team.id),+ access_level="admin",+ organization_member_id=self.organization_membership.id,+ )+@parameterized.expand([("utc", "UTC", "2025-09-22"),@@ -20,6 +57,7 @@ class TestEventsRetentionAPI(APIBaseTest):)@time_machine.travel("2026-09-22T23:30:00Z", tick=False)def test_reports_the_window_in_the_project_timezone(self, _name: str, tz: str, retained_from: str) -> None:+ self._set_plan_years(1)self.team.timezone = tzself.team.event_retention_months = 12self.team.save()@@ -31,21 +69,121 @@ class TestEventsRetentionAPI(APIBaseTest):"retention_months": 12,"retained_from": retained_from,"docs_url": "https://posthog.com/docs/data/events-retention",+ "project_retention_months": None,+ "organization_retention_months": None,+ "plan_retention_months": 12,+ "min_retention_months": 1,+ "max_retention_months": 12,}@override_settings(EVENTS_DATA_RETENTION_ENFORCED=False)def test_reports_no_window_until_retention_is_enforced(self) -> None:response = self.client.get(self.url())+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["retention_months"] is None+ assert response.json()["retained_from"] is None++ def test_organization_admin_sets_and_clears_the_project_window(self) -> None:+ self._set_membership("organization_admin")+ OrganizationEventsRetentionConfig.objects.create(+ organization=self.organization, default_events_retention_months=12+ )++ response = self.client.post(self.url(), {"retention_months": 6}, format="json")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["retention_months"] == 6+ assert response.json()["project_retention_months"] == 6+ assert ActivityLog.objects.filter(team_id=self.team.id, scope="Team", activity="updated").exists()++ response = self.client.post(self.url(), {"retention_months": None}, format="json")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["retention_months"] == 12+ assert response.json()["project_retention_months"] is None+ assert not TeamEventsRetentionConfig.objects.filter(team=self.team).exists()++ @parameterized.expand(+ [+ ("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),+ ]+ )+ def test_rejects_a_project_window(self, _name: str, level: str, months: int, expected_status: int) -> None:+ self._set_membership(level)+ OrganizationEventsRetentionConfig.objects.create(organization=self.organization, min_events_retention_months=6)++ response = self.client.post(self.url(), {"retention_months": months}, format="json")++ assert response.status_code == expected_status+ assert not TeamEventsRetentionConfig.objects.filter(team=self.team).exists()++ def test_organization_admin_sets_and_clears_the_default_window(self) -> None:+ self._set_membership("organization_admin")++ response = self.client.post(self.organization_url(), {"retention_months": 12}, format="json")+assert response.status_code == status.HTTP_200_OKassert response.json() == {- "retention_months": None,- "retained_from": None,- "docs_url": "https://posthog.com/docs/data/events-retention",+ "organization_retention_months": 12,+ "plan_retention_months": 24,+ "min_retention_months": 1,+ "max_retention_months": 24,}+ assert self.client.get(self.url()).json()["retention_months"] == 12+ assert ActivityLog.objects.filter(+ organization_id=self.organization.id, scope="Organization", activity="updated"+ ).exists()++ response = self.client.post(self.organization_url(), {"retention_months": None}, format="json")++ assert response.status_code == status.HTTP_200_OK+ assert self.client.get(self.url()).json()["retention_months"] == 24+ assert not OrganizationEventsRetentionConfig.objects.filter(organization=self.organization).exists()++ @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),+ ]+ )+ def test_rejects_an_organization_window(self, _name: str, level: str, months: int, expected_status: int) -> None:+ self._set_membership(level)+ OrganizationEventsRetentionConfig.objects.create(organization=self.organization, max_events_retention_months=12)++ response = self.client.post(self.organization_url(), {"retention_months": months}, format="json")++ assert response.status_code == expected_status+ assert (+ OrganizationEventsRetentionConfig.objects.get(+ organization=self.organization+ ).default_events_retention_months+ is None+ )++ @override_settings(EVENTS_DATA_RETENTION_ENFORCED=False)+ def test_accepts_windows_before_retention_is_enforced(self) -> None:+ self._set_membership("organization_admin")++ for url in (self.url(), self.organization_url()):+ response = self.client.post(url, {"retention_months": 12}, format="json")++ assert response.status_code == status.HTTP_200_OK+ assert (+ OrganizationEventsRetentionConfig.objects.get(+ organization=self.organization+ ).default_events_retention_months+ == 12+ )+ assert TeamEventsRetentionConfig.objects.get(team=self.team).events_retention_months == 12++ @parameterized.expand([("patch",), ("put",), ("delete",)])+ def test_rejects_other_writes(self, method: str) -> None:+ self._set_membership("organization_admin")- @parameterized.expand([("patch",), ("put",), ("post",), ("delete",)])- def test_rejects_writes(self, method: str) -> None:- response = getattr(self.client, method)(self.url(), {"retention_months": 1})+ for url in (self.url(), self.organization_url()):+ response = getattr(self.client, method)(url, {"retention_months": 1})- assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWEDdiff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 906649249cce..c83fa87d707d 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7,6 +7,29 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+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.+ * @nullable+ */+ readonly organization_retention_months: number | null+ /** The longest window the organization's plan allows, in months. */+ readonly plan_retention_months: number+ /** The shortest window an admin can set, in months. */+ readonly min_retention_months: number+ /** The longest window an admin can set, in months. Never longer than the plan's window. */+ readonly max_retention_months: number+}++export interface EventsRetentionUpdateApi {+ /**+ * The window in months. Events older than this are deleted on the next monthly cleanup and can't be restored. Null removes the window.+ * @minimum 1+ * @nullable+ */+ retention_months: number | null+}+/*** * `private` - Private (only visible to creator)* * `shared` - Shared with team@@ -212,6 +235,17 @@ 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.+ * @nullable+ */+ readonly organization_retention_months: number | null+ /** The longest window the organization's plan allows, in months. */+ readonly plan_retention_months: number+ /** The shortest window an admin can set, in months. */+ readonly min_retention_months: number+ /** The longest window an admin can set, in months. Never longer than the plan's window. */+ readonly max_retention_months: number/*** How many months of events stay queryable, counted back from today. Null while no retention window applies to the project.* @nullable@@ -224,6 +258,11 @@ export interface EventsRetentionApi {readonly retained_from: string | null/** Where the events retention policy is documented. */readonly docs_url: string+ /**+ * The window, in months, set for this project. Null while the project uses the organization's window.+ * @nullable+ */+ readonly project_retention_months: number | null}export type InsightVizNodeApiKind = (typeof InsightVizNodeApiKind)[keyof typeof InsightVizNodeApiKind]diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.tsindex 7f83cdbb36e7..4c5ef0be3fec 100644--- a/products/product_analytics/frontend/generated/api.ts+++ b/products/product_analytics/frontend/generated/api.ts@@ -21,6 +21,7 @@ import type {ElementsStatsRetrieveParams,ElementsValuesListParams,EventsRetentionApi,+ EventsRetentionUpdateApi,InsightApi,InsightBulkDeleteRequestApi,InsightBulkDeleteResponseApi,@@ -49,6 +50,7 @@ import type {InsightsTrendingRetrieveParams,InsightsUpdateParams,InsightsViewedCreateParams,+ OrganizationEventsRetentionApi,PaginatedColumnConfigurationListApi,PaginatedElementListApi,PaginatedInsightListApi,@@ -77,6 +79,45 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getOrganizationEventsRetentionRetrieveUrl = (organizationId: string) => {+ return `/api/organizations/${organizationId}/events_retention_setting/`+}++/**+ * Returns the events retention window that every project without its own window uses, and the range an organization admin can set.+ * @summary Get the organization's events retention window+ */+export const organizationEventsRetentionRetrieve = async (+ organizationId: string,+ options?: RequestInit+): Promise<OrganizationEventsRetentionApi> => {+ return apiMutator<OrganizationEventsRetentionApi>(getOrganizationEventsRetentionRetrieveUrl(organizationId), {+ ...options,+ method: 'GET',+ })+}++export const getOrganizationEventsRetentionUpdateUrl = (organizationId: string) => {+ return `/api/organizations/${organizationId}/events_retention_setting/`+}++/**+ * Sets how long every project without its own window keeps events. Events older than the window are deleted on the next monthly cleanup and can't be restored. Organization admins only.+ * @summary Set the organization's events retention window+ */+export const organizationEventsRetentionUpdate = async (+ organizationId: string,+ eventsRetentionUpdateApi: EventsRetentionUpdateApi,+ options?: RequestInit+): Promise<OrganizationEventsRetentionApi> => {+ return apiMutator<OrganizationEventsRetentionApi>(getOrganizationEventsRetentionUpdateUrl(organizationId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventsRetentionUpdateApi),+ })+}+export const getColumnConfigurationsListUrl = (projectId: string, params?: ColumnConfigurationsListParams) => {const normalizedParams = new URLSearchParams()@@ -353,7 +394,7 @@ export const getEventsRetentionRetrieveUrl = (projectId: string) => {}/**- * Returns how far back events stay queryable for this project. The window comes from the organization's plan and is read-only. Both window fields are null while no retention window applies to the project.+ * Returns how far back events stay queryable for this project, the windows set for the project and its organization, and the range an admin can set. Both window fields are null while no retention window applies to the project.* @summary Get the events retention window for a project*/export const eventsRetentionRetrieve = async (@@ -366,6 +407,27 @@ export const eventsRetentionRetrieve = async (})}+export const getEventsRetentionUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/events_retention/`+}++/**+ * Sets how long this project keeps events, overriding the organization's window. Events older than the window are deleted on the next monthly cleanup and can't be restored. Organization admins only.+ * @summary Set the events retention window for a project+ */+export const eventsRetentionUpdate = async (+ projectId: string,+ eventsRetentionUpdateApi: EventsRetentionUpdateApi,+ options?: RequestInit+): Promise<EventsRetentionApi> => {+ return apiMutator<EventsRetentionApi>(getEventsRetentionUpdateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(eventsRetentionUpdateApi),+ })+}+export const getInsightsListUrl = (projectId: string, params?: InsightsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.tsindex d3af5a5bcb33..c8e1417efcd7 100644--- a/products/product_analytics/frontend/generated/api.zod.ts+++ b/products/product_analytics/frontend/generated/api.zod.ts@@ -9,6 +9,21 @@*/import * as zod from 'zod'+/**+ * Sets how long every project without its own window keeps events. Events older than the window are deleted on the next monthly cleanup and can't be restored. Organization admins only.+ * @summary Set the organization's events retention window+ */++export const OrganizationEventsRetentionUpdateBody = /* @__PURE__ */ zod.object({+ retention_months: zod+ .number()+ .min(1)+ .nullable()+ .describe(+ "The window in months. Events older than this are deleted on the next monthly cleanup and can't be restored. Null removes the window."+ ),+})+export const columnConfigurationsCreateBodyContextKeyMax = 255export const columnConfigurationsCreateBodyNameMax = 255@@ -191,6 +206,21 @@ export const ElementsPartialUpdateBody = /* @__PURE__ */ zod.object({order: zod.number().min(elementsPartialUpdateBodyOrderMin).max(elementsPartialUpdateBodyOrderMax).nullish(),})+/**+ * Sets how long this project keeps events, overriding the organization's window. Events older than the window are deleted on the next monthly cleanup and can't be restored. Organization admins only.+ * @summary Set the events retention window for a project+ */++export const EventsRetentionUpdateBody = /* @__PURE__ */ zod.object({+ retention_months: zod+ .number()+ .min(1)+ .nullable()+ .describe(+ "The window in months. Events older than this are deleted on the next monthly cleanup and can't be restored. Null removes the window."+ ),+})+export const InsightsCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')diff --git a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.tsindex defa62aefade..d13428646fcc 100644--- a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts+++ b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.test.ts@@ -14,6 +14,11 @@ const RETENTION = {retention_months: 84,retained_from: '2019-09-22',docs_url: 'https://posthog.com/docs/data/events-retention',+ project_retention_months: null,+ organization_retention_months: null,+ plan_retention_months: 84,+ min_retention_months: 1,+ max_retention_months: 84,}describe('dataRetentionBannerLogic', () => {@@ -22,18 +27,33 @@ describe('dataRetentionBannerLogic', () => {name: 'reads the window from the events retention endpoint',response: [200, RETENTION],retentionMonths: 84,+ actionLabel: null,+ },+ {+ name: 'offers an upgrade below the longest plan',+ response: [200, { ...RETENTION, retention_months: 12, plan_retention_months: 12 }],+ retentionMonths: 12,+ actionLabel: 'Upgrade plan',+ },+ {+ name: 'links to settings when a setting shortens the window',+ response: [200, { ...RETENTION, retention_months: 12, organization_retention_months: 12 }],+ retentionMonths: 12,+ actionLabel: 'Change retention',},{name: 'treats a null window as retention not enforced',response: [200, { ...RETENTION, retention_months: null, retained_from: null }],retentionMonths: null,+ actionLabel: null,},{name: 'treats an empty response as retention not enforced',response: [204],retentionMonths: null,+ actionLabel: null,},- ])('$name', async ({ response, retentionMonths }) => {+ ])('$name', async ({ response, retentionMonths, actionLabel }) => {useMocks({ get: { '/api/projects/:team_id/events_retention/': () => response } })initKeaTests()const logic = dataRetentionBannerLogic()@@ -42,6 +62,7 @@ describe('dataRetentionBannerLogic', () => {await expectLogic(logic).toDispatchActions(['loadRetentionMonths', 'loadRetentionMonthsSuccess']).toMatchValues({ retentionMonths, retentionEnforced: retentionMonths !== null })+ expect(logic.values.retentionBannerAction?.children ?? null).toEqual(actionLabel)})it('waits for the team id before loading', async () => {diff --git a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.tsindex 4d6dc3d46021..7f95de0f1298 100644--- a/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts+++ b/products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic.ts@@ -4,11 +4,21 @@ import { loaders } from 'kea-loaders'import { dayjs } from 'lib/dayjs'import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'import { isSharedView } from '~/exporter/exporterViewLogic'import type { OrganizationType } from '~/types'import { eventsRetentionRetrieve } from 'products/product_analytics/frontend/generated/api'+import type { EventsRetentionApi } from 'products/product_analytics/frontend/generated/api.schemas'++export interface RetentionBannerAction {+ children: string+ to: string+}++// The longest window any plan offers, so there's nothing to upgrade to past it.+export const LONGEST_PLAN_RETENTION_MONTHS = 84const SNOOZE_DAYS = 30// Don't nag accounts that can't yet have at-risk data: only warn once the account is within 90 days of its@@ -31,10 +41,12 @@ export interface dataRetentionBannerLogicValues {currentTeamId: number | null // teamLogicaccountAgeEligible: booleanisSnoozed: boolean+ retention: EventsRetentionApi | nullretentionApplies: boolean+ retentionBannerAction: RetentionBannerAction | nullretentionEnforced: boolean+ retentionLoading: booleanretentionMonths: number | null- retentionMonthsLoading: booleanretentionPeriodLabel: string | nullsnoozedUntil: string | nullwarningEligible: boolean@@ -51,10 +63,10 @@ export interface dataRetentionBannerLogicActions {errorObject?: any}loadRetentionMonthsSuccess: (- retentionMonths: number | null,+ retention: EventsRetentionApi | null,payload?: any) => {- retentionMonths: number | null+ retention: EventsRetentionApi | nullpayload?: any}snooze: () => {@@ -65,6 +77,8 @@ export interface dataRetentionBannerLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface dataRetentionBannerLogicMeta {__keaTypeGenInternalSelectorTypes: {+ retentionMonths: (retention: EventsRetentionApi | null) => number | null+ retentionBannerAction: (retention: EventsRetentionApi | null) => RetentionBannerAction | nullretentionEnforced: (retentionMonths: number | null) => booleanretentionPeriodLabel: (retentionMonths: number | null) => string | nullisSnoozed: (snoozedUntil: string | null) => boolean@@ -93,15 +107,14 @@ export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([snooze: true,}),loaders(({ values }) => ({- retentionMonths: [- null as number | null,+ retention: [+ null as EventsRetentionApi | null,{loadRetentionMonths: async () => {if (values.currentTeamId === null || isSharedView()) {return null}- const retention = await eventsRetentionRetrieve(String(values.currentTeamId))- return retention?.retention_months ?? null+ return (await eventsRetentionRetrieve(String(values.currentTeamId))) || null},},],@@ -116,6 +129,28 @@ export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([],}),selectors({+ retentionMonths: [+ (s) => [s.retention],+ (retention: EventsRetentionApi | null): number | null => retention?.retention_months ?? null,+ ],+ // Upgrading doesn't help when someone set a window shorter than the plan's, or when the plan is the longest.+ retentionBannerAction: [+ (s) => [s.retention],+ (retention: EventsRetentionApi | null): RetentionBannerAction | null => {+ if (retention?.retention_months == null) {+ return null+ }+ if (retention.retention_months < retention.plan_retention_months) {+ return {+ children: 'Change retention',+ to: urls.settings('environment-product-analytics', 'project-events-retention'),+ }+ }+ return retention.plan_retention_months < LONGEST_PLAN_RETENTION_MONTHS+ ? { children: 'Upgrade plan', to: urls.organizationBilling() }+ : null+ },+ ],retentionEnforced: [(s) => [s.retentionMonths],(retentionMonths: number | null): boolean => retentionMonths !== null,diff --git a/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx b/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsxindex 29995fe3da46..df89a5322f2e 100644--- a/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx+++ b/products/product_analytics/frontend/insights/insightScene/banners/InsightRetentionBanner.tsx@@ -1,7 +1,6 @@import { useActions, useValues } from 'kea'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'-import { urls } from 'scenes/urls'import { InsightLogicProps } from '~/types'@@ -11,7 +10,7 @@ import { insightRetentionBannerLogic } from './insightRetentionBannerLogic'export function InsightRetentionBanner({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element | null {const { shouldShowBanner } = useValues(insightRetentionBannerLogic(insightProps))- const { retentionPeriodLabel } = useValues(dataRetentionBannerLogic)+ const { retentionPeriodLabel, retentionBannerAction } = useValues(dataRetentionBannerLogic)const { snooze } = useActions(dataRetentionBannerLogic)if (!shouldShowBanner || !retentionPeriodLabel) {@@ -19,11 +18,7 @@ export function InsightRetentionBanner({ insightProps }: { insightProps: Insight}return (- <LemonBanner- type="warning"- onClose={snooze}- action={{ children: 'Upgrade plan', to: urls.organizationBilling() }}- >+ <LemonBanner type="warning" onClose={snooze} action={retentionBannerAction ?? undefined}>This insight's date range goes beyond your {retentionPeriodLabel} data retention, so events older than thataren't included.</LemonBanner>diff --git a/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsxnew file mode 100644index 000000000000..b55b1b2b4445--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionSettings.stories.tsx@@ -0,0 +1,65 @@+import { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import type {+ EventsRetentionApi,+ OrganizationEventsRetentionApi,+} from 'products/product_analytics/frontend/generated/api.schemas'++import { OrganizationEventsRetentionSetting } from './OrganizationEventsRetentionSetting'+import { ProjectEventsRetentionSetting } from './ProjectEventsRetentionSetting'++const meta: Meta = {+ title: 'Scenes-App/Settings/Events Retention',+ parameters: {+ mockDate: '2026-11-01',+ },+}+export default meta+type Story = StoryObj++const retentionMocks = (+ organizationMonths: number | null,+ projectMonths: number | null+): ReturnType<typeof mswDecorator> => {+ const organization: OrganizationEventsRetentionApi = {+ organization_retention_months: organizationMonths,+ plan_retention_months: 36,+ min_retention_months: 1,+ max_retention_months: 36,+ }+ const project: EventsRetentionApi = {+ ...organization,+ retention_months: projectMonths ?? organizationMonths ?? 36,+ retained_from: '2024-11-01',+ docs_url: 'https://posthog.com/docs/data/events-retention',+ project_retention_months: projectMonths,+ }+ return mswDecorator({+ get: {+ '/api/projects/:team_id/events_retention/': project,+ '/api/organizations/:organization_id/events_retention_setting/': organization,+ },+ })+}++export const OrganizationWithoutWindow: Story = {+ render: () => <OrganizationEventsRetentionSetting />,+ decorators: [retentionMocks(null, null)],+}++export const OrganizationWithWindow: Story = {+ render: () => <OrganizationEventsRetentionSetting />,+ decorators: [retentionMocks(24, null)],+}++export const ProjectUsingOrganizationWindow: Story = {+ render: () => <ProjectEventsRetentionSetting />,+ decorators: [retentionMocks(24, null)],+}++export const ProjectWithOwnWindow: Story = {+ render: () => <ProjectEventsRetentionSetting />,+ decorators: [retentionMocks(24, 12)],+}diff --git a/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsx b/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsxnew file mode 100644index 000000000000..865b88a0056e--- /dev/null+++ b/products/product_analytics/frontend/settings/EventsRetentionWindowForm.tsx@@ -0,0 +1,144 @@+import { useEffect, useState } from 'react'++import { LemonBanner, LemonButton, LemonDialog, LemonInput, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { LONGEST_PLAN_RETENTION_MONTHS } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'++export interface EventsRetentionWindowFormProps {+ retentionMonths: number | null+ minMonths: number+ maxMonths: number+ planMonths: number+ /** Who keeps events for the chosen window, as the start of a sentence, e.g. "This project". */+ keptBy: string+ /** What happens when the window is removed. */+ removedDescription: string+ saving: boolean+ restrictionReason: string | null+ onSave: (retentionMonths: number | null) => void+ dataAttr: string+}++function draftMonthsProblem(+ draftMonths: number | undefined,+ minMonths: number,+ maxMonths: number,+ retentionMonths: number | null+): string | null {+ if (draftMonths === undefined || !Number.isInteger(draftMonths)) {+ return 'Enter a whole number of months'+ }+ if (draftMonths < minMonths || draftMonths > maxMonths) {+ return `Choose between ${minMonths} and ${maxMonths} months`+ }+ if (draftMonths === retentionMonths) {+ return 'No changes to save'+ }+ return null+}++export function EventsRetentionWindowForm({+ retentionMonths,+ minMonths,+ maxMonths,+ planMonths,+ keptBy,+ removedDescription,+ saving,+ restrictionReason,+ onSave,+ dataAttr,+}: EventsRetentionWindowFormProps): JSX.Element {+ const [draftMonths, setDraftMonths] = useState<number | undefined>(retentionMonths ?? undefined)++ useEffect(() => {+ setDraftMonths(retentionMonths ?? undefined)+ }, [retentionMonths])++ const saveDisabledReason =+ restrictionReason ?? draftMonthsProblem(draftMonths, minMonths, maxMonths, retentionMonths)++ const confirmSave = (): void => {+ if (draftMonths === undefined) {+ return+ }+ LemonDialog.open({+ title: `Delete events older than ${draftMonths} months?`,+ description: `${keptBy} keeps events for ${draftMonths} months. Older events are deleted at the next monthly cleanup and can't be restored.`,+ primaryButton: {+ children: 'Delete older events',+ status: 'danger',+ onClick: () => onSave(draftMonths),+ 'data-attr': `${dataAttr}-confirm`,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ const confirmRemove = (): void => {+ LemonDialog.open({+ title: 'Remove this window?',+ description: removedDescription,+ primaryButton: {+ children: 'Remove window',+ onClick: () => onSave(null),+ 'data-attr': `${dataAttr}-remove-confirm`,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <div>+ <LemonBanner type="warning" className="max-w-160 mb-4">+ Events older than this window are deleted at the next monthly cleanup. Deleted events can't be restored.+ </LemonBanner>+ <div className="flex flex-wrap items-center gap-2">+ <LemonInput+ type="number"+ min={minMonths}+ max={maxMonths}+ value={draftMonths}+ onChange={setDraftMonths}+ onPressEnter={() => !saveDisabledReason && confirmSave()}+ placeholder="Not set"+ suffix={<span className="text-secondary">months</span>}+ disabled={!!restrictionReason || saving}+ className="w-40"+ data-attr={`${dataAttr}-input`}+ />+ <LemonButton+ type="primary"+ status="danger"+ onClick={confirmSave}+ loading={saving}+ disabledReason={saveDisabledReason}+ data-attr={`${dataAttr}-save`}+ >+ Save+ </LemonButton>+ {retentionMonths !== null && (+ <LemonButton+ type="secondary"+ onClick={confirmRemove}+ disabledReason={restrictionReason ?? (saving ? 'Saving...' : null)}+ data-attr={`${dataAttr}-remove`}+ >+ Remove window+ </LemonButton>+ )}+ </div>+ <p className="mt-2 mb-0 text-sm text-secondary">+ You can choose between {minMonths} and {maxMonths} months.+ {maxMonths === planMonths && planMonths < LONGEST_PLAN_RETENTION_MONTHS && (+ <>+ {' '}+ Need a longer window? <Link to={urls.organizationBilling()}>Upgrade your plan</Link>.+ </>+ )}+ </p>+ </div>+ )+}diff --git a/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsx b/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsxnew file mode 100644index 000000000000..235df7834d7e--- /dev/null+++ b/products/product_analytics/frontend/settings/OrganizationEventsRetentionSetting.tsx@@ -0,0 +1,47 @@+import { useActions, useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import { useRestrictedArea } from 'lib/components/RestrictedArea'+import { OrganizationMembershipLevel } from 'lib/constants'++import { eventsRetentionSettingsLogic } from './eventsRetentionSettingsLogic'+import { EventsRetentionWindowForm } from './EventsRetentionWindowForm'++export function OrganizationEventsRetentionSetting(): JSX.Element | null {+ const { projectRetention, organizationRetention, organizationRetentionLoading } =+ useValues(eventsRetentionSettingsLogic)+ const { updateOrganizationRetention } = useActions(eventsRetentionSettingsLogic)+ const restrictionReason = useRestrictedArea({ minimumAccessLevel: OrganizationMembershipLevel.Admin })++ if (!projectRetention || !organizationRetention) {+ return null+ }++ const planMonths = organizationRetention.plan_retention_months++ return (+ <div>+ <p className="max-w-160 text-sm text-secondary mb-4">+ Choose how long projects in this organization keep events. A project can set its own window instead.{' '}+ {organizationRetention.organization_retention_months === null &&+ `No window is set, so projects keep events for your plan's window of ${planMonths} months. `}+ <Link to={projectRetention.docs_url} target="_blank">+ Learn more+ </Link>+ </p>+ <EventsRetentionWindowForm+ retentionMonths={organizationRetention.organization_retention_months}+ minMonths={organizationRetention.min_retention_months}+ maxMonths={organizationRetention.max_retention_months}+ planMonths={planMonths}+ keptBy="Every project without its own window"+ removedDescription={`Projects without their own window will keep events for your plan's window of ${planMonths} months.`}+ saving={organizationRetentionLoading}+ restrictionReason={restrictionReason}+ onSave={updateOrganizationRetention}+ dataAttr="organization-events-retention"+ />+ </div>+ )+}diff --git a/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsx b/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsxnew file mode 100644index 000000000000..31c1605777fb--- /dev/null+++ b/products/product_analytics/frontend/settings/ProjectEventsRetentionSetting.tsx@@ -0,0 +1,58 @@+import { useActions, useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import { useRestrictedArea } from 'lib/components/RestrictedArea'+import { OrganizationMembershipLevel } from 'lib/constants'+import { urls } from 'scenes/urls'++import { eventsRetentionSettingsLogic } from './eventsRetentionSettingsLogic'+import { EventsRetentionWindowForm } from './EventsRetentionWindowForm'++export function ProjectEventsRetentionSetting(): JSX.Element | null {+ const { projectRetention, projectRetentionLoading } = useValues(eventsRetentionSettingsLogic)+ const { updateProjectRetention } = useActions(eventsRetentionSettingsLogic)+ const restrictionReason = useRestrictedArea({ minimumAccessLevel: OrganizationMembershipLevel.Admin })++ if (!projectRetention) {+ return null+ }++ const organizationMonths = projectRetention.organization_retention_months+ const planMonths = projectRetention.plan_retention_months+ const fallback =+ organizationMonths !== null+ ? `the organization's window of ${organizationMonths} months`+ : `your plan's window of ${planMonths} months`++ return (+ <div>+ <p className="max-w-160 text-sm text-secondary mb-4">+ Choose how long this project keeps events. This replaces the window set in{' '}+ <Link to={urls.settings('organization-details', 'organization-events-retention')}>+ organization settings+ </Link>+ . {projectRetention.project_retention_months === null && `This project uses ${fallback}. `}+ <Link to={projectRetention.docs_url} target="_blank">+ Learn more+ </Link>+ </p>+ <EventsRetentionWindowForm+ retentionMonths={projectRetention.project_retention_months}+ minMonths={projectRetention.min_retention_months}+ maxMonths={projectRetention.max_retention_months}+ planMonths={planMonths}+ keptBy="This project"+ removedDescription={+ organizationMonths !== null+ ? `This project will use ${fallback}. Older events are deleted at the next monthly cleanup and can't be restored.`+ : `This project will keep events for ${fallback}.`+ }+ saving={projectRetentionLoading}+ restrictionReason={restrictionReason}+ onSave={updateProjectRetention}+ dataAttr="project-events-retention"+ />+ </div>+ )+}diff --git a/products/product_analytics/frontend/settings/eventsRetentionSettingsLogic.ts b/products/product_analytics/frontend/settings/eventsRetentionSettingsLogic.tsnew file mode 100644index 000000000000..17cc48b4f096--- /dev/null+++ b/products/product_analytics/frontend/settings/eventsRetentionSettingsLogic.ts@@ -0,0 +1,154 @@+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'+import { loaders } from 'kea-loaders'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { organizationLogic } from 'scenes/organizationLogic'+import { teamLogic } from 'scenes/teamLogic'++import * as api from 'products/product_analytics/frontend/generated/api'+import type {+ EventsRetentionApi,+ OrganizationEventsRetentionApi,+} from 'products/product_analytics/frontend/generated/api.schemas'+import { dataRetentionBannerLogic } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface eventsRetentionSettingsLogicValues {+ currentOrganizationId: string // organizationLogic+ currentTeamId: number | null // teamLogic+ organizationRetention: OrganizationEventsRetentionApi | null+ organizationRetentionLoading: boolean+ projectRetention: EventsRetentionApi | null+ projectRetentionLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface eventsRetentionSettingsLogicActions {+ loadOrganizationRetention: () => any+ loadOrganizationRetentionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOrganizationRetentionSuccess: (+ organizationRetention: OrganizationEventsRetentionApi | null,+ payload?: any+ ) => {+ organizationRetention: OrganizationEventsRetentionApi | null+ payload?: any+ }+ loadProjectRetention: () => any+ loadProjectRetentionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProjectRetentionSuccess: (+ projectRetention: EventsRetentionApi | null,+ payload?: any+ ) => {+ projectRetention: EventsRetentionApi | null+ payload?: any+ }+ updateOrganizationRetention: (retentionMonths: number | null) => number | null+ updateOrganizationRetentionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ updateOrganizationRetentionSuccess: (+ organizationRetention: OrganizationEventsRetentionApi | null,+ payload?: number | null+ ) => {+ organizationRetention: OrganizationEventsRetentionApi | null+ payload?: number | null+ }+ updateProjectRetention: (retentionMonths: number | null) => number | null+ updateProjectRetentionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ updateProjectRetentionSuccess: (+ projectRetention: EventsRetentionApi | null,+ payload?: number | null+ ) => {+ projectRetention: EventsRetentionApi | null+ payload?: number | null+ }+}++export type eventsRetentionSettingsLogicType = MakeLogicType<+ eventsRetentionSettingsLogicValues,+ eventsRetentionSettingsLogicActions+>++export const eventsRetentionSettingsLogic = kea<eventsRetentionSettingsLogicType>([+ path(['products', 'product_analytics', 'frontend', 'settings', 'eventsRetentionSettingsLogic']),+ connect(() => ({+ values: [organizationLogic, ['currentOrganizationId'], teamLogic, ['currentTeamId']],+ })),+ loaders(({ values }) => ({+ projectRetention: [+ null as EventsRetentionApi | null,+ {+ loadProjectRetention: async () => {+ if (values.currentTeamId === null) {+ return null+ }+ return await api.eventsRetentionRetrieve(String(values.currentTeamId))+ },+ updateProjectRetention: async (retentionMonths: number | null) => {+ if (values.currentTeamId === null) {+ return values.projectRetention+ }+ return await api.eventsRetentionUpdate(String(values.currentTeamId), {+ retention_months: retentionMonths,+ })+ },+ },+ ],+ organizationRetention: [+ null as OrganizationEventsRetentionApi | null,+ {+ loadOrganizationRetention: async () => {+ if (!values.currentOrganizationId) {+ return null+ }+ return await api.organizationEventsRetentionRetrieve(values.currentOrganizationId)+ },+ updateOrganizationRetention: async (retentionMonths: number | null) => {+ if (!values.currentOrganizationId) {+ return values.organizationRetention+ }+ return await api.organizationEventsRetentionUpdate(values.currentOrganizationId, {+ retention_months: retentionMonths,+ })+ },+ },+ ],+ })),+ listeners(({ actions }) => ({+ updateProjectRetentionSuccess: () => {+ lemonToast.success('Events retention updated')+ dataRetentionBannerLogic.findMounted()?.actions.loadRetentionMonths()+ },+ updateOrganizationRetentionSuccess: () => {+ lemonToast.success('Events retention updated')+ actions.loadProjectRetention()+ dataRetentionBannerLogic.findMounted()?.actions.loadRetentionMonths()+ },+ })),+ afterMount(({ actions }) => {+ actions.loadProjectRetention()+ actions.loadOrganizationRetention()+ }),+])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 60b435b34475..4f1b9224e85d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46771,6 +46771,17 @@ 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.+ * @nullable+ */+ readonly organization_retention_months: number | null;+ /** The longest window the organization's plan allows, in months. */+ readonly plan_retention_months: number;+ /** The shortest window an admin can set, in months. */+ readonly min_retention_months: number;+ /** The longest window an admin can set, in months. Never longer than the plan's window. */+ readonly max_retention_months: number;/*** How many months of events stay queryable, counted back from today. Null while no retention window applies to the project.* @nullable@@ -46783,6 +46794,20 @@ export namespace Schemas {readonly retained_from: string | null;/** Where the events retention policy is documented. */readonly docs_url: string;+ /**+ * The window, in months, set for this project. Null while the project uses the organization's window.+ * @nullable+ */+ readonly project_retention_months: number | null;+ }++ export interface EventsRetentionUpdate {+ /**+ * The window in months. Events older than this are deleted on the next monthly cleanup and can't be restored. Null removes the window.+ * @minimum 1+ * @nullable+ */+ retention_months: number | null;}export interface ExcerptChoice {@@ -75851,6 +75876,20 @@ export namespace Schemas {readonly scim_base_url: string | null;}+ 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.+ * @nullable+ */+ readonly organization_retention_months: number | null;+ /** The longest window the organization's plan allows, in months. */+ readonly plan_retention_months: number;+ /** The shortest window an admin can set, in months. */+ readonly min_retention_months: number;+ /** The longest window an admin can set, in months. Never longer than the plan's window. */+ readonly max_retention_months: number;+ }+export interface OrganizationFeatureFlagRow {/** ID of the representative feature flag for this key */id: number;