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(data-deletion): list configured events retention in django admin (#120094)

Paweł Szczur99d1586c2c63
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 412cb59dc984..ab2443618487 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -293,6 +293,8 @@ Staff set the retention in Django admin, on the team and organization pages:
- `TeamEventsRetentionConfig` holds a team's own months, which must fall within its organization's range. Saving an organization range that excludes an existing team value fails until that team changes.
- A team's effective retention is its own value, else its organization's default. A team with neither keeps all its events.
- This setting is separate from `Team.event_retention_months`, which the billing plan sets and which only hides older events from queries.
+- The Events retention page under Custom tools (`/admin/events-retention/`) lists every team that has a value of its own or belongs to an organization with a config.
+ It shows each team's billing months (`Team.event_retention_months`), its effective retention, where that comes from, and the first month the cleanup keeps, 100 teams per page.
`monthly_old_events_cleanup_job` has two steps:
diff --git a/ee/urls.py b/ee/urls.py
index 5f26231174e8..94b2dcb8ea92 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -70,6 +70,7 @@ if settings.ADMIN_PORTAL_ENABLED:
pass
from posthog.admin.admins.distinct_id_usage_admin import distinct_id_usage_view
+ from posthog.admin.admins.events_retention_admin import events_retention_view
from posthog.admin.admins.health_check_admin import (
health_check_list_view,
health_check_runs_fragment_view,
@@ -102,6 +103,11 @@ if settings.ADMIN_PORTAL_ENABLED:
admin.site.admin_view(distinct_id_usage_view),
name="distinct-id-usage",
),
+ path(
+ "admin/events-retention/",
+ admin.site.admin_view(events_retention_view),
+ name="events-retention",
+ ),
path(
"admin/tophog/",
admin.site.admin_view(tophog_dashboard_view),
diff --git a/posthog/admin/admins/events_retention_admin.py b/posthog/admin/admins/events_retention_admin.py
new file mode 100644
index 000000000000..1affc36b3831
--- /dev/null
+++ b/posthog/admin/admins/events_retention_admin.py
@@ -0,0 +1,66 @@
+from datetime import UTC, datetime
+
+from django.contrib import admin
+from django.core.exceptions import PermissionDenied
+from django.core.paginator import Paginator
+from django.http import HttpRequest, HttpResponse
+from django.shortcuts import render
+
+from posthog.dataclasses import frozen
+from posthog.models.events_retention_config import (
+ ConfiguredEventsRetention,
+ configured_events_retention,
+ count_configured_events_retention,
+ describe_months_range,
+ whole_month_cutoff,
+)
+
+TEAMS_PER_PAGE = 100
+
+
+@frozen
+class _RetentionRow:
+ retention: ConfiguredEventsRetention
+ source: str
+ allowed_range: str
+ deletes_before: datetime | None
+
+
+def _row(retention: ConfiguredEventsRetention, now: datetime) -> _RetentionRow:
+ if retention.team_months is not None:
+ source = "Team setting"
+ elif retention.organization_default_months is not None:
+ source = "Organization default"
+ else:
+ source = "Not set, events are kept"
+ low, high = retention.organization_min_months, retention.organization_max_months
+ months = retention.months
+ return _RetentionRow(
+ retention=retention,
+ source=source,
+ allowed_range=describe_months_range(low, high)
+ if low is not None or high is not None
+ else "any number of months",
+ deletes_before=whole_month_cutoff(now, months) if months is not None else None,
+ )
+
+
+def events_retention_view(request: HttpRequest) -> HttpResponse:
+ if not request.user.is_staff:
+ raise PermissionDenied
+
+ # The paginator only works out the page bounds, so the query reads the rows of one page.
+ page = Paginator(range(count_configured_events_retention()), TEAMS_PER_PAGE).get_page(request.GET.get("page"))
+ retention = configured_events_retention(offset=max(page.start_index() - 1, 0), limit=len(page.object_list))
+ now = datetime.now(UTC)
+ context = {
+ "rows": [_row(item, now) for item in retention],
+ "page": page,
+ "title": "Events retention",
+ "has_view_permission": True,
+ "site_title": admin.site.site_title,
+ "site_header": admin.site.site_header,
+ "site_url": admin.site.site_url,
+ "has_permission": True,
+ }
+ return render(request, "admin/events_retention.html", context)
diff --git a/posthog/admin/test_events_retention_admin.py b/posthog/admin/test_events_retention_admin.py
new file mode 100644
index 000000000000..300cada87503
--- /dev/null
+++ b/posthog/admin/test_events_retention_admin.py
@@ -0,0 +1,29 @@
+import time_machine
+from posthog.test.base import BaseTest
+
+from django.urls import reverse
+
+from posthog.models.events_retention_config import OrganizationEventsRetentionConfig
+
+
+class TestEventsRetentionAdmin(BaseTest):
+ @time_machine.travel("2026-10-20T12:00:00Z", tick=False)
+ def test_page_lists_the_teams_of_an_organization_with_a_default(self) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ self.client.force_login(self.user)
+
+ empty = self.client.get(reverse("events-retention"))
+ assert empty.status_code == 200
+ assert "No team has a deletion retention yet" in empty.content.decode()
+
+ OrganizationEventsRetentionConfig.objects.create(
+ organization=self.organization, default_events_retention_months=13
+ )
+ response = self.client.get(reverse("events-retention"))
+
+ assert response.status_code == 200
+ content = response.content.decode()
+ assert reverse("admin:posthog_team_change", args=[self.team.id]) in content
+ assert "Organization default" in content
+ assert "September 2025" in content
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 0a7cdca6b4d6..9ee3291808de 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -51,7 +51,7 @@ from posthog.models.deletion_targets import (
surviving_rows_sql,
sweep_clusters,
)
-from posthog.models.events_retention_config import effective_events_retention
+from posthog.models.events_retention_config import effective_events_retention, whole_month_cutoff
from posthog.models.group.sql import GROUPS_TABLE
from posthog.models.person.sql import (
PERSON_DISTINCT_ID2_TABLE,
@@ -145,11 +145,6 @@ class OldEventsCleanupPlan:
partitions: list[PartitionCleanup]
-def whole_month_cutoff(now: datetime, retention_months: int) -> datetime:
- """Start of the month that holds the instant ``retention_months`` before ``now``."""
- return (now - relativedelta(months=retention_months)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
-
-
def _yyyymm(moment: datetime) -> int:
return moment.year * 100 + moment.month
diff --git a/posthog/models/events_retention_config.py b/posthog/models/events_retention_config.py
index 8f08464698f8..940d33b02e20 100644
--- a/posthog/models/events_retention_config.py
+++ b/posthog/models/events_retention_config.py
@@ -1,10 +1,14 @@
+from datetime import datetime
from uuid import UUID
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import connection, models
+from dateutil.relativedelta import relativedelta
+
from posthog.dataclasses import frozen
+from posthog.models.organization import Organization
from posthog.models.team import Team
RETENTION_MONTHS_HELP = (
@@ -148,6 +152,11 @@ def _within(months: int, low: int | None, high: int | None) -> bool:
return (low is None or months >= low) and (high is None or months <= high)
+def whole_month_cutoff(now: datetime, retention_months: int) -> datetime:
+ """Start of the month that holds the instant ``retention_months`` before ``now``."""
+ return (now - relativedelta(months=retention_months)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
+
+
def describe_months_range(low: int | None, high: int | None) -> str:
if low is not None and high is not None:
return f"between {low} and {high} months"
@@ -185,3 +194,84 @@ def effective_events_retention() -> list[TeamEventsRetention]:
TeamEventsRetention(organization_id=organization_id, team_id=team_id, months=months)
for organization_id, team_id, months in cursor.fetchall()
]
+
+
+@frozen
+class ConfiguredEventsRetention:
+ organization_id: UUID
+ organization_name: str
+ team_id: int
+ team_name: str
+ team_months: int | None
+ organization_default_months: int | None
+ organization_min_months: int | None
+ organization_max_months: int | None
+ billing_months: int
+
+ @property
+ def months(self) -> int | None:
+ return self.team_months if self.team_months is not None else self.organization_default_months
+
+
+# Every team that has a retention value of its own or belongs to an organization with a retention config.
+_CONFIGURED_RETENTION_FROM = f"""
+ FROM {Team._meta.db_table} AS team
+ JOIN {Organization._meta.db_table} AS organization ON organization.id = team.organization_id
+ LEFT JOIN {TeamEventsRetentionConfig._meta.db_table} AS team_config ON team_config.team_id = team.id
+ LEFT JOIN {OrganizationEventsRetentionConfig._meta.db_table} AS org_config
+ ON org_config.organization_id = team.organization_id
+ WHERE org_config.organization_id IS NOT NULL OR team_config.events_retention_months IS NOT NULL
+"""
+
+
+def count_configured_events_retention() -> int:
+ with connection.cursor() as cursor:
+ cursor.execute(f"SELECT COUNT(*) {_CONFIGURED_RETENTION_FROM}")
+ [[count]] = cursor.fetchall()
+ return count
+
+
+def configured_events_retention(*, offset: int, limit: int) -> list[ConfiguredEventsRetention]:
+ """One page of the teams that count_configured_events_retention counts, ordered by organization."""
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f"""
+ SELECT organization.id,
+ organization.name,
+ team.id,
+ team.name,
+ team_config.events_retention_months,
+ org_config.default_events_retention_months,
+ org_config.min_events_retention_months,
+ org_config.max_events_retention_months,
+ team.event_retention_months
+ {_CONFIGURED_RETENTION_FROM}
+ ORDER BY organization.name, organization.id, team.id
+ LIMIT %s OFFSET %s
+ """,
+ [limit, offset],
+ )
+ return [
+ ConfiguredEventsRetention(
+ organization_id=organization_id,
+ organization_name=organization_name,
+ team_id=team_id,
+ team_name=team_name,
+ team_months=team_months,
+ organization_default_months=default_months,
+ organization_min_months=min_months,
+ organization_max_months=max_months,
+ billing_months=billing_months,
+ )
+ for (
+ organization_id,
+ organization_name,
+ team_id,
+ team_name,
+ team_months,
+ default_months,
+ min_months,
+ max_months,
+ billing_months,
+ ) in cursor.fetchall()
+ ]
diff --git a/posthog/models/test/test_events_retention_config.py b/posthog/models/test/test_events_retention_config.py
index ba6887ef9d82..bda1771421eb 100644
--- a/posthog/models/test/test_events_retention_config.py
+++ b/posthog/models/test/test_events_retention_config.py
@@ -7,6 +7,8 @@ from parameterized import parameterized
from posthog.models.events_retention_config import (
OrganizationEventsRetentionConfig,
TeamEventsRetentionConfig,
+ configured_events_retention,
+ count_configured_events_retention,
effective_events_retention,
)
from posthog.models.organization import Organization
@@ -94,3 +96,26 @@ class TestEventsRetentionConfig(BaseTest):
(self.organization.id, cleared.id): 13,
(other_org.id, own_value.id): 24,
}
+
+ def test_configured_retention_lists_teams_with_a_value_or_an_org_config(self) -> None:
+ OrganizationEventsRetentionConfig.objects.create(
+ organization=self.organization, min_events_retention_months=12, max_events_retention_months=24
+ )
+ own_value = Team.objects.create(organization=self.organization, name="Own value")
+ TeamEventsRetentionConfig.objects.create(team=own_value, events_retention_months=18)
+ other_org = Organization.objects.create(name="No config")
+ Team.objects.create(organization=other_org, name="Keeps everything")
+ cleared = Team.objects.create(organization=other_org, name="Cleared")
+ TeamEventsRetentionConfig.objects.create(team=cleared, events_retention_months=None)
+ overrides = Team.objects.create(organization=other_org, name="Overrides")
+ TeamEventsRetentionConfig.objects.create(team=overrides, events_retention_months=6)
+
+ retention = [
+ (item.team_id, item.team_months, item.months) for item in configured_events_retention(offset=0, limit=10)
+ ]
+
+ assert count_configured_events_retention() == 3
+ assert sorted(retention) == sorted([(self.team.id, None, None), (own_value.id, 18, 18), (overrides.id, 6, 6)])
+ assert [item.team_id for item in configured_events_retention(offset=1, limit=2)] == [
+ team_id for team_id, _, _ in retention[1:3]
+ ]
diff --git a/posthog/templates/admin/events_retention.html b/posthog/templates/admin/events_retention.html
new file mode 100644
index 000000000000..86f9d8e54448
--- /dev/null
+++ b/posthog/templates/admin/events_retention.html
@@ -0,0 +1,101 @@
+{% extends "admin/base_site.html" %}
+{% load i18n %}
+{% block extrastyle %}
+ {{ block.super }}
+ <style>
+ .retention-table {
+ width: 100%;
+ border-collapse: collapse;
+ }
+ .retention-table th {
+ padding: 8px 10px;
+ text-align: left;
+ border-bottom: 2px solid var(--hairline-color);
+ background: var(--darkened-bg);
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--body-quiet-color);
+ }
+ .retention-table td {
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--hairline-color);
+ font-size: 13px;
+ }
+ .retention-table tr.organization-row td {
+ background: var(--darkened-bg);
+ border-top: 2px solid var(--hairline-color);
+ }
+ .muted { color: var(--body-quiet-color); }
+ .retention-table th.group-header { text-align: center; }
+ .retention-table code.field-name { text-transform: none; letter-spacing: normal; }
+ </style>
+{% endblock %}
+{% block content %}
+ <p><a href="/admin/">&larr; Back to admin</a></p>
+ <p class="help">
+ Billing months is <code>Team.event_retention_months</code>, which the billing plan sets. It only hides older events in queries.
+ Deletion retention is the staff setting that the monthly cleanup enforces.
+ The cleanup deletes one calendar month at a time, and only when every event in that month is older than the retention.
+ </p>
+ {% if rows %}
+ {% regroup rows by retention.organization_id as organizations %}
+ <table class="retention-table">
+ <thead>
+ <tr>
+ <th rowspan="2">Team</th>
+ <th rowspan="2">
+ Billing months
+ <br />
+ <code class="field-name">event_retention_months</code>
+ </th>
+ <th colspan="4" class="group-header">Deletion retention</th>
+ </tr>
+ <tr>
+ <th>Team setting</th>
+ <th>Retention</th>
+ <th>Source</th>
+ <th>Deletes months before</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for organization in organizations %}
+ {% with first=organization.list.0.retention %}
+ <tr class="organization-row">
+ <td colspan="6">
+ <strong><a href="{% url 'admin:posthog_organization_change' first.organization_id %}">{{ first.organization_name }}</a></strong>
+ <span class="muted">({{ first.organization_id }})</span>
+ &middot; Default: {% if first.organization_default_months is not None %}{{ first.organization_default_months }} months{% else %}not set{% endif %}
+ &middot; Allowed: {{ organization.list.0.allowed_range }}
+ </td>
+ </tr>
+ {% endwith %}
+ {% for row in organization.list %}
+ <tr>
+ <td>
+ <a href="{% url 'admin:posthog_team_change' row.retention.team_id %}">{{ row.retention.team_name }}</a>
+ <span class="muted">({{ row.retention.team_id }})</span>
+ </td>
+ <td>{{ row.retention.billing_months }} months</td>
+ <td>{% if row.retention.team_months is not None %}{{ row.retention.team_months }} months{% else %}<span class="muted">-</span>{% endif %}</td>
+ <td>{% if row.retention.months is not None %}<strong>{{ row.retention.months }} months</strong>{% else %}<span class="muted">-</span>{% endif %}</td>
+ <td>{{ row.source }}</td>
+ <td>{% if row.deletes_before %}{{ row.deletes_before|date:"F Y" }}{% else %}<span class="muted">-</span>{% endif %}</td>
+ </tr>
+ {% endfor %}
+ {% endfor %}
+ </tbody>
+ </table>
+ <p class="paginator">
+ {% if page.has_previous %}
+ <a href="?page={{ page.previous_page_number }}">&larr; Previous</a>
+ {% endif %}
+ Page {{ page.number }} of {{ page.paginator.num_pages }} &middot; {{ page.paginator.count }} teams
+ {% if page.has_next %}
+ <a href="?page={{ page.next_page_number }}">Next &rarr;</a>
+ {% endif %}
+ </p>
+ {% else %}
+ <p>No team has a deletion retention yet. Set one on the organization or team page.</p>
+ {% endif %}
+{% endblock %}
diff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.html
index f8be62667faf..eabedde04215 100644
--- a/posthog/templates/custom_tools/app.html
+++ b/posthog/templates/custom_tools/app.html
@@ -24,6 +24,12 @@
<a href="{% url 'distinct-id-usage' %}">Distinct ID usage</a>
</td>
<td>Monitor distinct ID usage patterns and create ingestion restrictions</td>
+ <tr class="model-eventsretention">
+ <td scope="row">
+ <a href="{% url 'events-retention' %}">Events retention</a>
+ </td>
+ <td>List the organizations and teams that have an events retention, and which months get deleted</td>
+ </tr>
<tr class="model-tophog">
<td scope="row">
<a href="{% url 'tophog-dashboard' %}">TopHog Dashboard</a>