Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(retention): add a read-only events retention endpoint (#105350)

Andy Zhaof637123043b2
diff --git a/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.test.ts b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.test.ts
new file mode 100644
index 000000000000..a4e46302505a
--- /dev/null
+++ b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.test.ts
@@ -0,0 +1,83 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { expectLogic } from 'kea-test-utils'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import type { TeamType } from '~/types'
+
+import { dataRetentionBannerLogic } from './dataRetentionBannerLogic'
+
+const RETENTION = {
+ retention_months: 84,
+ retained_from: '2019-09-22',
+ docs_url: 'https://posthog.com/docs/data/events-retention',
+}
+
+describe('dataRetentionBannerLogic', () => {
+ it.each([
+ {
+ name: 'reads the window from the events retention endpoint',
+ response: [200, RETENTION],
+ retentionMonths: 84,
+ },
+ {
+ name: 'treats a null window as retention not enforced',
+ response: [200, { ...RETENTION, retention_months: null, retained_from: null }],
+ retentionMonths: null,
+ },
+ ])('$name', async ({ response, retentionMonths }) => {
+ useMocks({ get: { '/api/projects/:team_id/events_retention/': () => response } })
+ initKeaTests()
+ const logic = dataRetentionBannerLogic()
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadRetentionMonths', 'loadRetentionMonthsSuccess'])
+ .toMatchValues({ retentionMonths, retentionEnforced: retentionMonths !== null })
+ })
+
+ it('waits for the team id before loading', async () => {
+ const requestedTeamIds: string[] = []
+ useMocks({
+ get: {
+ '/api/projects/:team_id/events_retention/': ({ params }) => {
+ requestedTeamIds.push(String(params.team_id))
+ return [200, RETENTION]
+ },
+ },
+ })
+ initKeaTests(true, null as unknown as TeamType)
+ const logic = dataRetentionBannerLogic()
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions([teamLogic.actionTypes.loadCurrentTeamSuccess, 'loadRetentionMonthsSuccess'])
+ .toMatchValues({ retentionMonths: 84 })
+ expect(requestedTeamIds).toEqual([String(MOCK_DEFAULT_TEAM.id)])
+ })
+
+ it('does not call the endpoint in a shared view', async () => {
+ let requested = false
+ useMocks({
+ get: {
+ '/api/projects/:team_id/events_retention/': () => {
+ requested = true
+ return [200, RETENTION]
+ },
+ },
+ })
+ initKeaTests()
+ ;(window as { POSTHOG_EXPORTED_DATA?: unknown }).POSTHOG_EXPORTED_DATA = { type: 'embed' }
+ const logic = dataRetentionBannerLogic()
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadRetentionMonths', 'loadRetentionMonthsSuccess'])
+ .toMatchValues({ retentionMonths: null })
+ expect(requested).toBe(false)
+ delete (window as { POSTHOG_EXPORTED_DATA?: unknown }).POSTHOG_EXPORTED_DATA
+ })
+})
diff --git a/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
index 9ed57c3c63dd..4ebf8c63f4bc 100644
--- a/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
+++ b/frontend/src/scenes/insights/dataRetention/dataRetentionBannerLogic.ts
@@ -1,7 +1,13 @@
-import { MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
import { dayjs } from 'lib/dayjs'
import { organizationLogic } from 'scenes/organizationLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { isSharedView } from '~/exporter/exporterViewLogic'
+
+import { eventsRetentionRetrieve } from 'products/product_analytics/frontend/generated/api'
import type { OrganizationType } from '../../../types'
@@ -23,11 +29,13 @@ function retentionMonthsLabel(months: number): string {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataRetentionBannerLogicValues {
currentOrganization: OrganizationType | null // organizationLogic
+ currentTeamId: number | null // teamLogic
accountAgeEligible: boolean
isSnoozed: boolean
retentionApplies: boolean
retentionEnforced: boolean
retentionMonths: number | null
+ retentionMonthsLoading: boolean
retentionPeriodLabel: string | null
snoozedUntil: string | null
warningEligible: boolean
@@ -35,6 +43,21 @@ export interface dataRetentionBannerLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataRetentionBannerLogicActions {
+ loadRetentionMonths: () => any
+ loadRetentionMonthsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRetentionMonthsSuccess: (
+ retentionMonths: number | null,
+ payload?: any
+ ) => {
+ retentionMonths: number | null
+ payload?: any
+ }
snooze: () => {
value: true
}
@@ -65,14 +88,26 @@ export type dataRetentionBannerLogicType = MakeLogicType<
export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([
path(['scenes', 'insights', 'dataRetention', 'dataRetentionBannerLogic']),
connect({
- values: [organizationLogic, ['currentOrganization']],
+ values: [organizationLogic, ['currentOrganization'], teamLogic, ['currentTeamId']],
}),
actions({
snooze: true,
}),
+ loaders(({ values }) => ({
+ retentionMonths: [
+ null as number | null,
+ {
+ loadRetentionMonths: async () => {
+ if (values.currentTeamId === null || isSharedView()) {
+ return null
+ }
+ const retention = await eventsRetentionRetrieve(String(values.currentTeamId))
+ return retention.retention_months ?? null
+ },
+ },
+ ],
+ })),
reducers({
- // No source until events retention enforcement ships, see https://github.com/PostHog/posthog/issues/17031
- retentionMonths: [null as number | null, {}],
snoozedUntil: [
null as string | null,
{ persist: true },
@@ -120,4 +155,12 @@ export const dataRetentionBannerLogic = kea<dataRetentionBannerLogicType>([
(retentionApplies: boolean, isSnoozed: boolean): boolean => retentionApplies && !isSnoozed,
],
}),
+ listeners(({ actions }) => ({
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => {
+ actions.loadRetentionMonths()
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadRetentionMonths()
+ }),
])
diff --git a/posthog/models/team/event_retention.py b/posthog/models/team/event_retention.py
index 1c6729d1e869..7a0c347e0e5e 100644
--- a/posthog/models/team/event_retention.py
+++ b/posthog/models/team/event_retention.py
@@ -1,9 +1,11 @@
+from datetime import date
from typing import TYPE_CHECKING, Optional
from django.conf import settings
from django.utils import timezone
import posthoganalytics
+from dateutil.relativedelta import relativedelta
from posthog.cloud_utils import is_cloud
from posthog.constants import AvailableFeature
@@ -69,6 +71,10 @@ def events_retention_months_for_team(team: Optional[Team], team_id: Optional[int
return team.event_retention_months or DEFAULT_EVENT_RETENTION_MONTHS
+def events_retention_floor_date(team: Team, retention_months: int) -> date:
+ return (timezone.now() - relativedelta(months=retention_months)).astimezone(team.timezone_info).date()
+
+
def parse_events_feature_to_months(retention_feature: ProductFeature | None) -> int:
"""Map the billing events-retention entitlement to a number of months for the sync job.
diff --git a/products/product_analytics/backend/presentation/events_retention.py b/products/product_analytics/backend/presentation/events_retention.py
new file mode 100644
index 000000000000..cc01d46d83d1
--- /dev/null
+++ b/products/product_analytics/backend/presentation/events_retention.py
@@ -0,0 +1,60 @@
+from typing import Any
+
+from drf_spectacular.utils import extend_schema, extend_schema_serializer
+from rest_framework import serializers, viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.team.event_retention import events_retention_floor_date, events_retention_months_for_team
+
+EVENTS_RETENTION_DOCS_URL = "https://posthog.com/docs/data/events-retention"
+
+
+@extend_schema_serializer(many=False)
+class EventsRetentionSerializer(serializers.Serializer):
+ retention_months = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="How many months of events stay queryable, counted back from today. Null while no retention window applies to the project.",
+ )
+ retained_from = serializers.DateField(
+ read_only=True,
+ allow_null=True,
+ help_text="The earliest date whose events are still queryable, in the project's timezone. Null while no retention window applies to the project.",
+ )
+ docs_url = serializers.URLField(
+ read_only=True,
+ help_text="Where the events retention policy is documented.",
+ )
+
+
+@extend_schema(tags=["events_retention"])
+class EventsRetentionViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "project"
+ pagination_class = None
+
+ @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 "
+ "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 Response(
+ EventsRetentionSerializer(
+ {
+ "retention_months": retention_months,
+ "retained_from": retained_from,
+ "docs_url": EVENTS_RETENTION_DOCS_URL,
+ }
+ ).data
+ )
diff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.py
index da55012c7d47..c92874cfdb78 100644
--- a/products/product_analytics/backend/routes.py
+++ b/products/product_analytics/backend/routes.py
@@ -3,6 +3,7 @@ from posthog.api.routing import RouterRegistry
from posthog.settings import EE_AVAILABLE
import products.alerts.backend.presentation.views.alert as alert
+from products.product_analytics.backend.presentation.events_retention import EventsRetentionViewSet
from products.product_analytics.backend.presentation.insight import InsightViewSet
from products.product_analytics.backend.presentation.insight_ee import EnterpriseInsightsViewSet
from products.product_analytics.backend.presentation.insight_variable import InsightVariableViewSet
@@ -47,3 +48,10 @@ def register_routes(routers: RouterRegistry) -> None:
"project_paths_v2",
["team_id"],
)
+
+ routers.projects.register(
+ r"events_retention",
+ EventsRetentionViewSet,
+ "project_events_retention",
+ ["team_id"],
+ )
diff --git a/products/product_analytics/backend/tests/api/test_events_retention.py b/products/product_analytics/backend/tests/api/test_events_retention.py
new file mode 100644
index 000000000000..95f5486d4f3c
--- /dev/null
+++ b/products/product_analytics/backend/tests/api/test_events_retention.py
@@ -0,0 +1,51 @@
+import time_machine
+from posthog.test.base import APIBaseTest
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+
+@override_settings(EVENTS_DATA_RETENTION_ENFORCED=True)
+class TestEventsRetentionAPI(APIBaseTest):
+ def url(self) -> str:
+ return f"/api/projects/{self.team.id}/events_retention/"
+
+ @parameterized.expand(
+ [
+ ("utc", "UTC", "2025-09-22"),
+ ("ahead_of_utc", "Pacific/Auckland", "2025-09-23"),
+ ]
+ )
+ @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.team.timezone = tz
+ self.team.event_retention_months = 12
+ self.team.save()
+
+ response = self.client.get(self.url())
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {
+ "retention_months": 12,
+ "retained_from": retained_from,
+ "docs_url": "https://posthog.com/docs/data/events-retention",
+ }
+
+ @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": None,
+ "retained_from": None,
+ "docs_url": "https://posthog.com/docs/data/events-retention",
+ }
+
+ @parameterized.expand([("patch",), ("put",), ("post",), ("delete",)])
+ def test_rejects_writes(self, method: str) -> None:
+ response = getattr(self.client, method)(self.url(), {"retention_months": 1})
+
+ assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index bcc2edf59b77..854393905d40 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -211,6 +211,21 @@ export interface ElementValueApi {
name: string
}
+export interface EventsRetentionApi {
+ /**
+ * How many months of events stay queryable, counted back from today. Null while no retention window applies to the project.
+ * @nullable
+ */
+ readonly retention_months: number | null
+ /**
+ * The earliest date whose events are still queryable, in the project's timezone. Null while no retention window applies to the project.
+ * @nullable
+ */
+ readonly retained_from: string | null
+ /** Where the events retention policy is documented. */
+ readonly docs_url: string
+}
+
export type InsightVizNodeApiKind = (typeof InsightVizNodeApiKind)[keyof typeof InsightVizNodeApiKind]
export const InsightVizNodeApiKind = {
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index e1a6fc98c68e..2836a67af852 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -20,6 +20,7 @@ import type {
ElementsListParams,
ElementsStatsRetrieveParams,
ElementsValuesListParams,
+ EventsRetentionApi,
InsightApi,
InsightBulkDeleteRequestApi,
InsightBulkDeleteResponseApi,
@@ -343,6 +344,24 @@ export const elementsValuesList = async (
})
}
+export const getEventsRetentionRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/events_retention/`
+}
+
+/**
+ * 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.
+ * @summary Get the events retention window for a project
+ */
+export const eventsRetentionRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<EventsRetentionApi> => {
+ return apiMutator<EventsRetentionApi>(getEventsRetentionRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getInsightsListUrl = (projectId: string, params?: InsightsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index 21ac9217516d..641de13d8bee 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -69,6 +69,9 @@ tools:
elements-values-list:
operation: elements_values_list
enabled: false
+ events-retention-retrieve:
+ operation: events_retention_retrieve
+ enabled: false
insight-create:
operation: insights_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0f6747488141..be6a8a15de6c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38632,6 +38632,21 @@ export namespace Schemas {
NeedsAttention: 'needs_attention',
} as const;
+ export interface EventsRetention {
+ /**
+ * How many months of events stay queryable, counted back from today. Null while no retention window applies to the project.
+ * @nullable
+ */
+ readonly retention_months: number | null;
+ /**
+ * The earliest date whose events are still queryable, in the project's timezone. Null while no retention window applies to the project.
+ * @nullable
+ */
+ readonly retained_from: string | null;
+ /** Where the events retention policy is documented. */
+ readonly docs_url: string;
+ }
+
export interface ExecuteTestClusterRequest {
/**
* ClickHouse SQL to run against the test cluster.