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): add staff-only events retention settings (#114156)

Paweł Szczur79ae5dce9e8e
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 41f9d85eb428..346c34971199 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -212,6 +212,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"TeamDataQualityConfig",
"TeamDataWarehouseConfig",
"TeamExperimentsConfig",
+ # Staff-only OneToOne extension keyed on the team, edited in Django admin and read by the
+ # events cleanup schedule; no endpoint looks it up by a user-supplied ID.
+ "TeamEventsRetentionConfig",
"TeamFeatureFlagsConfig",
# OneToOne extension of Team keyed on team_id, only ever read as get(team=team) via
# get_or_create_team_extension; no endpoint looks it up by a user-supplied ID.
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 24ce9cf79578..39eec27468b6 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -1001,6 +1001,7 @@ rules:
|OrganizationMembership
|OrganizationMemberNotificationLock
|OrganizationDomain
+ |OrganizationEventsRetentionConfig
|OrganizationFeatureFlagsConfig
|OrganizationIntegration
|OrganizationInvite
@@ -1082,6 +1083,7 @@ rules:
|OrganizationMembership
|OrganizationMemberNotificationLock
|OrganizationDomain
+ |OrganizationEventsRetentionConfig
|OrganizationFeatureFlagsConfig
|OrganizationIntegration
|OrganizationInvite
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 8ed8be88fb88..0275fcb6f04c 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -22,6 +22,7 @@ from django.utils.safestring import mark_safe
from posthog.admin.ai_training_opt_in_history import get_ai_training_opt_in_history
from posthog.admin.authorization import can_trigger_admin_deletion
from posthog.admin.inline_registry import extra_inlines_for
+from posthog.admin.inlines.events_retention_config_inline import OrganizationEventsRetentionConfigInline
from posthog.admin.inlines.organization_domain_inline import OrganizationDomainInline
from posthog.admin.inlines.organization_invite_inline import OrganizationInviteInline
from posthog.admin.inlines.organization_member_inline import OrganizationMemberInline
@@ -267,6 +268,7 @@ class OrganizationAdmin(admin.ModelAdmin):
OrganizationInviteInline,
OrganizationDomainInline,
ProxyRecordInline,
+ OrganizationEventsRetentionConfigInline,
]
readonly_fields = [
"id",
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index 8f1b097f5b2a..02dea93b477c 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -30,6 +30,7 @@ from temporalio import common
from temporalio.client import WorkflowExecutionStatus
from temporalio.common import SearchAttributePair, TypedSearchAttributes
+from posthog.admin.inlines.events_retention_config_inline import TeamEventsRetentionConfigInline
from posthog.admin.inlines.organization_member_for_related_inline import OrganizationMemberForRelatedInline
from posthog.admin.inlines.team_experiments_config_inline import TeamExperimentsConfigInline
from posthog.admin.inlines.team_marketing_analytics_config_inline import TeamMarketingAnalyticsConfigInline
@@ -37,8 +38,14 @@ from posthog.helpers.impersonation import is_impersonated
from posthog.llm.gateway_internal_client import AIGatewayInternalError, AIGatewayNotConfigured, add_credit, get_wallet
from posthog.models import Team
from posthog.models.activity_logging.activity_log import ActivityContextBase, ActivityLog, Detail, log_activity
+from posthog.models.events_retention_config import (
+ OrganizationEventsRetentionConfig,
+ TeamEventsRetentionConfig,
+ describe_months_range,
+)
from posthog.models.group_type_mapping import invalidate_group_types_cache
from posthog.models.remote_config import RemoteConfig
+from posthog.models.team.event_retention import should_enforce_events_retention
from posthog.models.team.team import DEPRECATED_ATTRS
from posthog.personhog_client.client import get_personhog_client
from posthog.personhog_client.converters import proto_group_type_mapping_to_dict
@@ -190,6 +197,7 @@ class TeamAdmin(admin.ModelAdmin):
"email_sending_suspension_actions",
"email_sending_tier_state",
"email_sending_tier_actions",
+ "events_retention_display",
]
exclude = DEPRECATED_ATTRS
@@ -197,6 +205,7 @@ class TeamAdmin(admin.ModelAdmin):
OrganizationMemberForRelatedInline,
TeamMarketingAnalyticsConfigInline,
TeamExperimentsConfigInline,
+ TeamEventsRetentionConfigInline,
]
def changeform_view(self, request, object_id=None, form_url="", extra_context=None):
@@ -296,6 +305,15 @@ class TeamAdmin(admin.ModelAdmin):
],
},
),
+ (
+ "Events retention",
+ {
+ "classes": ["collapse"],
+ "fields": [
+ "events_retention_display",
+ ],
+ },
+ ),
(
"Group type mappings",
{
@@ -584,6 +602,37 @@ class TeamAdmin(admin.ModelAdmin):
props.append("API_QUERIES_RATE_LIMIT_BYPASS")
return format_html("<span>{}</span>", ", ".join(props) or "-")
+ @admin.display(description="Events retention")
+ def events_retention_display(self, team: Team):
+ if not team.pk:
+ return "-"
+ team_months = (
+ TeamEventsRetentionConfig.objects.filter(team_id=team.pk)
+ .values_list("events_retention_months", flat=True)
+ .first()
+ )
+ org_config = OrganizationEventsRetentionConfig.objects.filter(organization_id=team.organization_id).first()
+ org_default = org_config.default_events_retention_months if org_config else None
+ if team_months is not None:
+ deletion = f"Deleted after {team_months} months, from the team setting."
+ elif org_default is not None:
+ deletion = f"Deleted after {org_default} months, from the organization default."
+ else:
+ deletion = "Never deleted. Neither the team nor the organization has a setting."
+ if org_config and (org_config.min_events_retention_months or org_config.max_events_retention_months):
+ allowed = describe_months_range(
+ org_config.min_events_retention_months, org_config.max_events_retention_months
+ )
+ deletion += f" The organization allows {allowed}."
+
+ hidden = (
+ "Older events are hidden from queries."
+ if should_enforce_events_retention(team.pk)
+ else "Older events are not hidden yet, because enforcement is off for this team."
+ )
+ billing = f"{team.event_retention_months} months from the billing plan. {hidden}"
+ return format_html("<div>{}</div><div>{}</div>", deletion, billing)
+
@admin.display(description="API token")
def api_token_display(self, team: Team):
if not team.pk:
diff --git a/posthog/admin/inlines/events_retention_config_inline.py b/posthog/admin/inlines/events_retention_config_inline.py
new file mode 100644
index 000000000000..9dd90e921774
--- /dev/null
+++ b/posthog/admin/inlines/events_retention_config_inline.py
@@ -0,0 +1,23 @@
+from django.contrib import admin
+
+from posthog.models.events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig
+
+
+class OrganizationEventsRetentionConfigInline(admin.StackedInline):
+ model = OrganizationEventsRetentionConfig
+ verbose_name = "Events retention"
+ verbose_name_plural = "Events retention"
+ extra = 1
+ max_num = 1
+ classes = ("collapse",)
+ fields = ["default_events_retention_months", "min_events_retention_months", "max_events_retention_months"]
+
+
+class TeamEventsRetentionConfigInline(admin.StackedInline):
+ model = TeamEventsRetentionConfig
+ verbose_name = "Events retention"
+ verbose_name_plural = "Events retention"
+ extra = 1
+ max_num = 1
+ classes = ("collapse",)
+ fields = ["events_retention_months"]
diff --git a/posthog/admin/inlines/team_inline.py b/posthog/admin/inlines/team_inline.py
index de7f1af3fe9c..a16a68588884 100644
--- a/posthog/admin/inlines/team_inline.py
+++ b/posthog/admin/inlines/team_inline.py
@@ -59,6 +59,7 @@ class TeamInline(TabularInlinePaginated):
"email_sending_suspension_actions",
"email_sending_tier_state",
"email_sending_tier_actions",
+ "events_retention_display",
)
] + ["displayed_name"]
diff --git a/posthog/migrations/1396_events_retention_config.py b/posthog/migrations/1396_events_retention_config.py
new file mode 100644
index 000000000000..d89349b3be81
--- /dev/null
+++ b/posthog/migrations/1396_events_retention_config.py
@@ -0,0 +1,149 @@
+# Generated by Django 5.2.18 on 2026-10-09 09:44
+
+import django.core.validators
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1395_id_jag_identity"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="OrganizationEventsRetentionConfig",
+ fields=[
+ (
+ "organization",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="+",
+ serialize=False,
+ to="posthog.organization",
+ ),
+ ),
+ (
+ "default_events_retention_months",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Applies to every team in the organization that has no value of its own. Leave empty to keep the events of those teams. Events are deleted one calendar month at a time. A month is deleted only when every event in it is older than this many months. For example, with 13 months, the events of March 2025 are deleted on the first monthly run after 1 May 2026.",
+ null=True,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "min_events_retention_months",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="The shortest retention a team in this organization may set.",
+ null=True,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ (
+ "max_events_retention_months",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="The longest retention a team in this organization may set.",
+ null=True,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("default_events_retention_months__isnull", True),
+ ("default_events_retention_months__gte", 1),
+ _connector="OR",
+ ),
+ models.Q(
+ ("min_events_retention_months__isnull", True),
+ ("min_events_retention_months__gte", 1),
+ _connector="OR",
+ ),
+ models.Q(
+ ("max_events_retention_months__isnull", True),
+ ("max_events_retention_months__gte", 1),
+ _connector="OR",
+ ),
+ ),
+ name="org_events_retention_months_positive",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(
+ models.Q(
+ ("min_events_retention_months__isnull", True),
+ ("default_events_retention_months__isnull", True),
+ (
+ "min_events_retention_months__lte",
+ models.F("default_events_retention_months"),
+ ),
+ _connector="OR",
+ ),
+ models.Q(
+ ("default_events_retention_months__isnull", True),
+ ("max_events_retention_months__isnull", True),
+ (
+ "default_events_retention_months__lte",
+ models.F("max_events_retention_months"),
+ ),
+ _connector="OR",
+ ),
+ models.Q(
+ ("min_events_retention_months__isnull", True),
+ ("max_events_retention_months__isnull", True),
+ (
+ "min_events_retention_months__lte",
+ models.F("max_events_retention_months"),
+ ),
+ _connector="OR",
+ ),
+ ),
+ name="org_events_retention_months_ordered",
+ ),
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="TeamEventsRetentionConfig",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "events_retention_months",
+ models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Overrides the organization's default and has to fall within the organization's range. Leave empty to use the organization's default. Events are kept only when neither this nor the organization's default is set. Events are deleted one calendar month at a time. A month is deleted only when every event in it is older than this many months. For example, with 13 months, the events of March 2025 are deleted on the first monthly run after 1 May 2026.",
+ null=True,
+ validators=[django.core.validators.MinValueValidator(1)],
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.CheckConstraint(
+ condition=models.Q(
+ ("events_retention_months__isnull", True),
+ ("events_retention_months__gte", 1),
+ _connector="OR",
+ ),
+ name="team_events_retention_months_positive",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 806fd35d63d3..766902e0dd64 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1395_id_jag_identity
+1396_events_retention_config
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index d17cc2e7c55e..ffb7ad09c3a7 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -18,6 +18,7 @@ from .data_color_theme import DataColorTheme
from .element import Element
from .element_group import ElementGroup
from .entity import Entity
+from .events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig
from .event.event import Event
from .event_buffer import EventBuffer
@@ -133,6 +134,7 @@ __all__ = [
"ObjectMediaPreview",
"Organization",
"OrganizationDomain",
+ "OrganizationEventsRetentionConfig",
"OrganizationMemberNotificationLock",
"OrganizationIntegration",
"OrganizationInvite",
@@ -171,6 +173,7 @@ __all__ = [
"Tag",
"TaggedItem",
"Team",
+ "TeamEventsRetentionConfig",
"TeamRevenueAnalyticsConfig",
"TeamMarketingAnalyticsConfig",
"EventIngestionRestrictionConfig",
diff --git a/posthog/models/events_retention_config.py b/posthog/models/events_retention_config.py
new file mode 100644
index 000000000000..8f08464698f8
--- /dev/null
+++ b/posthog/models/events_retention_config.py
@@ -0,0 +1,187 @@
+from uuid import UUID
+
+from django.core.exceptions import ValidationError
+from django.core.validators import MinValueValidator
+from django.db import connection, models
+
+from posthog.dataclasses import frozen
+from posthog.models.team import Team
+
+RETENTION_MONTHS_HELP = (
+ "Events are deleted one calendar month at a time. A month is deleted only when every event in it is "
+ "older than this many months. For example, with 13 months, the events of March 2025 are deleted on "
+ "the first monthly run after 1 May 2026."
+)
+
+
+def _months_field(help_text: str) -> models.PositiveSmallIntegerField:
+ return models.PositiveSmallIntegerField(
+ null=True, blank=True, validators=[MinValueValidator(1)], help_text=help_text
+ )
+
+
+class OrganizationEventsRetentionConfig(models.Model):
+ """Staff-only events deletion settings for an organization. No customer-facing serializer may write this model."""
+
+ # db_constraint=False: a real FK constraint would take a SHARE ROW EXCLUSIVE
+ # lock on posthog_organization (a hot table) while migrating.
+ organization = models.OneToOneField(
+ "posthog.Organization", on_delete=models.CASCADE, primary_key=True, db_constraint=False, related_name="+"
+ )
+ default_events_retention_months = _months_field(
+ "Applies to every team in the organization that has no value of its own. Leave empty to keep the events "
+ f"of those teams. {RETENTION_MONTHS_HELP}"
+ )
+ min_events_retention_months = _months_field("The shortest retention a team in this organization may set.")
+ max_events_retention_months = _months_field("The longest retention a team in this organization may set.")
+
+ class Meta:
+ constraints = [
+ models.CheckConstraint(
+ name="org_events_retention_months_positive",
+ condition=(
+ (
+ models.Q(default_events_retention_months__isnull=True)
+ | models.Q(default_events_retention_months__gte=1)
+ )
+ & (
+ models.Q(min_events_retention_months__isnull=True)
+ | models.Q(min_events_retention_months__gte=1)
+ )
+ & (
+ models.Q(max_events_retention_months__isnull=True)
+ | models.Q(max_events_retention_months__gte=1)
+ )
+ ),
+ ),
+ models.CheckConstraint(
+ name="org_events_retention_months_ordered",
+ condition=(
+ (
+ models.Q(min_events_retention_months__isnull=True)
+ | models.Q(default_events_retention_months__isnull=True)
+ | models.Q(min_events_retention_months__lte=models.F("default_events_retention_months"))
+ )
+ & (
+ models.Q(default_events_retention_months__isnull=True)
+ | models.Q(max_events_retention_months__isnull=True)
+ | models.Q(default_events_retention_months__lte=models.F("max_events_retention_months"))
+ )
+ & (
+ models.Q(min_events_retention_months__isnull=True)
+ | models.Q(max_events_retention_months__isnull=True)
+ | models.Q(min_events_retention_months__lte=models.F("max_events_retention_months"))
+ )
+ ),
+ ),
+ ]
+
+ def clean(self) -> None:
+ _lock_organization_retention(self.organization_id)
+ low, default, high = (
+ self.min_events_retention_months,
+ self.default_events_retention_months,
+ self.max_events_retention_months,
+ )
+ if low is not None and high is not None and low > high:
+ raise ValidationError({"min_events_retention_months": "The minimum can't be more than the maximum."})
+ if default is not None and not _within(default, low, high):
+ raise ValidationError(
+ {"default_events_retention_months": f"The default has to be {describe_months_range(low, high)}."}
+ )
+
+ out_of_range = sorted(
+ team_id
+ for team_id, months in TeamEventsRetentionConfig.objects.filter(
+ team__organization_id=self.organization_id, events_retention_months__isnull=False
+ ).values_list("team_id", "events_retention_months")
+ if months is not None and not _within(months, low, high)
+ )
+ if out_of_range:
+ raise ValidationError(
+ f"Teams {', '.join(map(str, out_of_range))} have a retention that isn't {describe_months_range(low, high)}. "
+ "Change those teams first, then save this range."
+ )
+
+
+class TeamEventsRetentionConfig(models.Model):
+ """Staff-only events deletion setting for a team. No customer-facing serializer may write this model."""
+
+ team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True, db_constraint=False)
+ events_retention_months = _months_field(
+ "Overrides the organization's default and has to fall within the organization's range. Leave empty to use "
+ "the organization's default. Events are kept only when neither this nor the organization's default is set. "
+ f"{RETENTION_MONTHS_HELP}"
+ )
+
+ class Meta:
+ constraints = [
+ models.CheckConstraint(
+ name="team_events_retention_months_positive",
+ condition=models.Q(events_retention_months__isnull=True) | models.Q(events_retention_months__gte=1),
+ )
+ ]
+
+ def clean(self) -> None:
+ if self.events_retention_months is None:
+ return
+ _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
+ low, high = org_config.min_events_retention_months, org_config.max_events_retention_months
+ if not _within(self.events_retention_months, low, high):
+ raise ValidationError(
+ {"events_retention_months": f"The organization allows {describe_months_range(low, high)}."}
+ )
+
+
+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.
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"events-retention:{organization_id}"])
+
+
+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 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"
+ if low is not None:
+ return f"at least {low} months"
+ return f"at most {high} months"
+
+
+@frozen
+class TeamEventsRetention:
+ organization_id: UUID
+ team_id: int
+ months: int
+
+
+def effective_events_retention() -> list[TeamEventsRetention]:
+ """Every team with an effective events retention: its own value, else its organization's default."""
+ team_table = Team._meta.db_table
+ team_config_table = TeamEventsRetentionConfig._meta.db_table
+ org_config_table = OrganizationEventsRetentionConfig._meta.db_table
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f"""
+ SELECT team.organization_id,
+ team.id,
+ COALESCE(team_config.events_retention_months, org_config.default_events_retention_months)
+ FROM {team_table} AS team
+ LEFT JOIN {team_config_table} AS team_config ON team_config.team_id = team.id
+ LEFT JOIN {org_config_table} AS org_config ON org_config.organization_id = team.organization_id
+ WHERE COALESCE(team_config.events_retention_months, org_config.default_events_retention_months) IS NOT NULL
+ ORDER BY team.organization_id, team.id
+ """
+ )
+ return [
+ TeamEventsRetention(organization_id=organization_id, team_id=team_id, months=months)
+ for organization_id, team_id, months in cursor.fetchall()
+ ]
diff --git a/posthog/models/test/test_events_retention_config.py b/posthog/models/test/test_events_retention_config.py
new file mode 100644
index 000000000000..ba6887ef9d82
--- /dev/null
+++ b/posthog/models/test/test_events_retention_config.py
@@ -0,0 +1,96 @@
+from posthog.test.base import BaseTest
+
+from django.core.exceptions import ValidationError
+
+from parameterized import parameterized
+
+from posthog.models.events_retention_config import (
+ OrganizationEventsRetentionConfig,
+ TeamEventsRetentionConfig,
+ effective_events_retention,
+)
+from posthog.models.organization import Organization
+from posthog.models.team import Team
+
+
+class TestEventsRetentionConfig(BaseTest):
+ @parameterized.expand(
+ [
+ ("inside_range", 12, 24, 18, True),
+ ("on_lower_bound", 12, 24, 12, True),
+ ("below_range", 12, 24, 6, False),
+ ("above_range", 12, 24, 36, False),
+ ("no_org_range", None, None, 1, True),
+ ("only_min", 12, None, 120, True),
+ ]
+ )
+ def test_team_value_has_to_fall_in_org_range(
+ self, _name: str, low: int | None, high: int | None, months: int, valid: bool
+ ) -> None:
+ OrganizationEventsRetentionConfig.objects.create(
+ organization=self.organization, min_events_retention_months=low, max_events_retention_months=high
+ )
+ config = TeamEventsRetentionConfig(team=self.team, events_retention_months=months)
+
+ if valid:
+ config.full_clean()
+ else:
+ with self.assertRaises(ValidationError) as error:
+ config.full_clean()
+ assert "events_retention_months" in error.exception.message_dict
+
+ @parameterized.expand(
+ [
+ ("excludes_team_below", 13, 24, False),
+ ("excludes_team_above", 6, 12, False),
+ ("includes_team", 12, 24, True),
+ ]
+ )
+ def test_org_range_has_to_cover_existing_team_values(self, _name: str, low: int, high: int, valid: bool) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ TeamEventsRetentionConfig.objects.create(team=self.team, events_retention_months=12)
+ TeamEventsRetentionConfig.objects.create(team=other_team, events_retention_months=24)
+ config = OrganizationEventsRetentionConfig(
+ organization=self.organization, min_events_retention_months=low, max_events_retention_months=high
+ )
+
+ if valid:
+ config.full_clean()
+ else:
+ with self.assertRaises(ValidationError) as error:
+ config.full_clean()
+ assert "Change those teams first" in str(error.exception)
+
+ def test_org_default_has_to_fall_in_org_range(self) -> None:
+ config = OrganizationEventsRetentionConfig(
+ organization=self.organization,
+ default_events_retention_months=6,
+ min_events_retention_months=12,
+ max_events_retention_months=24,
+ )
+
+ with self.assertRaises(ValidationError) as error:
+ config.full_clean()
+ assert "default_events_retention_months" in error.exception.message_dict
+
+ def test_effective_retention_prefers_the_team_value_over_the_org_default(self) -> None:
+ OrganizationEventsRetentionConfig.objects.create(
+ organization=self.organization, default_events_retention_months=13
+ )
+ overrides = Team.objects.create(organization=self.organization, name="Overrides")
+ TeamEventsRetentionConfig.objects.create(team=overrides, events_retention_months=18)
+ cleared = Team.objects.create(organization=self.organization, name="Cleared")
+ TeamEventsRetentionConfig.objects.create(team=cleared, events_retention_months=None)
+ other_org = Organization.objects.create(name="No default")
+ Team.objects.create(organization=other_org, name="Keeps everything")
+ own_value = Team.objects.create(organization=other_org, name="Own value")
+ TeamEventsRetentionConfig.objects.create(team=own_value, events_retention_months=24)
+
+ retention = {(item.organization_id, item.team_id): item.months for item in effective_events_retention()}
+
+ assert retention == {
+ (self.organization.id, self.team.id): 13,
+ (self.organization.id, overrides.id): 18,
+ (self.organization.id, cleared.id): 13,
+ (other_org.id, own_value.id): 24,
+ }