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(logs): add retention rules model and API (#73827)

Frank Hamand793eca79fa31
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index b3768d8ca814..515a12a0abbd 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -192,6 +192,7 @@ rules:
|LogsAlertConfiguration
|LogsExclusionRule
|LogsMetricRule
+ |LogsRetentionRule
|LogsView
|Loop
|LoopFire
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index b050a84e33cc..32c3231ccf61 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -89,6 +89,7 @@ ActivityScope = Literal[
"Log",
"LogsAlertConfiguration",
"LogsExclusionRule",
+ "LogsRetentionRule",
"DashboardWidget",
"ProductTour",
"Ticket",
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index c4bcc388e16d..258aee50cd7d 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -113,6 +113,7 @@ Link
LiveDebuggerBreakpoint
LogsAlertConfiguration
LogsExclusionRule
+LogsRetentionRule
LogsView
MCPAnalyticsSubmission
MCPServerInstallation
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 4aa9b631bfe0..b0930e4c8b6a 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -34,6 +34,7 @@ model_activity:products.exports.backend.models.subscription.log_subscription_act
model_activity:products.feature_flags.backend.activity_logging.handle_feature_flag_change
model_activity:products.legal_documents.backend.signals.handle_legal_document_change
model_activity:products.logs.backend.activity_logging.handle_logs_alert_activity
+model_activity:products.logs.backend.activity_logging.handle_logs_retention_rule_activity
model_activity:products.logs.backend.activity_logging.handle_logs_sampling_rule_activity
model_activity:products.managed_migrations.backend.activity_logging.handle_batch_import_change
model_activity:products.signals.backend.activity_logging.handle_signal_scout_config_change
diff --git a/products/logs/backend/activity_logging.py b/products/logs/backend/activity_logging.py
index 55e7ad11a7ef..93cd454bf3b5 100644
--- a/products/logs/backend/activity_logging.py
+++ b/products/logs/backend/activity_logging.py
@@ -8,7 +8,7 @@ from posthog.models.activity_logging.activity_log import ActivityScope, Detail,
from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.user import User
-from products.logs.backend.models import LogsAlertConfiguration, LogsExclusionRule
+from products.logs.backend.models import LogsAlertConfiguration, LogsExclusionRule, LogsRetentionRule
@mutable_receiver(model_activity_signal, sender=LogsAlertConfiguration)
@@ -65,3 +65,32 @@ def handle_logs_sampling_rule_activity(
name=instance.name,
),
)
+
+
+@mutable_receiver(model_activity_signal, sender=LogsRetentionRule)
+def handle_logs_retention_rule_activity(
+ sender: Any,
+ scope: str,
+ before_update: LogsRetentionRule | None,
+ after_update: LogsRetentionRule | None,
+ activity: str,
+ user: User | None,
+ was_impersonated: bool = False,
+ **kwargs: Any,
+) -> None:
+ instance = after_update or before_update
+ if instance is None:
+ return
+ log_activity(
+ organization_id=instance.team.organization_id,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope=scope,
+ activity=activity,
+ detail=Detail(
+ changes=changes_between(cast(ActivityScope, scope), previous=before_update, current=after_update),
+ name=instance.name,
+ ),
+ )
diff --git a/products/logs/backend/migrations/0020_logsretentionrule.py b/products/logs/backend/migrations/0020_logsretentionrule.py
new file mode 100644
index 000000000000..4115ba13a86d
--- /dev/null
+++ b/products/logs/backend/migrations/0020_logsretentionrule.py
@@ -0,0 +1,72 @@
+# Generated by Django 5.2.14 on 2026-07-15 15:12
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0019_backfill_logs_distinct_id_attribute_keys"),
+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="LogsRetentionRule",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("enabled", models.BooleanField(default=False)),
+ (
+ "priority",
+ models.PositiveIntegerField(
+ default=0,
+ help_text="Lower values run first; first matching rule wins. Ties use created_at ascending (same as ingestion query order).",
+ ),
+ ),
+ ("config", models.JSONField(default=dict)),
+ ("version", models.PositiveIntegerField(default=1)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "logs_logsretentionrule",
+ "indexes": [
+ models.Index(
+ fields=["team_id", "enabled", "priority"],
+ name="logs_retention_team_en_pr_idx",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index 57d22b681823..82796b54b219 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0019_backfill_logs_distinct_id_attribute_keys
+0020_logsretentionrule
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index 55365f47c590..5f8579732146 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -401,3 +401,39 @@ class LogsExclusionRule(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields
def __str__(self) -> str:
return f"{self.name} (team={self.team_id})"
+
+
+class LogsRetentionRule(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):
+ """User-defined rules that override how long matching log lines are retained (evaluated in ingestion
+ when enabled). First matching rule by (priority, created_at) wins; logs matching no rule keep the
+ team's default retention (`Team.logs_settings.retention_days`)."""
+
+ # Plain team FK — like LogsExclusionRule and TeamLogsConfig, retention rules are per-environment,
+ # so this deliberately does not use TeamScopedRootMixin (whose canonical-team save() rewrite would
+ # let one child environment mutate a sibling's rules). Tenant isolation is enforced at the API layer
+ # via safely_get_queryset filtering on team_id; the model is tracked in scoping/baseline_unmigrated.txt.
+ # db_constraint=False on the hot-table FKs (team, created_by) keeps the CreateModel migration
+ # lock-free — creating a real FK constraint would take a SHARE ROW EXCLUSIVE lock on the parent.
+ # Enforcement stays at the ORM level (cascade/set-null run through the Django collector).
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ name = models.CharField(max_length=255)
+ enabled = models.BooleanField(default=False)
+ priority = models.PositiveIntegerField(
+ default=0,
+ help_text="Lower values run first; first matching rule wins. Ties use created_at ascending (same as ingestion query order).",
+ )
+ # {"filter_group": <PropertyGroupFilter>, "retention_days": <14|30|90>}
+ config = models.JSONField(default=dict)
+ version = models.PositiveIntegerField(default=1)
+
+ class Meta:
+ db_table = "logs_logsretentionrule"
+ indexes = [
+ models.Index(fields=["team_id", "enabled", "priority"], name="logs_retention_team_en_pr_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.name} (team={self.team_id})"
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index b3a38668f619..66b22adde5ae 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -71,6 +71,7 @@ from products.logs.backend.patterns_query_runner import PatternsQueryRunner
from products.logs.backend.presentation.views.alerts_api import LogsAlertViewSet
from products.logs.backend.presentation.views.explain import LogExplainViewSet
from products.logs.backend.presentation.views.metric_rules_api import LogsMetricRuleViewSet
+from products.logs.backend.presentation.views.retention_api import LogsRetentionRuleViewSet
from products.logs.backend.presentation.views.sampling_api import LogsSamplingRuleViewSet
from products.logs.backend.presentation.views.views_api import LogsViewViewSet
from products.logs.backend.services_query_runner import ServicesQueryRunner
@@ -81,6 +82,7 @@ __all__ = [
"LogExplainViewSet",
"LogsAlertViewSet",
"LogsMetricRuleViewSet",
+ "LogsRetentionRuleViewSet",
"LogsSamplingRuleViewSet",
"LogsViewViewSet",
]
diff --git a/products/logs/backend/presentation/views/retention_api.py b/products/logs/backend/presentation/views/retention_api.py
new file mode 100644
index 000000000000..f162552aaf74
--- /dev/null
+++ b/products/logs/backend/presentation/views/retention_api.py
@@ -0,0 +1,258 @@
+from __future__ import annotations
+
+from typing import Any, cast
+
+from django.db import transaction
+from django.db.models import F, Max, QuerySet
+
+from drf_spectacular.utils import extend_schema
+from pydantic import ValidationError as PydanticValidationError
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import PermissionDenied, ValidationError
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.schema import PropertyGroupFilter
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS
+from posthog.event_usage import report_user_action
+from posthog.models.user import User
+from posthog.permissions import PostHogFeatureFlagPermission
+
+from products.logs.backend.models import LogsRetentionRule
+from products.logs.backend.presentation.filter_group_validation import (
+ MAX_FILTER_GROUP_DEPTH,
+ MAX_FILTER_GROUP_LEAF_VALUES,
+ MAX_FILTER_GROUP_NODES,
+ MAX_FILTER_GROUP_VALUE_LENGTH,
+ filter_group_depth,
+ filter_group_has_oversized_value,
+ filter_group_leaf_value_count,
+ filter_group_node_count,
+)
+
+# Retention tiers a rule may assign. Derived from the same source as the team-wide setting in
+# `TeamSerializer` (`posthog/api/team.py`): 14 is the always-available default, and every other
+# tier must have an entitlement feature in `LOGS_RETENTION_FEATURES_BY_DAYS` (currently just 30).
+# Deriving it keeps rules in lockstep with the team-wide setting — a per-log rule can never grant a
+# tier the org couldn't set team-wide, and a new tier (e.g. 90) becomes available here the moment it
+# gets an entitlement mapping.
+VALID_RETENTION_DAYS = {14} | set(LOGS_RETENTION_FEATURES_BY_DAYS.keys())
+
+
+class LogsRetentionRuleSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this retention rule.")
+ name = serializers.CharField(max_length=255, help_text="User-visible label for this rule.")
+ enabled = serializers.BooleanField(
+ default=False,
+ help_text="When false, the rule is ignored by ingestion and listing UIs that show active rules only.",
+ )
+ priority = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=0,
+ help_text="Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.",
+ )
+ config = serializers.JSONField(
+ help_text=(
+ "Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are "
+ "kept; must be a tier the organization is entitled to, same as the team-wide Logs retention "
+ "setting) and `filter_group` (PropertyGroupFilter shape — an AND/OR tree of property "
+ "predicates evaluated per record to decide which logs this rule matches). "
+ 'Example: `{"retention_days":30,"filter_group":{"type":"AND","values":[{"type":"AND",'
+ '"values":[{"key":"service.name","operator":"exact","value":"api"}]}]}}`. Logs matching no '
+ "enabled rule keep the environment's default retention."
+ )
+ )
+ version = serializers.IntegerField(
+ read_only=True, help_text="Incremented on each update for worker cache coherency."
+ )
+ created_by: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField(read_only=True) # ty: ignore[invalid-assignment]
+
+ class Meta:
+ model = LogsRetentionRule
+ fields = [
+ "id",
+ "name",
+ "enabled",
+ "priority",
+ "config",
+ "version",
+ "created_by",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = ["id", "version", "created_by", "created_at", "updated_at"]
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ attrs = super().validate(attrs)
+ config = attrs.get("config")
+ if config is None and self.instance is not None:
+ config = self.instance.config
+ if not isinstance(config, dict):
+ raise ValidationError({"config": "config must be a JSON object."})
+
+ retention_days = config.get("retention_days")
+ # bool is an int subclass — reject it explicitly so `true`/`false` don't slip through.
+ if isinstance(retention_days, bool) or not isinstance(retention_days, int):
+ raise ValidationError({"config": {"retention_days": "Must be an integer."}})
+ if retention_days not in VALID_RETENTION_DAYS:
+ raise ValidationError(
+ {"config": {"retention_days": f"Must be one of {sorted(VALID_RETENTION_DAYS)} days."}}
+ )
+ # Gate paid tiers on the org entitlement, mirroring TeamSerializer.validate_logs_settings —
+ # otherwise a Logs editor could grant a per-log retention tier the org can't set team-wide.
+ required_feature = LOGS_RETENTION_FEATURES_BY_DAYS.get(retention_days)
+ if required_feature is not None:
+ get_organization = self.context.get("get_organization")
+ organization = get_organization() if callable(get_organization) else None
+ if organization is None or not organization.is_feature_available(required_feature):
+ raise PermissionDenied(
+ f"This organization does not have permission to set Logs retention to {retention_days} days."
+ )
+
+ self._validate_filter_group(config.get("filter_group"))
+ return attrs
+
+ def _validate_filter_group(self, filter_group: Any) -> None:
+ # A retention rule with no filter_group would match every log, silently overriding the
+ # team default for all traffic — require an explicit selector.
+ if filter_group is None:
+ raise ValidationError({"config": {"filter_group": "A retention rule requires a filter_group."}})
+ # Validate shape against PropertyGroupFilter so malformed payloads are rejected at write time
+ # rather than flowing through to the ingestion worker. Mirrors sampling_api / alerts_api.
+ try:
+ PropertyGroupFilter.model_validate(filter_group)
+ except PydanticValidationError as e:
+ raise ValidationError({"config": {"filter_group": f"Invalid filter_group shape: {e.errors()[0]['msg']}"}})
+ # Bound depth and total node count — the Node ingestion worker recurses per record over this
+ # tree, so an adversarially deep or wide group is a stack-overflow + CPU footgun on every log
+ # line. Matches MAX_FILTER_GROUP_DEPTH / MAX_FILTER_GROUP_NODES shared with the sampling rules.
+ if filter_group_depth(filter_group) > MAX_FILTER_GROUP_DEPTH:
+ raise ValidationError(
+ {"config": {"filter_group": f"filter_group is nested too deeply (max depth {MAX_FILTER_GROUP_DEPTH})."}}
+ )
+ if filter_group_node_count(filter_group) > MAX_FILTER_GROUP_NODES:
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group has too many nodes (max {MAX_FILTER_GROUP_NODES} groups + leaves)."
+ }
+ }
+ )
+ # A single leaf can smuggle a huge value array or multi-megabyte string while counting as one
+ # node — the ingestion matcher would then scan that per record. Bound total leaf values and
+ # per-value length, matching the metric-rules validator.
+ if filter_group_leaf_value_count(filter_group) > MAX_FILTER_GROUP_LEAF_VALUES:
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group has too many filter values (max {MAX_FILTER_GROUP_LEAF_VALUES} across all filters)."
+ }
+ }
+ )
+ if filter_group_has_oversized_value(filter_group):
+ raise ValidationError(
+ {
+ "config": {
+ "filter_group": f"filter_group contains a value longer than {MAX_FILTER_GROUP_VALUE_LENGTH} characters."
+ }
+ }
+ )
+
+
+class LogsRetentionRuleReorderSerializer(serializers.Serializer):
+ ordered_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ help_text="Rule IDs in the desired evaluation order (first element is highest priority / lowest order index).",
+ )
+
+
+class LogsRetentionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "logs"
+ queryset = LogsRetentionRule.objects.all().order_by("priority", "created_at")
+ serializer_class = LogsRetentionRuleSerializer
+ lookup_field = "id"
+ posthog_feature_flag = "logs-settings-retention-rules"
+ permission_classes = [PostHogFeatureFlagPermission]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ return queryset.filter(team_id=self.team_id)
+
+ def perform_create(self, serializer: serializers.BaseSerializer) -> None:
+ s = cast(LogsRetentionRuleSerializer, serializer)
+ user = cast(User, self.request.user)
+ # `or -1` would misfire when the current max is 0 (0 is falsy), so check for None explicitly.
+ max_priority = LogsRetentionRule.objects.filter(team_id=self.team_id).aggregate(m=Max("priority"))["m"]
+ raw_priority = s.validated_data.pop("priority", None)
+ priority = int(raw_priority) if raw_priority is not None else (0 if max_priority is None else max_priority + 1)
+ instance = s.save(
+ team_id=self.team_id,
+ created_by=user if user.is_authenticated else None,
+ priority=priority,
+ version=1,
+ )
+ report_user_action(
+ user,
+ "logs retention rule created",
+ {"rule_id": str(instance.id)},
+ team=self.team,
+ request=self.request,
+ )
+
+ def perform_update(self, serializer: serializers.BaseSerializer) -> None:
+ s = cast(LogsRetentionRuleSerializer, serializer)
+ user = cast(User, self.request.user)
+ # priority is managed via the reorder action; a null in an update payload would reach the
+ # non-nullable column and raise a 500. Drop it so the stored value is preserved.
+ if s.validated_data.get("priority") is None:
+ s.validated_data.pop("priority", None)
+ instance = cast(LogsRetentionRule, s.save())
+ LogsRetentionRule.objects.filter(pk=instance.pk, team_id=self.team_id).update(version=F("version") + 1)
+ instance.refresh_from_db(fields=["version", "updated_at"])
+ report_user_action(
+ user,
+ "logs retention rule updated",
+ {"rule_id": str(instance.id)},
+ team=self.team,
+ request=self.request,
+ )
+
+ def perform_destroy(self, instance: LogsRetentionRule) -> None:
+ user = cast(User, self.request.user)
+ report_user_action(
+ user,
+ "logs retention rule deleted",
+ {"rule_id": str(instance.id)},
+ team=self.team,
+ request=self.request,
+ )
+ super().perform_destroy(instance)
+
+ @extend_schema(
+ request=LogsRetentionRuleReorderSerializer,
+ responses={200: LogsRetentionRuleSerializer(many=True)},
+ description="Atomically reassign priorities so the given ID order maps to ascending priorities (0..n-1).",
+ )
+ @action(detail=False, methods=["post"], url_path="reorder")
+ def reorder(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = LogsRetentionRuleReorderSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ ordered_ids = serializer.validated_data["ordered_ids"]
+ with transaction.atomic():
+ # Validate inside the transaction (and lock the rows) so a concurrent create/delete
+ # can't invalidate the check between validation and the priority writes (TOCTOU).
+ team_rule_ids = set(
+ LogsRetentionRule.objects.select_for_update().filter(team_id=self.team_id).values_list("id", flat=True)
+ )
+ if set(ordered_ids) != team_rule_ids or len(ordered_ids) != len(team_rule_ids):
+ raise ValidationError("ordered_ids must list every retention rule for this team exactly once.")
+ for index, rid in enumerate(ordered_ids):
+ LogsRetentionRule.objects.filter(id=rid, team_id=self.team_id).update(
+ priority=index,
+ version=F("version") + 1,
+ )
+ qs = self.safely_get_queryset(LogsRetentionRule.objects.all()).order_by("priority", "created_at")
+ return Response(LogsRetentionRuleSerializer(qs, many=True).data, status=status.HTTP_200_OK)
diff --git a/products/logs/backend/routes.py b/products/logs/backend/routes.py
index 9bc8e7ce440d..b557a37e6ba6 100644
--- a/products/logs/backend/routes.py
+++ b/products/logs/backend/routes.py
@@ -9,6 +9,9 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"logs/sampling_rules", logs.LogsSamplingRuleViewSet, "project_logs_sampling_rules", ["team_id"]
)
+ routers.projects.register(
+ r"logs/retention_rules", logs.LogsRetentionRuleViewSet, "project_logs_retention_rules", ["team_id"]
+ )
routers.projects.register(
r"logs/metric_rules", logs.LogsMetricRuleViewSet, "project_logs_metric_rules", ["team_id"]
)
diff --git a/products/logs/backend/test/test_retention_rules_api.py b/products/logs/backend/test/test_retention_rules_api.py
new file mode 100644
index 000000000000..aed5f59e45c0
--- /dev/null
+++ b/products/logs/backend/test/test_retention_rules_api.py
@@ -0,0 +1,148 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.constants import AvailableFeature
+
+from products.logs.backend.models import LogsRetentionRule
+
+VALID_FILTER_GROUP = {"type": "AND", "values": [{"type": "AND", "values": []}]}
+
+
+class TestLogsRetentionRulesAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.base_url = f"/api/projects/{self.team.pk}/logs/retention_rules/"
+ self._ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
+ self._ff_patcher.start()
+ self.addCleanup(self._ff_patcher.stop)
+
+ def _grant_30d_retention(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.LOGS_RETENTION_30D, "name": AvailableFeature.LOGS_RETENTION_30D}
+ ]
+ self.organization.save()
+
+ def _payload(self, **overrides):
+ # 14 days is the always-available free tier, so the generic CRUD tests need no entitlement.
+ data = {
+ "name": "Keep api logs longer",
+ "config": {"retention_days": 14, "filter_group": VALID_FILTER_GROUP},
+ }
+ data.update(overrides)
+ return data
+
+ @patch("products.logs.backend.presentation.views.retention_api.report_user_action")
+ def test_create_defaults_disabled_and_priority(self, mock_report):
+ response = self.client.post(self.base_url, self._payload(), format="json")
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ body = response.json()
+ assert body["enabled"] is False
+ assert body["priority"] == 0
+ assert body["version"] == 1
+ assert body["config"]["retention_days"] == 14
+ mock_report.assert_called_once()
+
+ def test_paid_tier_requires_org_entitlement(self):
+ # 30 days is entitlement-gated; without the feature the org can't set it via a rule either.
+ denied = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 30, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ )
+ assert denied.status_code == status.HTTP_403_FORBIDDEN, denied.json()
+ assert LogsRetentionRule.objects.count() == 0
+
+ self._grant_30d_retention()
+ allowed = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 30, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ )
+ assert allowed.status_code == status.HTTP_201_CREATED, allowed.json()
+ assert allowed.json()["config"]["retention_days"] == 30
+
+ def test_list_scoped_to_team(self):
+ self.client.post(self.base_url, self._payload(name="mine"), format="json")
+ other_team = self.create_team_with_organization(organization=self.organization)
+ LogsRetentionRule.objects.create(
+ team_id=other_team.id,
+ name="other",
+ enabled=False,
+ priority=0,
+ config={"retention_days": 30, "filter_group": VALID_FILTER_GROUP},
+ )
+
+ response = self.client.get(self.base_url)
+ assert response.status_code == status.HTTP_200_OK
+ results = response.json()["results"]
+ assert len(results) == 1
+ assert results[0]["name"] == "mine"
+
+ def test_reorder(self):
+ a = self.client.post(self.base_url, self._payload(name="a"), format="json").json()
+ b = self.client.post(self.base_url, self._payload(name="b"), format="json").json()
+
+ r = self.client.post(f"{self.base_url}reorder/", {"ordered_ids": [b["id"], a["id"]]}, format="json")
+ assert r.status_code == status.HTTP_200_OK, r.json()
+ ordered = r.json()
+ assert ordered[0]["id"] == b["id"] and ordered[0]["priority"] == 0
+ assert ordered[1]["id"] == a["id"] and ordered[1]["priority"] == 1
+
+ def test_append_priority_when_existing_max_is_zero(self):
+ first = self.client.post(self.base_url, self._payload(name="first"), format="json").json()
+ assert first["priority"] == 0
+ second = self.client.post(self.base_url, self._payload(name="second"), format="json").json()
+ # Guards the `max or -1` footgun: max priority 0 is falsy, so a second rule must still
+ # append at 1 rather than collide at 0.
+ assert second["priority"] == 1
+
+ def test_update_with_null_priority_does_not_error(self):
+ rule = self.client.post(self.base_url, self._payload(name="r"), format="json").json()
+ response = self.client.patch(
+ f"{self.base_url}{rule['id']}/",
+ {"name": "renamed", "priority": None},
+ format="json",
+ )
+ # A null priority must not reach the non-nullable column (would 500); the stored value stays.
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["priority"] == 0
+
+ @parameterized.expand(
+ [
+ ("non_tier_value", {"retention_days": 45, "filter_group": VALID_FILTER_GROUP}),
+ ("ninety_no_longer_a_tier", {"retention_days": 90, "filter_group": VALID_FILTER_GROUP}),
+ ("boolean_masquerading_as_int", {"retention_days": True, "filter_group": VALID_FILTER_GROUP}),
+ ("missing_retention_days", {"filter_group": VALID_FILTER_GROUP}),
+ ("missing_filter_group", {"retention_days": 14}),
+ ("malformed_filter_group", {"retention_days": 14, "filter_group": ["not", "an", "object"]}),
+ (
+ "oversized_leaf_value",
+ {
+ "retention_days": 14,
+ "filter_group": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": "service.name",
+ "type": "log_resource_attribute",
+ "operator": "exact",
+ "value": "x" * 2000,
+ }
+ ],
+ }
+ ],
+ },
+ },
+ ),
+ ]
+ )
+ def test_invalid_config_rejected(self, _name, config):
+ response = self.client.post(self.base_url, self._payload(config=config), format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert LogsRetentionRule.objects.count() == 0
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 08c16ccfa575..084c7a204c14 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1535,6 +1535,72 @@ export interface _LogsQueryResponseApi {
columns?: string[] | null
}
+export interface LogsRetentionRuleApi {
+ /** Unique identifier for this retention rule. */
+ readonly id: string
+ /**
+ * User-visible label for this rule.
+ * @maxLength 255
+ */
+ name: string
+ /** When false, the rule is ignored by ingestion and listing UIs that show active rules only. */
+ enabled?: boolean
+ /**
+ * Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.
+ * @minimum 0
+ * @nullable
+ */
+ priority?: number | null
+ /** Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{"retention_days":30,"filter_group":{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}}`. Logs matching no enabled rule keep the environment's default retention. */
+ config: unknown
+ /** Incremented on each update for worker cache coherency. */
+ readonly version: number
+ readonly created_by: number
+ readonly created_at: string
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedLogsRetentionRuleListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: LogsRetentionRuleApi[]
+}
+
+export interface PatchedLogsRetentionRuleApi {
+ /** Unique identifier for this retention rule. */
+ readonly id?: string
+ /**
+ * User-visible label for this rule.
+ * @maxLength 255
+ */
+ name?: string
+ /** When false, the rule is ignored by ingestion and listing UIs that show active rules only. */
+ enabled?: boolean
+ /**
+ * Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.
+ * @minimum 0
+ * @nullable
+ */
+ priority?: number | null
+ /** Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{"retention_days":30,"filter_group":{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}}`. Logs matching no enabled rule keep the environment's default retention. */
+ config?: unknown
+ /** Incremented on each update for worker cache coherency. */
+ readonly version?: number
+ readonly created_by?: number
+ readonly created_at?: string
+ /** @nullable */
+ readonly updated_at?: string | null
+}
+
+export interface LogsRetentionRuleReorderApi {
+ /** Rule IDs in the desired evaluation order (first element is highest priority / lowest order index). */
+ ordered_ids: string[]
+}
+
/**
* * `severity_sampling` - Severity-based reduction
* * `path_drop` - Path exclusion
@@ -2000,6 +2066,28 @@ export type LogsMetricRulesListParams = {
offset?: number
}
+export type LogsRetentionRulesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type LogsRetentionRulesReorderCreateParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type LogsSamplingRulesListParams = {
/**
* Number of results to return per page.
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index ac3effb74381..c1b479ff35df 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -23,6 +23,10 @@ import type {
LogsHasLogsRetrieve200,
LogsMetricRuleApi,
LogsMetricRulesListParams,
+ LogsRetentionRuleApi,
+ LogsRetentionRuleReorderApi,
+ LogsRetentionRulesListParams,
+ LogsRetentionRulesReorderCreateParams,
LogsSamplingRuleApi,
LogsSamplingRuleReorderApi,
LogsSamplingRuleSimulateResponseApi,
@@ -34,10 +38,12 @@ import type {
PaginatedLogsAlertConfigurationListApi,
PaginatedLogsAlertEventListApi,
PaginatedLogsMetricRuleListApi,
+ PaginatedLogsRetentionRuleListApi,
PaginatedLogsSamplingRuleListApi,
PaginatedLogsViewListApi,
PatchedLogsAlertConfigurationApi,
PatchedLogsMetricRuleApi,
+ PatchedLogsRetentionRuleApi,
PatchedLogsSamplingRuleApi,
PatchedLogsViewApi,
_LogsAttributesResponseApi,
@@ -595,6 +601,152 @@ export const logsQueryCreate = async (
})
}
+export const getLogsRetentionRulesListUrl = (projectId: string, params?: LogsRetentionRulesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/logs/retention_rules/?${stringifiedParams}`
+ : `/api/projects/${projectId}/logs/retention_rules/`
+}
+
+export const logsRetentionRulesList = async (
+ projectId: string,
+ params?: LogsRetentionRulesListParams,
+ options?: RequestInit
+): Promise<PaginatedLogsRetentionRuleListApi> => {
+ return apiMutator<PaginatedLogsRetentionRuleListApi>(getLogsRetentionRulesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getLogsRetentionRulesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/logs/retention_rules/`
+}
+
+export const logsRetentionRulesCreate = async (
+ projectId: string,
+ logsRetentionRuleApi: NonReadonly<LogsRetentionRuleApi>,
+ options?: RequestInit
+): Promise<LogsRetentionRuleApi> => {
+ return apiMutator<LogsRetentionRuleApi>(getLogsRetentionRulesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(logsRetentionRuleApi),
+ })
+}
+
+export const getLogsRetentionRulesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/logs/retention_rules/${id}/`
+}
+
+export const logsRetentionRulesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<LogsRetentionRuleApi> => {
+ return apiMutator<LogsRetentionRuleApi>(getLogsRetentionRulesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getLogsRetentionRulesUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/logs/retention_rules/${id}/`
+}
+
+export const logsRetentionRulesUpdate = async (
+ projectId: string,
+ id: string,
+ logsRetentionRuleApi: NonReadonly<LogsRetentionRuleApi>,
+ options?: RequestInit
+): Promise<LogsRetentionRuleApi> => {
+ return apiMutator<LogsRetentionRuleApi>(getLogsRetentionRulesUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(logsRetentionRuleApi),
+ })
+}
+
+export const getLogsRetentionRulesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/logs/retention_rules/${id}/`
+}
+
+export const logsRetentionRulesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedLogsRetentionRuleApi?: NonReadonly<PatchedLogsRetentionRuleApi>,
+ options?: RequestInit
+): Promise<LogsRetentionRuleApi> => {
+ return apiMutator<LogsRetentionRuleApi>(getLogsRetentionRulesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedLogsRetentionRuleApi),
+ })
+}
+
+export const getLogsRetentionRulesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/logs/retention_rules/${id}/`
+}
+
+export const logsRetentionRulesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getLogsRetentionRulesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getLogsRetentionRulesReorderCreateUrl = (
+ projectId: string,
+ params?: LogsRetentionRulesReorderCreateParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/logs/retention_rules/reorder/?${stringifiedParams}`
+ : `/api/projects/${projectId}/logs/retention_rules/reorder/`
+}
+
+/**
+ * Atomically reassign priorities so the given ID order maps to ascending priorities (0..n-1).
+ */
+export const logsRetentionRulesReorderCreate = async (
+ projectId: string,
+ logsRetentionRuleReorderApi: LogsRetentionRuleReorderApi,
+ params?: LogsRetentionRulesReorderCreateParams,
+ options?: RequestInit
+): Promise<PaginatedLogsRetentionRuleListApi> => {
+ return apiMutator<PaginatedLogsRetentionRuleListApi>(getLogsRetentionRulesReorderCreateUrl(projectId, params), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(logsRetentionRuleReorderApi),
+ })
+}
+
export const getLogsSamplingRulesListUrl = (projectId: string, params?: LogsSamplingRulesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 508b36fd81d0..b08040ec2018 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -1288,6 +1288,97 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe('The logs query to execute.'),
})
+export const logsRetentionRulesCreateBodyNameMax = 255
+
+export const logsRetentionRulesCreateBodyEnabledDefault = false
+export const logsRetentionRulesCreateBodyPriorityMin = 0
+
+export const LogsRetentionRulesCreateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(logsRetentionRulesCreateBodyNameMax).describe('User-visible label for this rule.'),
+ enabled: zod
+ .boolean()
+ .default(logsRetentionRulesCreateBodyEnabledDefault)
+ .describe('When false, the rule is ignored by ingestion and listing UIs that show active rules only.'),
+ priority: zod
+ .number()
+ .min(logsRetentionRulesCreateBodyPriorityMin)
+ .nullish()
+ .describe(
+ 'Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.'
+ ),
+ config: zod
+ .unknown()
+ .describe(
+ 'Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND\/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{\"retention_days\":30,\"filter_group\":{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}}`. Logs matching no enabled rule keep the environment\'s default retention.'
+ ),
+})
+
+export const logsRetentionRulesUpdateBodyNameMax = 255
+
+export const logsRetentionRulesUpdateBodyEnabledDefault = false
+export const logsRetentionRulesUpdateBodyPriorityMin = 0
+
+export const LogsRetentionRulesUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod.string().max(logsRetentionRulesUpdateBodyNameMax).describe('User-visible label for this rule.'),
+ enabled: zod
+ .boolean()
+ .default(logsRetentionRulesUpdateBodyEnabledDefault)
+ .describe('When false, the rule is ignored by ingestion and listing UIs that show active rules only.'),
+ priority: zod
+ .number()
+ .min(logsRetentionRulesUpdateBodyPriorityMin)
+ .nullish()
+ .describe(
+ 'Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.'
+ ),
+ config: zod
+ .unknown()
+ .describe(
+ 'Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND\/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{\"retention_days\":30,\"filter_group\":{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}}`. Logs matching no enabled rule keep the environment\'s default retention.'
+ ),
+})
+
+export const logsRetentionRulesPartialUpdateBodyNameMax = 255
+
+export const logsRetentionRulesPartialUpdateBodyEnabledDefault = false
+export const logsRetentionRulesPartialUpdateBodyPriorityMin = 0
+
+export const LogsRetentionRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(logsRetentionRulesPartialUpdateBodyNameMax)
+ .optional()
+ .describe('User-visible label for this rule.'),
+ enabled: zod
+ .boolean()
+ .default(logsRetentionRulesPartialUpdateBodyEnabledDefault)
+ .describe('When false, the rule is ignored by ingestion and listing UIs that show active rules only.'),
+ priority: zod
+ .number()
+ .min(logsRetentionRulesPartialUpdateBodyPriorityMin)
+ .nullish()
+ .describe(
+ 'Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.'
+ ),
+ config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND\/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{\"retention_days\":30,\"filter_group\":{\"type\":\"AND\",\"values\":[{\"type\":\"AND\",\"values\":[{\"key\":\"service.name\",\"operator\":\"exact\",\"value\":\"api\"}]}]}}`. Logs matching no enabled rule keep the environment\'s default retention.'
+ ),
+})
+
+/**
+ * Atomically reassign priorities so the given ID order maps to ascending priorities (0..n-1).
+ */
+export const LogsRetentionRulesReorderCreateBody = /* @__PURE__ */ zod.object({
+ ordered_ids: zod
+ .array(zod.uuid())
+ .describe(
+ 'Rule IDs in the desired evaluation order (first element is highest priority \/ lowest order index).'
+ ),
+})
+
export const logsSamplingRulesCreateBodyNameMax = 255
export const logsSamplingRulesCreateBodyEnabledDefault = false
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index d992491cb50f..aa15696f47f8 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -429,6 +429,27 @@ tools:
- entries.*.pattern.sparkline
- entries.*.pattern.count
- entries.*.pattern.error_count
+ logs-retention-rules-create:
+ operation: logs_retention_rules_create
+ enabled: false
+ logs-retention-rules-destroy:
+ operation: logs_retention_rules_destroy
+ enabled: false
+ logs-retention-rules-list:
+ operation: logs_retention_rules_list
+ enabled: false
+ logs-retention-rules-partial-update:
+ operation: logs_retention_rules_partial_update
+ enabled: false
+ logs-retention-rules-reorder-create:
+ operation: logs_retention_rules_reorder_create
+ enabled: false
+ logs-retention-rules-retrieve:
+ operation: logs_retention_rules_retrieve
+ enabled: false
+ logs-retention-rules-update:
+ operation: logs_retention_rules_update
+ enabled: false
logs-sampling-rules-create:
operation: logs_sampling_rules_create
enabled: false
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index cb6df4606ceb..e9e55c2d5c74 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -1016,6 +1016,7 @@ export type ActivityLogListParams = {
* * `Log` - Log
* * `LogsAlertConfiguration` - LogsAlertConfiguration
* * `LogsExclusionRule` - LogsExclusionRule
+ * * `LogsRetentionRule` - LogsRetentionRule
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
@@ -1106,6 +1107,7 @@ export const ActivityLogListScope = {
Log: 'Log',
LogsAlertConfiguration: 'LogsAlertConfiguration',
LogsExclusionRule: 'LogsExclusionRule',
+ LogsRetentionRule: 'LogsRetentionRule',
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
@@ -1183,6 +1185,7 @@ export const ActivityLogListScope = {
* * `Log` - Log
* * `LogsAlertConfiguration` - LogsAlertConfiguration
* * `LogsExclusionRule` - LogsExclusionRule
+ * * `LogsRetentionRule` - LogsRetentionRule
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
@@ -1261,6 +1264,7 @@ export const ActivityLogListScopesItem = {
Log: 'Log',
LogsAlertConfiguration: 'LogsAlertConfiguration',
LogsExclusionRule: 'LogsExclusionRule',
+ LogsRetentionRule: 'LogsRetentionRule',
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
diff --git a/pyproject.toml b/pyproject.toml
index d3de74b2a8c5..86783a8ee56e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -563,6 +563,7 @@ ignore_imports = [
"products.logs.backend.presentation.views.alerts_api -> products.logs.backend.alert_state_machine",
"products.logs.backend.presentation.views.alerts_api -> products.logs.backend.models",
"products.logs.backend.presentation.views.metric_rules_api -> products.logs.backend.models",
+ "products.logs.backend.presentation.views.retention_api -> products.logs.backend.models",
"products.logs.backend.presentation.views.sampling_api -> products.logs.backend.models",
"products.logs.backend.presentation.views.views_api -> products.logs.backend.models",
# logs presentation isolation (temporary): cross-product imports the moved viewsets
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index de96dde2022a..40f46e03fddc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -36774,6 +36774,37 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ export interface LogsRetentionRule {
+ /** Unique identifier for this retention rule. */
+ readonly id: string;
+ /**
+ * User-visible label for this rule.
+ * @maxLength 255
+ */
+ name: string;
+ /** When false, the rule is ignored by ingestion and listing UIs that show active rules only. */
+ enabled?: boolean;
+ /**
+ * Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.
+ * @minimum 0
+ * @nullable
+ */
+ priority?: number | null;
+ /** Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{"retention_days":30,"filter_group":{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}}`. Logs matching no enabled rule keep the environment's default retention. */
+ config: unknown;
+ /** Incremented on each update for worker cache coherency. */
+ readonly version: number;
+ readonly created_by: number;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
+ export interface LogsRetentionRuleReorder {
+ /** Rule IDs in the desired evaluation order (first element is highest priority / lowest order index). */
+ ordered_ids: string[];
+ }
+
export type LogsSamplingRuleScopeAttributeFiltersItem = { [key: string]: unknown };
/**
@@ -40882,6 +40913,15 @@ export namespace Schemas {
results: LogsMetricRule[];
}
+ export interface PaginatedLogsRetentionRuleList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: LogsRetentionRule[];
+ }
+
export interface PaginatedLogsSamplingRuleList {
count: number;
/** @nullable */
@@ -48723,6 +48763,32 @@ export namespace Schemas {
readonly updated_at?: string | null;
}
+ export interface PatchedLogsRetentionRule {
+ /** Unique identifier for this retention rule. */
+ readonly id?: string;
+ /**
+ * User-visible label for this rule.
+ * @maxLength 255
+ */
+ name?: string;
+ /** When false, the rule is ignored by ingestion and listing UIs that show active rules only. */
+ enabled?: boolean;
+ /**
+ * Lower numbers are evaluated first; the first matching rule wins. Omit to append after existing rules.
+ * @minimum 0
+ * @nullable
+ */
+ priority?: number | null;
+ /** Retention rule JSON. Required keys: `retention_days` (integer — how long matching logs are kept; must be a tier the organization is entitled to, same as the team-wide Logs retention setting) and `filter_group` (PropertyGroupFilter shape — an AND/OR tree of property predicates evaluated per record to decide which logs this rule matches). Example: `{"retention_days":30,"filter_group":{"type":"AND","values":[{"type":"AND","values":[{"key":"service.name","operator":"exact","value":"api"}]}]}}`. Logs matching no enabled rule keep the environment's default retention. */
+ config?: unknown;
+ /** Incremented on each update for worker cache coherency. */
+ readonly version?: number;
+ readonly created_by?: number;
+ readonly created_at?: string;
+ /** @nullable */
+ readonly updated_at?: string | null;
+ }
+
export type PatchedLogsSamplingRuleScopeAttributeFiltersItem = { [key: string]: unknown };
export interface PatchedLogsSamplingRule {
@@ -71447,6 +71513,7 @@ export namespace Schemas {
* * `Log` - Log
* * `LogsAlertConfiguration` - LogsAlertConfiguration
* * `LogsExclusionRule` - LogsExclusionRule
+ * * `LogsRetentionRule` - LogsRetentionRule
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
@@ -71538,6 +71605,7 @@ export namespace Schemas {
Log: 'Log',
LogsAlertConfiguration: 'LogsAlertConfiguration',
LogsExclusionRule: 'LogsExclusionRule',
+ LogsRetentionRule: 'LogsRetentionRule',
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
@@ -71615,6 +71683,7 @@ export namespace Schemas {
* * `Log` - Log
* * `LogsAlertConfiguration` - LogsAlertConfiguration
* * `LogsExclusionRule` - LogsExclusionRule
+ * * `LogsRetentionRule` - LogsRetentionRule
* * `DashboardWidget` - DashboardWidget
* * `ProductTour` - ProductTour
* * `Ticket` - Ticket
@@ -71694,6 +71763,7 @@ export namespace Schemas {
Log: 'Log',
LogsAlertConfiguration: 'LogsAlertConfiguration',
LogsExclusionRule: 'LogsExclusionRule',
+ LogsRetentionRule: 'LogsRetentionRule',
DashboardWidget: 'DashboardWidget',
ProductTour: 'ProductTour',
Ticket: 'Ticket',
@@ -76778,6 +76848,28 @@ export namespace Schemas {
offset?: number;
};
+ export type LogsRetentionRulesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type LogsRetentionRulesReorderCreateParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type LogsSamplingRulesListParams = {
/**
* Number of results to return per page.