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): allow custom retention in whole months behind a flag (#101531)

Frank Hamande9086d49551a
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index 7a2b27a7154c..cb53570927ba 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -22,6 +22,8 @@ from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
+from products.logs.backend.models import LogsRetentionRule
+
from ee.billing.billing_manager import (
BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER,
BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION,
@@ -573,6 +575,12 @@ class TestBillingManager(BaseTest):
organization.save()
self.team.logs_settings = {"retention_days": 30}
self.team.save()
+ rule = LogsRetentionRule.objects.create(
+ team=self.team,
+ name="keep api logs",
+ enabled=True,
+ config={"retention_days": 90, "filter_group": {"type": "AND", "values": []}},
+ )
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
@@ -592,6 +600,10 @@ class TestBillingManager(BaseTest):
self.team.refresh_from_db()
assert organization.available_product_features == [{"key": "surveys", "name": "Surveys"}]
assert self.team.logs_settings == {"retention_days": 14}
+ rule.refresh_from_db()
+ assert rule.config == {"retention_days": 14, "filter_group": {"type": "AND", "values": []}}
+ assert rule.enabled is True
+ assert rule.version == 2
@patch("ee.billing.billing_manager.http_session.get")
def test_update_available_product_features_reconciles_events_retention(self, mock_get: MagicMock):
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c624c1f6a270..296d6b5c85fc 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5160,6 +5160,30 @@ snapshots:
hash: v1.k794b7964.1d690c0916c6cb0e1cd9682b2c2ceaf072907faf864eb9c60708f20b54491d01.CSbDUiLNw1wFHNsYIjr6gY5pqrWGWK_ka7wav_H_zwo
logs-logsfiltervolumesparkline--with-rate-limit-threshold--light:
hash: v1.k794b7964.90511b5879e111bf4d4b3f7b31f5d24159de7590de35e110bc4d510f763cfa1a.l4VDaP9QZZgd9RbT-nWeHb00FGgojPia3OHP-Bq-pfU
+ logs-logsretentionperiodpicker--base-tiers--dark:
+ hash: v1.k794b7964.b320377cfdae680285b0c049d5e57679c5f210812167fd3b513a66aa12c87bcc.ZaoS8GMwD6RM5pYr3lwjuGMhrEWveeoqZe1kil1pDDI
+ logs-logsretentionperiodpicker--base-tiers--light:
+ hash: v1.k794b7964.b164cfedc47b630ad3640861298a56ba2087b325354d4909a1ae52d5932e4837.qIo-IubUDMqw2GkDGv3WNKgUCrnLDMV46KJYLv7PRwU
+ logs-logsretentionperiodpicker--custom-months-in-form--dark:
+ hash: v1.k794b7964.5a098bca3356e26b33c1a5ae92d63734901e83169db67050d276bb30e79b5a90.QzUMqSnor2VLJSYu61WTRLhVCjdJ2OCQq568e9pDZuk
+ logs-logsretentionperiodpicker--custom-months-in-form--light:
+ hash: v1.k794b7964.66660e4e391db992d95fcc2cc191db8a92c92ea52023bf0bf733583ab8a57821.6kJnoNuiJzMN2o4z3tU83FFaWbYLwT0ksNWhLYLneas
+ logs-logsretentionperiodpicker--custom-months-with-apply--dark:
+ hash: v1.k794b7964.908f17c98f247c0679a47fae9b1f3306bc96033de77a1ff170f5dfe119634c40.3qC_zyo-6PnHiYkDCw4RUmmlwP-aoqaJfC9dWHv2wQ8
+ logs-logsretentionperiodpicker--custom-months-with-apply--light:
+ hash: v1.k794b7964.d9b029c0a9738183532b05f05b402946bdf972438f2560a6784f170e7c8666fb.9SaLcWk-7GL2P-k_zG2_pVpqVndrOqGqv49I7YXMI5w
+ logs-logsretentionperiodpicker--presets--dark:
+ hash: v1.k794b7964.bf7f1a6328c67bfb20ab0a6f47be32bd40ed1f15ef1ffaeef6def4da1095ae2d.P7GBBikTJ9Kb3gB3Or9dmerilH4g3PXVXOXfush_JOc
+ logs-logsretentionperiodpicker--presets--light:
+ hash: v1.k794b7964.4b41ea1b1872ac95d91ad583f561d9ec11fd333b14641ed314971f984b81424f.DNMtT1FYhAOvTURLo5mgLNjN47OI677rxr8SxVT6PcQ
+ logs-logsretentionperiodpicker--stored-custom-months-without-flag--dark:
+ hash: v1.k794b7964.6351563996282eddb3ae33121d7dcf8e2e31ebe5ad69db2464179c405d86bd24.IlTIycUAQ8pO4uGcT68dfvXC5o1C_TVuiI2-OAPybh8
+ logs-logsretentionperiodpicker--stored-custom-months-without-flag--light:
+ hash: v1.k794b7964.3b75256a9f10257b59e553ea6dd50f156d4bb3eaca060757ae418a7260eb9aaf.Bd3DaT36fdW6E8TlosPxzlUs-cToSFuebbW5U7F0BpU
+ logs-logsretentionperiodpicker--stored-custom-months-without-paid-retention--dark:
+ hash: v1.k794b7964.f9059da612f8cb309c1100982a7352bf0c010c585701ed9f703ed1962da1a8b2.4Wbe0lwcRKZju4mbcJDVTwzvT2DtSSqF1VwdFStAA5o
+ logs-logsretentionperiodpicker--stored-custom-months-without-paid-retention--light:
+ hash: v1.k794b7964.d8d79824779beb9150246c932e4f2b756133d02aca4ca269271b98d0e9082480.PCD7I0jw8Fis5NRmUgRrjvUpwz5Dap-BO1UKMSJu5Ns
marketing-analytics-customer-acquisition-cards--configuration-loading--dark:
hash: v1.k794b7964.4e3295796230b8ccc9ce5cb239d9ffe000af9d00324d31584d3fa6fde8550fe9.04jR2iHz7Mn5n3Z6KmK4yt-R520UGYL9im_4Icykhxk
marketing-analytics-customer-acquisition-cards--configuration-loading--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b3ba795141ef..bacb6ec05e33 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -374,6 +374,7 @@ export const FEATURE_FLAGS = {
LOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logs
LOGS_SERVICES_VIEW_V2: 'logs-services-view-v2', // owner: #team-logs
LOGS_SESSION_ERROR_BADGES: 'logs-session-error-badges', // owner: #team-logs
+ LOGS_SETTINGS_CUSTOM_RETENTION: 'logs-settings-custom-retention', // owner: #team-logs
LOGS_SETTINGS_JSON: 'logs-settings-json', // owner: #team-logs
LOGS_SETTINGS_PII_SCRUB: 'logs-settings-pii-scrub', // owner: #team-logs
LOGS_SETTINGS_RETENTION_RULES: 'logs-settings-retention-rules', // owner: #team-logs
diff --git a/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx b/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx
index f484796685c8..463d8d94043c 100644
--- a/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx
+++ b/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx
@@ -1,18 +1,23 @@
import { useActions, useValues } from 'kea'
-import { LemonDialog, LemonSegmentedButton, LemonSegmentedButtonOption, LemonSwitch } from '@posthog/lemon-ui'
+import { LemonDialog, LemonSwitch } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { TeamMembershipLevel } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { teamLogic } from 'scenes/teamLogic'
-import { userLogic } from 'scenes/userLogic'
-import { AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
-const VALID_RETENTION_DAYS = [14, 30] as const
-type LogsRetentionDays = (typeof VALID_RETENTION_DAYS)[number]
+import {
+ LOGS_RETENTION_DEFAULT_DAYS,
+ isValidLogsRetentionDays,
+ logsRetentionDaysLabel,
+} from 'products/logs/frontend/components/LogsRetention/logsRetentionPeriod'
+import { LogsRetentionPeriodPicker } from 'products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker'
+import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'
export function LogsCaptureSettings(): JSX.Element {
const { updateCurrentTeam } = useActions(teamLogic)
@@ -116,16 +121,17 @@ export function LogsPiiScrubSettings(): JSX.Element {
export function LogsRetentionSettings(): JSX.Element {
const { updateCurrentTeam } = useActions(teamLogic)
const { currentTeam, currentTeamLoading } = useValues(teamLogic)
- const { hasAvailableFeature } = useValues(userLogic)
+ const allowCustomRetention = useFeatureFlag(LogsFeatureFlagKeys.customRetention)
const restrictedReason = useRestrictedArea({
scope: RestrictionScope.Project,
minimumAccessLevel: TeamMembershipLevel.Admin,
})
- const storedRetentionDays = currentTeam?.logs_settings?.retention_days ?? 14
- const currentRetention: LogsRetentionDays = VALID_RETENTION_DAYS.includes(storedRetentionDays as LogsRetentionDays)
- ? (storedRetentionDays as LogsRetentionDays)
- : 14
+ const storedRetentionDays = currentTeam?.logs_settings?.retention_days ?? LOGS_RETENTION_DEFAULT_DAYS
+ // Show any stored period the backend accepts, even when the flag that offered it is now off.
+ const currentRetention = isValidLogsRetentionDays(storedRetentionDays, true)
+ ? storedRetentionDays
+ : LOGS_RETENTION_DEFAULT_DAYS
const retentionLastUpdated = currentTeam?.logs_settings?.retention_last_updated
const getThrottleReason = (): string | undefined => {
@@ -140,37 +146,13 @@ export function LogsRetentionSettings(): JSX.Element {
return undefined
}
- const throttleReason = getThrottleReason()
- const retentionFeatureDisabledReason = (retentionDays: LogsRetentionDays): string | undefined => {
- if (retentionDays === 30 && !hasAvailableFeature(AvailableFeature.LOGS_RETENTION_30D)) {
- return 'Upgrade to a paid plan to use 30-day retention'
- }
- return undefined
- }
-
- const renderOptions = (): LemonSegmentedButtonOption<LogsRetentionDays>[] => {
- const disabledReason = currentTeamLoading ? 'Loading...' : (restrictedReason ?? throttleReason ?? undefined)
- return [
- {
- value: 14,
- label: '14 days (default)',
- disabledReason,
- 'data-attr': 'logs-retention-button-14d',
- },
- {
- value: 30,
- label: '30 days',
- disabledReason: disabledReason ?? retentionFeatureDisabledReason(30),
- 'data-attr': 'logs-retention-button-30d',
- },
- ]
- }
+ const disabledReason = currentTeamLoading ? 'Loading...' : (restrictedReason ?? getThrottleReason())
- const handleRetentionChange = (retentionDays: LogsRetentionDays): void => {
+ const handleRetentionChange = (retentionDays: number): void => {
if (retentionDays === currentRetention) {
return
}
- const label = renderOptions().find((o) => o.value === retentionDays)?.label ?? `${retentionDays} days`
+ const label = logsRetentionDaysLabel(retentionDays)
LemonDialog.open({
title: 'Change logs retention period?',
description:
@@ -191,11 +173,12 @@ export function LogsRetentionSettings(): JSX.Element {
return (
<AccessControlAction resourceType={AccessControlResourceType.Logs} minAccessLevel={AccessControlLevel.Editor}>
- <LemonSegmentedButton
+ <LogsRetentionPeriodPicker
value={currentRetention}
- onChange={(val) => handleRetentionChange(val)}
- options={renderOptions()}
- disabledReason={restrictedReason ?? undefined}
+ onChange={handleRetentionChange}
+ allowCustom={allowCustomRetention}
+ disabledReason={disabledReason}
+ customCommit="apply"
/>
</AccessControlAction>
)
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index b2bc65a4966c..a597bef4cecf 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -84,7 +84,7 @@ export interface LogsIngestionConsumerDeps {
dependencyRetry?: { retryCount: number; initialRetryDelayMs: number }
}
-/** Ingestion default when `logs_settings.retention_days` is unset; must be in `TeamSerializer.VALID_RETENTION_DAYS`. */
+/** Ingestion default when `logs_settings.retention_days` is unset; must match `DEFAULT_LOGS_RETENTION_DAYS` in `posthog/models/team/logs_retention.py`. */
export const DEFAULT_LOGS_RETENTION_DAYS = 14
/** Retention day counts that get their own per-tier usage metric. */
diff --git a/nodejs/src/logs/retention/compile-retention-rules.ts b/nodejs/src/logs/retention/compile-retention-rules.ts
index ee56c78df31a..0a0318c8796c 100644
--- a/nodejs/src/logs/retention/compile-retention-rules.ts
+++ b/nodejs/src/logs/retention/compile-retention-rules.ts
@@ -1,5 +1,5 @@
import { parseFilterGroup } from '../sampling/compile-rules'
-import { type CompiledRetentionRule, type CompiledRetentionRuleSet, VALID_RETENTION_DAYS } from './evaluate-retention'
+import { type CompiledRetentionRule, type CompiledRetentionRuleSet, isValidRetentionDays } from './evaluate-retention'
/**
* Defensive cap on enabled retention rules compiled (and thus scanned per record) for one team.
@@ -25,10 +25,7 @@ export function compileRetentionRuleSet(rows: RetentionRuleRow[]): CompiledReten
const retentionDays = config.retention_days
// Skip rows the API validator would have rejected — robustness against legacy or
// hand-crafted rows. A `true` boolean is not accepted (typeof true === 'boolean').
- if (typeof retentionDays !== 'number' || !Number.isInteger(retentionDays)) {
- continue
- }
- if (!VALID_RETENTION_DAYS.has(retentionDays)) {
+ if (typeof retentionDays !== 'number' || !isValidRetentionDays(retentionDays)) {
continue
}
// parseFilterGroup bounds depth/breadth and pre-compiles regex leaves; returns null for
diff --git a/nodejs/src/logs/retention/evaluate-retention.test.ts b/nodejs/src/logs/retention/evaluate-retention.test.ts
index 3606db2b77c8..e888e68fe321 100644
--- a/nodejs/src/logs/retention/evaluate-retention.test.ts
+++ b/nodejs/src/logs/retention/evaluate-retention.test.ts
@@ -52,9 +52,13 @@ describe('logs retention rules', () => {
})
it('drops rows whose retention_days is not an allowed tier', () => {
- const ruleSet = compileRetentionRuleSet([serviceRule('a', 'api', 45), serviceRule('b', 'api', 30)])
- expect(ruleSet.rules).toHaveLength(1)
- expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBe(30)
+ const ruleSet = compileRetentionRuleSet([
+ serviceRule('a', 'api', 45),
+ serviceRule('b', 'api', 2610),
+ serviceRule('c', 'api', 360),
+ ])
+ expect(ruleSet.rules.map((r) => r.id)).toEqual(['c'])
+ expect(evaluateRetentionDays(ruleSet, record({ service_name: 'api' }))).toBe(360)
})
it('ignores a rule with a missing filter_group (matches nothing)', () => {
diff --git a/nodejs/src/logs/retention/evaluate-retention.ts b/nodejs/src/logs/retention/evaluate-retention.ts
index c029e9995dbe..57bd54f5ab40 100644
--- a/nodejs/src/logs/retention/evaluate-retention.ts
+++ b/nodejs/src/logs/retention/evaluate-retention.ts
@@ -6,12 +6,22 @@ import type { LogRecord } from '~/logs/log-record-avro'
import { type FilterGroupNode, matchFilterGroup } from '../sampling/filter-group-match'
/**
- * Retention tiers a rule may assign. Kept in sync with `VALID_RETENTION_DAYS` in
- * `products/logs/backend/presentation/views/retention_api.py` (write-time validation) and
- * `RETENTION_USAGE_TIERS` in `logs-ingestion-consumer.ts`. Rows outside these tiers are
- * dropped at compile time so a hand-crafted or legacy row can't stamp an arbitrary value.
+ * Kept in sync with `logs_retention_days_error` in `posthog/models/team/logs_retention.py`. Rows
+ * outside this shape are dropped at compile time so a hand-crafted or legacy row can't stamp an arbitrary value.
*/
-export const VALID_RETENTION_DAYS = new Set([14, 30, 90])
+export const DEFAULT_RETENTION_DAYS = 14
+export const RETENTION_MONTH_DAYS = 30
+export const MAX_RETENTION_DAYS = RETENTION_MONTH_DAYS * 86
+
+export function isValidRetentionDays(days: number): boolean {
+ if (!Number.isInteger(days)) {
+ return false
+ }
+ if (days === DEFAULT_RETENTION_DAYS) {
+ return true
+ }
+ return days > 0 && days <= MAX_RETENTION_DAYS && days % RETENTION_MONTH_DAYS === 0
+}
export type CompiledRetentionRule = {
id: string
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 75f1349c8c5a..284b201e9bb1 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -45,7 +45,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import TeamBasicSerializer
from posthog.api.utils import action, validate_authorized_url_wildcards
from posthog.auth import SessionAuthentication
-from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS, AvailableFeature
+from posthog.constants import AvailableFeature
from posthog.decorators import disallow_if_impersonated
from posthog.event_usage import report_user_action
from posthog.geoip import get_geoip_properties
@@ -76,6 +76,12 @@ from posthog.models.product_intent.product_intent import (
)
from posthog.models.project import Project
from posthog.models.team.extensions import get_or_create_team_extension
+from posthog.models.team.logs_retention import (
+ LOGS_CUSTOM_RETENTION_FLAG,
+ LOGS_RETENTION_BASE_TIERS_DAYS,
+ logs_retention_days_error,
+ required_logs_retention_feature,
+)
from posthog.models.team.setup_tasks import SetupTaskId
from posthog.models.team.team import CURRENCY_CODE_CHOICES, DEFAULT_CURRENCY
from posthog.models.team.team_caching import set_team_in_cache
@@ -91,6 +97,7 @@ from posthog.permissions import (
UserCanCreateProjectPermission,
get_authenticator_scoped_organization_ids,
get_authenticator_scoped_team_ids,
+ posthog_feature_flag_enabled,
)
from posthog.scopes import APIScopeObjectOrNotSupported
from posthog.session_recordings.data_retention import (
@@ -1210,6 +1217,20 @@ def _get_organization_for_logs_settings_check(serializer: serializers.BaseSerial
return None
+def _custom_logs_retention_enabled(serializer: serializers.BaseSerializer, team: Team | None) -> bool:
+ organization = _get_organization_for_logs_settings_check(serializer)
+ request = serializer.context.get("request")
+ user = getattr(request, "user", None)
+ if organization is None or user is None or not user.is_authenticated:
+ return False
+ return posthog_feature_flag_enabled(
+ LOGS_CUSTOM_RETENTION_FLAG,
+ str(user.distinct_id),
+ organization_id=organization.id,
+ team_id=team.id if team is not None else None,
+ )
+
+
class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):
instance: Team | None
_group_types_cache: list[dict[str, Any]] | None = None
@@ -1888,8 +1909,6 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
return value
- VALID_RETENTION_DAYS = {14, 30}
-
def validate_logs_settings(self, value: dict | None) -> dict | None:
if value is None:
return value
@@ -1908,22 +1927,31 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
)
value["json_parse_logs_attribute_key"] = attribute_key.strip()
- new_retention = value.get("retention_days")
- if new_retention is not None and new_retention not in TeamSerializer.VALID_RETENTION_DAYS:
- raise exceptions.ValidationError(
- f"retention_days must be one of {sorted(TeamSerializer.VALID_RETENTION_DAYS)}"
- )
-
team = (
self.instance.passthrough_team
if self.instance is not None and hasattr(self.instance, "passthrough_team")
else self.instance
)
+
logs_settings = team.logs_settings if team is not None else None
old_retention = logs_settings.get("retention_days") if logs_settings else None
+ new_retention = value.get("retention_days")
+ if new_retention is not None and (isinstance(new_retention, bool) or not isinstance(new_retention, int)):
+ raise exceptions.ValidationError("retention_days must be an integer")
+
+ # Only a changed period is checked against the flag and the entitlement. Unrelated settings
+ # updates send the stored period back, and must not fail when the flag is turned off later.
if new_retention is not None and old_retention != new_retention:
- required_feature = LOGS_RETENTION_FEATURES_BY_DAYS.get(new_retention)
+ # Only evaluate the flag for values outside the base tiers, so the common path makes no flag call.
+ custom_enabled = new_retention not in LOGS_RETENTION_BASE_TIERS_DAYS and _custom_logs_retention_enabled(
+ self, team
+ )
+ error = logs_retention_days_error(new_retention, custom_retention_enabled=custom_enabled)
+ if error:
+ raise exceptions.ValidationError(error)
+
+ required_feature = required_logs_retention_feature(new_retention)
if required_feature:
organization = _get_organization_for_logs_settings_check(self)
if organization is None or not organization.is_feature_available(required_feature):
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 96579337843d..8f695720f7c4 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -2089,6 +2089,65 @@ def team_api_test_factory():
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "logs_settings must be an object" in response.json()["detail"]
+ def test_logs_settings_custom_retention_requires_flag(self):
+ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)
+
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": 90}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "retention_days must be one of" in response.json()["detail"]
+
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ for valid_days in [90, 360, 2580]:
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": valid_days}},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["logs_settings"]["retention_days"] == valid_days
+ # Reset so the next update is not blocked by the 24-hour throttle.
+ self.team.logs_settings = {}
+ self.team.save()
+
+ for invalid_days in [45, 2610, 0, -30]:
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": invalid_days}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, (
+ f"Expected 400 for retention_days={invalid_days}"
+ )
+ assert "multiple of 30" in response.json()["detail"]
+
+ def test_logs_settings_unchanged_custom_retention_kept_when_flag_off(self):
+ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": 90}},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ # Settings switches send the whole object back, including the stored period.
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": 90, "json_parse_logs": True}},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["logs_settings"]["retention_days"] == 90
+ assert response.json()["logs_settings"]["json_parse_logs"] is True
+
+ def test_logs_settings_custom_retention_requires_paid_feature(self):
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"retention_days": 90}},
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert "90 days" in response.json()["detail"]
+
def test_logs_settings_retention_requires_matching_feature(self):
response = self.client.patch(
"/api/environments/@current/",
diff --git a/posthog/constants.py b/posthog/constants.py
index bb5da91e5c9b..3705a592c6ae 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -58,11 +58,6 @@ class AvailableFeature(StrEnum):
POSTHOG_CODE_USAGE = "posthog_code_usage"
-LOGS_RETENTION_FEATURES_BY_DAYS: dict[int, AvailableFeature] = {
- 30: AvailableFeature.LOGS_RETENTION_30D,
-}
-
-
TREND_FILTER_TYPE_ACTIONS = "actions"
TREND_FILTER_TYPE_EVENTS = "events"
TREND_FILTER_TYPE_DATA_WAREHOUSE = "data_warehouse"
diff --git a/posthog/models/team/logs_retention.py b/posthog/models/team/logs_retention.py
index 95edf35eb5c6..33dda1167b9a 100644
--- a/posthog/models/team/logs_retention.py
+++ b/posthog/models/team/logs_retention.py
@@ -1,12 +1,49 @@
import structlog
-from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS
+from posthog.constants import AvailableFeature
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from products.logs.backend.models import LogsRetentionRule
+
logger = structlog.get_logger(__name__)
DEFAULT_LOGS_RETENTION_DAYS = 14
+# Custom retention periods are whole 30-day months, so ingestion and billing can treat each one as a tier.
+LOGS_RETENTION_MONTH_DAYS = 30
+# 86 thirty-day months cover 7 calendar years, the same ceiling as events retention.
+LOGS_RETENTION_MAX_MONTHS = 86
+LOGS_RETENTION_MAX_DAYS = LOGS_RETENTION_MONTH_DAYS * LOGS_RETENTION_MAX_MONTHS
+LOGS_RETENTION_BASE_TIERS_DAYS = frozenset({DEFAULT_LOGS_RETENTION_DAYS, 30})
+LOGS_CUSTOM_RETENTION_FLAG = "logs-settings-custom-retention"
+LOGS_RETENTION_PAID_FEATURE = AvailableFeature.LOGS_RETENTION_30D
+
+
+def logs_retention_days_error(days: int, *, custom_retention_enabled: bool) -> str | None:
+ """Return the validation message for a retention period, or None when it is accepted."""
+ if days in LOGS_RETENTION_BASE_TIERS_DAYS:
+ return None
+ if not custom_retention_enabled:
+ return f"retention_days must be one of {sorted(LOGS_RETENTION_BASE_TIERS_DAYS)}"
+ if days <= 0 or days % LOGS_RETENTION_MONTH_DAYS != 0 or days > LOGS_RETENTION_MAX_DAYS:
+ return (
+ f"retention_days must be {DEFAULT_LOGS_RETENTION_DAYS} or a multiple of {LOGS_RETENTION_MONTH_DAYS} days, "
+ f"up to {LOGS_RETENTION_MAX_DAYS}"
+ )
+ return None
+
+
+def required_logs_retention_feature(days: int) -> AvailableFeature | None:
+ return LOGS_RETENTION_PAID_FEATURE if days > DEFAULT_LOGS_RETENTION_DAYS else None
+
+
+def reset_logs_retention_rules(rules: list[LogsRetentionRule]) -> None:
+ """Reset each rule's retention period to the default, keeping its filters and enabled state."""
+ for rule in rules:
+ rule.config = {**rule.config, "retention_days": DEFAULT_LOGS_RETENTION_DAYS}
+ # Ingestion tracks rule changes by version, the same as an API update.
+ rule.version += 1
+ LogsRetentionRule.objects.bulk_update(rules, ["config", "version"])
def reset_revoked_logs_retention(organization: Organization, revoked_feature_keys: set[str]) -> int:
@@ -17,26 +54,33 @@ def reset_revoked_logs_retention(organization: Organization, revoked_feature_key
newly ingested logs. The Temporal `retention_entitlements` workflow remains
available for org-wide manual reconciliation.
"""
- revoked_days = [
- days for days, feature in LOGS_RETENTION_FEATURES_BY_DAYS.items() if feature.value in revoked_feature_keys
- ]
- if not revoked_days:
+ if LOGS_RETENTION_PAID_FEATURE.value not in revoked_feature_keys:
return 0
teams = list(
- Team.objects.filter(organization=organization, logs_settings__retention_days__in=revoked_days).only(
- "id", "logs_settings"
- )
+ Team.objects.filter(
+ organization=organization, logs_settings__retention_days__gt=DEFAULT_LOGS_RETENTION_DAYS
+ ).only("id", "logs_settings")
)
for team in teams:
# Preserve unrelated Logs settings such as JSON parsing and PII scrubbing.
team.logs_settings = {**(team.logs_settings or {}), "retention_days": DEFAULT_LOGS_RETENTION_DAYS}
+ rules = list(
+ LogsRetentionRule.objects.filter(
+ team__organization=organization, config__retention_days__gt=DEFAULT_LOGS_RETENTION_DAYS
+ ).only("id", "config", "version")
+ )
+
if teams:
Team.objects.bulk_update(teams, ["logs_settings"])
+ if rules:
+ reset_logs_retention_rules(rules)
+ if teams or rules:
logger.info(
"Logs retention reset after entitlement revocation",
organization_id=str(organization.id),
teams_reset=len(teams),
+ rules_reset=len(rules),
)
return len(teams)
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index 73c5887a65e2..ea93c6e2d152 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -521,7 +521,7 @@ class LogsRetentionRule(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields
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>}
+ # {"filter_group": <PropertyGroupFilter>, "retention_days": <14 or a multiple of 30>}
config = models.JSONField(default=dict)
version = models.PositiveIntegerField(default=1)
diff --git a/products/logs/backend/presentation/views/retention_api.py b/products/logs/backend/presentation/views/retention_api.py
index 8fb6f6ac2d2f..d4bf3bfb4019 100644
--- a/products/logs/backend/presentation/views/retention_api.py
+++ b/products/logs/backend/presentation/views/retention_api.py
@@ -16,10 +16,15 @@ 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.team.logs_retention import (
+ LOGS_CUSTOM_RETENTION_FLAG,
+ LOGS_RETENTION_BASE_TIERS_DAYS,
+ logs_retention_days_error,
+ required_logs_retention_feature,
+)
from posthog.models.user import User
-from posthog.permissions import PostHogFeatureFlagPermission
+from posthog.permissions import PostHogFeatureFlagPermission, posthog_feature_flag_enabled
from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
from products.logs.backend.facade.retention import suggest_retention_rule_name
@@ -35,13 +40,13 @@ from products.logs.backend.presentation.filter_group_validation import (
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())
+# Rules accept the same retention periods as the team-wide setting in `TeamSerializer`
+# (`posthog/api/team.py`), so a per-log rule can never grant a tier the org couldn't set team-wide.
+
+
+def custom_retention_enabled_for(context: dict[str, Any]) -> bool:
+ is_enabled = context.get("custom_retention_enabled")
+ return bool(is_enabled()) if callable(is_enabled) else False
def retention_filter_group_error(filter_group: Any) -> str | None:
@@ -133,13 +138,28 @@ class LogsRetentionRuleSerializer(serializers.ModelSerializer):
# 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."}}
- )
+ # Only a changed period is checked against the flag and the entitlement, so a partial update
+ # such as disabling a rule still works after the flag is turned off.
+ if retention_days != self._stored_retention_days():
+ self._validate_retention_days(retention_days)
+
+ self._validate_filter_group(config.get("filter_group"))
+ return attrs
+
+ def _stored_retention_days(self) -> int | None:
+ stored = self.instance.config if self.instance is not None and isinstance(self.instance.config, dict) else {}
+ return stored.get("retention_days")
+
+ def _validate_retention_days(self, retention_days: int) -> None:
+ custom_enabled = retention_days not in LOGS_RETENTION_BASE_TIERS_DAYS and custom_retention_enabled_for(
+ self.context
+ )
+ error = logs_retention_days_error(retention_days, custom_retention_enabled=custom_enabled)
+ if error:
+ raise ValidationError({"config": {"retention_days": error}})
# 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)
+ required_feature = required_logs_retention_feature(retention_days)
if required_feature is not None:
get_organization = self.context.get("get_organization")
organization = get_organization() if callable(get_organization) else None
@@ -148,9 +168,6 @@ class LogsRetentionRuleSerializer(serializers.ModelSerializer):
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:
message = retention_filter_group_error(filter_group)
if message:
@@ -169,8 +186,10 @@ class LogsRetentionRuleSuggestNameSerializer(serializers.Serializer):
filter_group = serializers.JSONField(help_text="PropertyGroupFilter tree the rule would match on.")
def validate_retention_days(self, value: int) -> int:
- if value not in VALID_RETENTION_DAYS:
- raise ValidationError(f"Must be one of {sorted(VALID_RETENTION_DAYS)} days.")
+ custom_enabled = value not in LOGS_RETENTION_BASE_TIERS_DAYS and custom_retention_enabled_for(self.context)
+ error = logs_retention_days_error(value, custom_retention_enabled=custom_enabled)
+ if error:
+ raise ValidationError(error)
return value
def validate_filter_group(self, value: Any) -> Any:
@@ -199,6 +218,20 @@ class LogsRetentionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
return queryset.filter(team_id=self.team_id)
+ def get_serializer_context(self) -> dict[str, Any]:
+ context = super().get_serializer_context()
+ context["custom_retention_enabled"] = self._custom_retention_enabled
+ return context
+
+ def _custom_retention_enabled(self) -> bool:
+ user = cast(User, self.request.user)
+ return posthog_feature_flag_enabled(
+ LOGS_CUSTOM_RETENTION_FLAG,
+ str(user.distinct_id),
+ organization_id=self.organization.id,
+ team_id=self.team_id,
+ )
+
def perform_create(self, serializer: serializers.BaseSerializer) -> None:
s = cast(LogsRetentionRuleSerializer, serializer)
user = cast(User, self.request.user)
@@ -296,11 +329,11 @@ class LogsRetentionRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def suggest_name(self, request: Request, *args: Any, **kwargs: Any) -> Response:
if not self.organization.is_ai_data_processing_approved:
raise PermissionDenied("AI data processing must be approved by your organization to suggest names")
- serializer = LogsRetentionRuleSuggestNameSerializer(data=request.data)
+ serializer = LogsRetentionRuleSuggestNameSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
user = cast(User, request.user)
# A suggestion doesn't grant a retention tier, so entitlement is deliberately not checked here —
- # unlike a write, where LOGS_RETENTION_FEATURES_BY_DAYS gates the paid tiers.
+ # unlike a write, where `required_logs_retention_feature` gates the paid tiers.
name = suggest_retention_rule_name(
serializer.validated_data["retention_days"],
serializer.validated_data["filter_group"],
diff --git a/products/logs/backend/temporal/retention_entitlements/activities.py b/products/logs/backend/temporal/retention_entitlements/activities.py
index 1cf8b61a42dd..047b6d4bd4f7 100644
--- a/products/logs/backend/temporal/retention_entitlements/activities.py
+++ b/products/logs/backend/temporal/retention_entitlements/activities.py
@@ -1,11 +1,16 @@
from temporalio import activity
-from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS
from posthog.models import Team
+from posthog.models.team.logs_retention import (
+ DEFAULT_LOGS_RETENTION_DAYS,
+ required_logs_retention_feature,
+ reset_logs_retention_rules,
+)
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_write_only_logger
+from products.logs.backend.models import LogsRetentionRule
from products.logs.backend.temporal.retention_entitlements.types import (
EnforceLogsRetentionEntitlementsInput,
EnforceLogsRetentionEntitlementsOutput,
@@ -28,7 +33,7 @@ async def enforce_logs_retention_entitlements(
# This scans all teams with paid Logs retention enabled. Run it as explicit reconciliation
# after Billing removes those entitlements; new over-entitled writes are blocked by the API.
async for team in (
- Team.objects.filter(logs_settings__retention_days__in=list(LOGS_RETENTION_FEATURES_BY_DAYS.keys()))
+ Team.objects.filter(logs_settings__retention_days__gt=DEFAULT_LOGS_RETENTION_DAYS)
.select_related("organization")
.only("id", "name", "organization", "organization__available_product_features", "logs_settings")
):
@@ -37,7 +42,7 @@ async def enforce_logs_retention_entitlements(
if not isinstance(retention_days, int):
continue
- required_feature = LOGS_RETENTION_FEATURES_BY_DAYS.get(retention_days)
+ required_feature = required_logs_retention_feature(retention_days)
if not required_feature:
continue
@@ -49,7 +54,7 @@ async def enforce_logs_retention_entitlements(
# Preserve unrelated Logs settings such as JSON parsing and PII scrubbing.
team.logs_settings = {
**logs_settings,
- "retention_days": 14,
+ "retention_days": DEFAULT_LOGS_RETENTION_DAYS,
}
teams_to_update.append(team)
@@ -59,7 +64,7 @@ async def enforce_logs_retention_entitlements(
team_name=team.name,
organization_id=organization.id,
retention_period_before=retention_days,
- retention_period_after=14,
+ retention_period_after=DEFAULT_LOGS_RETENTION_DAYS,
)
if teams_checked % batch_size == 0:
@@ -72,12 +77,48 @@ async def enforce_logs_retention_entitlements(
batch_size=batch_size,
)
+ # Rules store their own retention period, so ingestion keeps applying a paid period until they are reset too.
+ rules_to_update: list[LogsRetentionRule] = []
+ rules_checked = 0
+ async for rule in (
+ LogsRetentionRule.objects.filter(config__retention_days__gt=DEFAULT_LOGS_RETENTION_DAYS)
+ .select_related("team__organization")
+ .only("id", "config", "version", "team__id", "team__organization__available_product_features")
+ ):
+ retention_days = rule.config.get("retention_days")
+ if not isinstance(retention_days, int):
+ continue
+ required_feature = required_logs_retention_feature(retention_days)
+ if not required_feature:
+ continue
+
+ rules_checked += 1
+ organization = rule.team.organization
+ if organization.is_feature_available(required_feature):
+ continue
+ rules_to_update.append(rule)
+ logger.info(
+ "Logs retention rule period forcibly reduced",
+ rule_id=str(rule.id),
+ team_id=rule.team_id,
+ organization_id=organization.id,
+ retention_period_before=retention_days,
+ retention_period_after=DEFAULT_LOGS_RETENTION_DAYS,
+ )
+
+ if not input.dry_run and rules_to_update:
+ await database_sync_to_async(reset_logs_retention_rules)(rules_to_update)
+
logger.info(
"Logs retention entitlement enforcement complete",
teams_checked=teams_checked,
teams_reset=len(teams_to_update),
+ rules_checked=rules_checked,
+ rules_reset=len(rules_to_update),
)
return EnforceLogsRetentionEntitlementsOutput(
teams_checked=teams_checked,
teams_reset=len(teams_to_update),
+ rules_checked=rules_checked,
+ rules_reset=len(rules_to_update),
)
diff --git a/products/logs/backend/temporal/retention_entitlements/types.py b/products/logs/backend/temporal/retention_entitlements/types.py
index b803f781c975..61c47ec215f9 100644
--- a/products/logs/backend/temporal/retention_entitlements/types.py
+++ b/products/logs/backend/temporal/retention_entitlements/types.py
@@ -11,3 +11,5 @@ class EnforceLogsRetentionEntitlementsInput:
class EnforceLogsRetentionEntitlementsOutput:
teams_checked: int
teams_reset: int
+ rules_checked: int = 0
+ rules_reset: int = 0
diff --git a/products/logs/backend/test/test_retention_entitlements.py b/products/logs/backend/test/test_retention_entitlements.py
index 36107313484e..4090615f5669 100644
--- a/products/logs/backend/test/test_retention_entitlements.py
+++ b/products/logs/backend/test/test_retention_entitlements.py
@@ -8,6 +8,7 @@ from temporalio.testing import ActivityEnvironment
from posthog.constants import AvailableFeature
from posthog.models import Organization, Team
+from products.logs.backend.models import LogsRetentionRule
from products.logs.backend.temporal.retention_entitlements.activities import enforce_logs_retention_entitlements
from products.logs.backend.temporal.retention_entitlements.types import (
EnforceLogsRetentionEntitlementsInput,
@@ -38,6 +39,19 @@ async def _refresh_team(team: Team) -> Team:
return await sync_to_async(Team.objects.get)(id=team.id)
+async def _create_rule(team: Team, retention_days: int) -> LogsRetentionRule:
+ return await sync_to_async(LogsRetentionRule.objects.create)(
+ team=team,
+ name=f"Rule {uuid.uuid4()}",
+ enabled=True,
+ config={"retention_days": retention_days, "filter_group": {"type": "AND", "values": []}},
+ )
+
+
+async def _refresh_rule(rule: LogsRetentionRule) -> LogsRetentionRule:
+ return await sync_to_async(LogsRetentionRule.objects.get)(id=rule.id)
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_enforce_logs_retention_entitlements_resets_only_over_entitled_teams() -> None:
@@ -52,17 +66,32 @@ async def test_enforce_logs_retention_entitlements_resets_only_over_entitled_tea
capture_console_logs=True,
retention_last_updated="2026-06-01T00:00:00Z",
)
+ team_90d_blocked = await _create_team(org_without_retention, 90)
+ # A rule keeps its own period, so a 14-day team can still apply a paid period through it.
+ rule_allowed = await _create_rule(team_30d_allowed, 90)
+ rule_blocked = await _create_rule(team_14d, 30)
+ rule_14d = await _create_rule(team_14d, 14)
output: EnforceLogsRetentionEntitlementsOutput = await ActivityEnvironment().run(
enforce_logs_retention_entitlements,
EnforceLogsRetentionEntitlementsInput(dry_run=False),
)
- assert output.teams_checked == 2
- assert output.teams_reset == 1
+ assert output.teams_checked == 3
+ assert output.teams_reset == 2
+ assert output.rules_checked == 2
+ assert output.rules_reset == 1
+
+ assert (await _refresh_rule(rule_allowed)).config["retention_days"] == 90
+ assert (await _refresh_rule(rule_14d)).config["retention_days"] == 14
+ blocked_rule = await _refresh_rule(rule_blocked)
+ assert blocked_rule.config == {"retention_days": 14, "filter_group": {"type": "AND", "values": []}}
+ assert blocked_rule.enabled is True
+ assert blocked_rule.version == rule_blocked.version + 1
assert (await _refresh_team(team_14d)).logs_settings["retention_days"] == 14
assert (await _refresh_team(team_30d_allowed)).logs_settings["retention_days"] == 30
+ assert (await _refresh_team(team_90d_blocked)).logs_settings["retention_days"] == 14
blocked_30d_settings = (await _refresh_team(team_30d_blocked)).logs_settings
assert blocked_30d_settings["retention_days"] == 14
@@ -75,6 +104,7 @@ async def test_enforce_logs_retention_entitlements_resets_only_over_entitled_tea
async def test_enforce_logs_retention_entitlements_dry_run_does_not_update_team() -> None:
organization = await _create_organization([])
team = await _create_team(organization, 30)
+ rule = await _create_rule(team, 90)
output: EnforceLogsRetentionEntitlementsOutput = await ActivityEnvironment().run(
enforce_logs_retention_entitlements,
@@ -83,4 +113,6 @@ async def test_enforce_logs_retention_entitlements_dry_run_does_not_update_team(
assert output.teams_checked == 1
assert output.teams_reset == 1
+ assert output.rules_reset == 1
assert (await _refresh_team(team)).logs_settings["retention_days"] == 30
+ assert (await _refresh_rule(rule)).config["retention_days"] == 90
diff --git a/products/logs/backend/test/test_retention_rules_api.py b/products/logs/backend/test/test_retention_rules_api.py
index 09c7a03e4742..4514bb71afe3 100644
--- a/products/logs/backend/test/test_retention_rules_api.py
+++ b/products/logs/backend/test/test_retention_rules_api.py
@@ -66,6 +66,64 @@ class TestLogsRetentionRulesAPI(APIBaseTest):
assert allowed.status_code == status.HTTP_201_CREATED, allowed.json()
assert allowed.json()["config"]["retention_days"] == 30
+ def test_custom_tier_requires_flag_and_entitlement(self):
+ self._grant_30d_retention()
+ # The class-level patch enables every flag; turn only the custom-retention flag off.
+ with patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=lambda flag, *args, **kwargs: flag != "logs-settings-custom-retention",
+ ):
+ flag_off = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 90, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ )
+ assert flag_off.status_code == status.HTTP_400_BAD_REQUEST, flag_off.json()
+
+ allowed = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 90, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ )
+ assert allowed.status_code == status.HTTP_201_CREATED, allowed.json()
+ assert allowed.json()["config"]["retention_days"] == 90
+
+ self.organization.available_product_features = []
+ self.organization.save()
+ denied = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 360, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ )
+ assert denied.status_code == status.HTTP_403_FORBIDDEN, denied.json()
+
+ def test_partial_update_keeps_stored_custom_period_when_flag_and_feature_are_gone(self):
+ self._grant_30d_retention()
+ rule = self.client.post(
+ self.base_url,
+ self._payload(config={"retention_days": 90, "filter_group": VALID_FILTER_GROUP}),
+ format="json",
+ ).json()
+
+ self.organization.available_product_features = []
+ self.organization.save()
+ with patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=lambda flag, *args, **kwargs: flag != "logs-settings-custom-retention",
+ ):
+ response = self.client.patch(f"{self.base_url}{rule['id']}/", {"enabled": True}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["enabled"] is True
+ assert response.json()["config"]["retention_days"] == 90
+
+ # A changed period is still checked.
+ response = self.client.patch(
+ f"{self.base_url}{rule['id']}/",
+ {"config": {"retention_days": 180, "filter_group": VALID_FILTER_GROUP}},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
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)
@@ -115,7 +173,7 @@ class TestLogsRetentionRulesAPI(APIBaseTest):
@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}),
+ ("above_maximum", {"retention_days": 2610, "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}),
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
index 5841443c9e0c..1f637409d454 100644
--- a/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionForm.tsx
@@ -1,48 +1,33 @@
import { useActions, useValues } from 'kea'
import { IconInfo } from '@posthog/icons'
-import {
- LemonInput,
- LemonSegmentedButton,
- LemonSegmentedButtonOption,
- LemonSwitch,
- Link,
- Tooltip,
-} from '@posthog/lemon-ui'
+import { LemonInput, LemonSwitch, Link, Tooltip } from '@posthog/lemon-ui'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonField } from 'lib/lemon-ui/LemonField'
-import { userLogic } from 'scenes/userLogic'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
-import { AvailableFeature } from '~/types'
import { LogsFilterVolumeSparkline } from 'products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline'
import { DropRuleFilterEditor } from 'products/logs/frontend/components/LogsSampling/DropRuleFilterEditor'
+import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'
-import { RETENTION_DAYS_OPTIONS, logsRetentionFormLogic } from './logsRetentionFormLogic'
+import { logsRetentionFormLogic } from './logsRetentionFormLogic'
+import { isValidLogsRetentionDays } from './logsRetentionPeriod'
+import { LogsRetentionPeriodPicker } from './LogsRetentionPeriodPicker'
import { buildRetentionProjection, retentionProjectionText } from './retentionStorageProjection'
export function LogsRetentionForm(): JSX.Element {
const { retentionForm, retentionFormErrors, suggestedName, suggestedNameLoading } =
useValues(logsRetentionFormLogic)
const { setRetentionFormValue, applySuggestedName } = useActions(logsRetentionFormLogic)
- const { hasAvailableFeature } = useValues(userLogic)
+ const allowCustomRetention = useFeatureFlag(LogsFeatureFlagKeys.customRetention)
const hasFilters = retentionForm.filter_group.values.length > 0
+ const retentionDaysValid = isValidLogsRetentionDays(retentionForm.retention_days, true)
// Hide the hint once it matches what's in the field — the link would be a no-op.
const showSuggestion = !!suggestedName?.name && suggestedName.name !== retentionForm.name.trim()
- // Gate paid tiers on the org entitlement, mirroring the team-wide LogsRetentionSettings — the
- // backend rejects an unentitled tier with a 403, so disable it here rather than fail on save.
- const retentionOptions: LemonSegmentedButtonOption<number>[] = RETENTION_DAYS_OPTIONS.map((days) => ({
- value: days,
- label: `${days} days`,
- disabledReason:
- days === 30 && !hasAvailableFeature(AvailableFeature.LOGS_RETENTION_30D)
- ? 'Upgrade to a paid plan to use 30-day retention'
- : undefined,
- }))
-
return (
<div className="flex flex-col gap-4 max-w-3xl">
<div className="flex flex-col gap-3">
@@ -77,12 +62,13 @@ export function LogsRetentionForm(): JSX.Element {
</div>
<SceneSection title="Retention" titleSize="sm">
- <LemonField.Pure label="Keep matching logs for">
- <LemonSegmentedButton
+ <LemonField.Pure label="Keep matching logs for" error={retentionFormErrors.retention_days}>
+ <LogsRetentionPeriodPicker
value={retentionForm.retention_days}
- onChange={(v) => v && setRetentionFormValue('retention_days', v)}
- options={retentionOptions}
+ onChange={(days) => setRetentionFormValue('retention_days', days)}
+ allowCustom={allowCustomRetention}
size="small"
+ dataAttrPrefix="logs-retention-rule"
/>
</LemonField.Pure>
</SceneSection>
@@ -101,7 +87,9 @@ export function LogsRetentionForm(): JSX.Element {
filterGroup={retentionForm.filter_group}
metric="bytes"
renderCaption={({ points }) => {
- const projection = buildRetentionProjection(points, retentionForm.retention_days)
+ const projection = retentionDaysValid
+ ? buildRetentionProjection(points, retentionForm.retention_days)
+ : null
if (!projection) {
return null
}
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.stories.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.stories.tsx
new file mode 100644
index 000000000000..188bf7e106dc
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.stories.tsx
@@ -0,0 +1,55 @@
+import { Meta, StoryFn } from '@storybook/react'
+import { useState } from 'react'
+
+import { useAvailableFeatures } from '~/mocks/features'
+import { AvailableFeature } from '~/types'
+
+import { LogsRetentionPeriodPicker, LogsRetentionPeriodPickerProps } from './LogsRetentionPeriodPicker'
+
+type StoryProps = Pick<LogsRetentionPeriodPickerProps, 'value' | 'allowCustom' | 'customCommit'> & {
+ features?: AvailableFeature[]
+}
+
+const meta: Meta<StoryProps> = {
+ title: 'Logs/LogsRetentionPeriodPicker',
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+export default meta
+
+const Template: StoryFn<StoryProps> = (args) => {
+ useAvailableFeatures(args.features ?? [AvailableFeature.LOGS_RETENTION_30D])
+ const [value, setValue] = useState(args.value)
+ return (
+ <div className="max-w-2xl">
+ <LogsRetentionPeriodPicker
+ value={value}
+ onChange={setValue}
+ allowCustom={args.allowCustom}
+ customCommit={args.customCommit}
+ />
+ <p className="text-secondary text-sm mt-2 mb-0">Selected: {value} days</p>
+ </div>
+ )
+}
+
+export const BaseTiers = Template.bind({})
+BaseTiers.args = { value: 14, allowCustom: false, customCommit: 'apply' }
+
+export const Presets = Template.bind({})
+Presets.args = { value: 360, allowCustom: true, customCommit: 'apply' }
+
+export const CustomMonthsWithApply = Template.bind({})
+CustomMonthsWithApply.args = { value: 180, allowCustom: true, customCommit: 'apply' }
+
+export const CustomMonthsInForm = Template.bind({})
+CustomMonthsInForm.args = { value: 180, allowCustom: true, customCommit: 'change' }
+
+export const StoredCustomMonthsWithoutFlag = Template.bind({})
+StoredCustomMonthsWithoutFlag.args = { value: 180, allowCustom: false, customCommit: 'apply' }
+
+export const StoredCustomMonthsWithoutPaidRetention = Template.bind({})
+StoredCustomMonthsWithoutPaidRetention.args = { value: 180, allowCustom: true, customCommit: 'apply', features: [] }
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.tsx
new file mode 100644
index 000000000000..bff03ed7aedf
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionPeriodPicker.tsx
@@ -0,0 +1,173 @@
+import { useValues } from 'kea'
+import { useEffect, useRef, useState } from 'react'
+
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonSegmentedButtonOption } from '@posthog/lemon-ui'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { AvailableFeature } from '~/types'
+
+import {
+ LOGS_RETENTION_BASE_TIERS_DAYS,
+ LOGS_RETENTION_DEFAULT_DAYS,
+ LOGS_RETENTION_MAX_MONTHS,
+ LOGS_RETENTION_MONTHS_HINT,
+ LOGS_RETENTION_PRESET_DAYS,
+ isValidLogsRetentionDays,
+ isValidLogsRetentionMonths,
+ logsRetentionDaysLabel,
+ logsRetentionDaysToMonths,
+ logsRetentionMonthsToDays,
+} from './logsRetentionPeriod'
+
+const CUSTOM = 'custom'
+type PickerValue = number | typeof CUSTOM
+
+const PAID_TIER_DISABLED_REASON = 'Upgrade to a paid plan to keep logs longer than 14 days'
+
+export interface LogsRetentionPeriodPickerProps {
+ value: number
+ onChange: (days: number) => void
+ /** Show the 90-day, 1-year and custom options. Off keeps the 14/30-day tiers only. */
+ allowCustom: boolean
+ disabledReason?: string | null
+ /**
+ * `change` commits the custom month count as the user types (inside a form with its own save
+ * button), including an invalid count so the form can block saving. `apply` adds an Apply button,
+ * for settings that save on every change.
+ */
+ customCommit?: 'change' | 'apply'
+ size?: 'small' | 'medium'
+ dataAttrPrefix?: string
+}
+
+/** With the custom option off, a stored custom period is still shown, so the picker never hides the current value. */
+function pickerPresetDays(value: number, allowCustom: boolean): number[] {
+ if (allowCustom) {
+ return LOGS_RETENTION_PRESET_DAYS
+ }
+ if (!LOGS_RETENTION_BASE_TIERS_DAYS.includes(value) && isValidLogsRetentionDays(value, true)) {
+ return [...LOGS_RETENTION_BASE_TIERS_DAYS, value]
+ }
+ return LOGS_RETENTION_BASE_TIERS_DAYS
+}
+
+export function LogsRetentionPeriodPicker({
+ value,
+ onChange,
+ allowCustom,
+ disabledReason,
+ customCommit = 'change',
+ size,
+ dataAttrPrefix = 'logs-retention',
+}: LogsRetentionPeriodPickerProps): JSX.Element {
+ const { hasAvailableFeature } = useValues(userLogic)
+ const hasPaidRetention = hasAvailableFeature(AvailableFeature.LOGS_RETENTION_30D)
+
+ const presetDays = pickerPresetDays(value, allowCustom)
+ const valueIsPreset = presetDays.includes(value)
+ const [customSelected, setCustomSelected] = useState(allowCustom && !valueIsPreset)
+ const [customMonths, setCustomMonths] = useState<number | undefined>(logsRetentionDaysToMonths(value))
+ // The last value the custom input committed, so a whole-month count that equals a preset keeps the input open.
+ const committedCustomDays = useRef<number | undefined>(undefined)
+
+ // Keep the input in step when the stored value changes from outside, e.g. after a save or reload.
+ useEffect(() => {
+ if (value === committedCustomDays.current) {
+ return
+ }
+ setCustomSelected(allowCustom && !valueIsPreset)
+ if (!valueIsPreset) {
+ setCustomMonths(logsRetentionDaysToMonths(value))
+ }
+ }, [value, valueIsPreset, allowCustom])
+
+ const paidTierReason = (days: number): string | undefined =>
+ days > LOGS_RETENTION_DEFAULT_DAYS && !hasPaidRetention ? PAID_TIER_DISABLED_REASON : undefined
+ const customDisabledReason = disabledReason ?? (hasPaidRetention ? undefined : PAID_TIER_DISABLED_REASON)
+
+ const options: LemonSegmentedButtonOption<PickerValue>[] = presetDays.map((days) => ({
+ value: days,
+ label: logsRetentionDaysLabel(days),
+ disabledReason: disabledReason ?? paidTierReason(days),
+ 'data-attr': `${dataAttrPrefix}-button-${days}d`,
+ }))
+ if (allowCustom) {
+ options.push({
+ value: CUSTOM,
+ label: 'Custom',
+ disabledReason: customDisabledReason,
+ 'data-attr': `${dataAttrPrefix}-button-custom`,
+ })
+ }
+
+ const customDays = isValidLogsRetentionMonths(customMonths) ? logsRetentionMonthsToDays(customMonths) : undefined
+ const customApplyDisabledReason =
+ customDays === undefined
+ ? LOGS_RETENTION_MONTHS_HINT
+ : customDays === value
+ ? 'This is the current retention period'
+ : undefined
+
+ const commitCustomDays = (days: number): void => {
+ committedCustomDays.current = days
+ onChange(days)
+ }
+
+ const handleCustomMonthsChange = (months: number | undefined): void => {
+ setCustomMonths(months)
+ if (customCommit === 'change') {
+ commitCustomDays(months === undefined ? 0 : logsRetentionMonthsToDays(months))
+ }
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSegmentedButton<PickerValue>
+ value={customSelected ? CUSTOM : value}
+ onChange={(selected) => {
+ if (selected === CUSTOM) {
+ setCustomSelected(true)
+ return
+ }
+ setCustomSelected(false)
+ committedCustomDays.current = undefined
+ onChange(selected)
+ }}
+ options={options}
+ size={size}
+ disabledReason={disabledReason ?? undefined}
+ />
+ {customSelected && (
+ <div className="flex items-center gap-2 flex-wrap">
+ <LemonInput
+ type="number"
+ size={size}
+ className="w-24"
+ min={1}
+ max={LOGS_RETENTION_MAX_MONTHS}
+ step={1}
+ value={customMonths}
+ onChange={handleCustomMonthsChange}
+ disabledReason={customDisabledReason}
+ data-attr={`${dataAttrPrefix}-custom-months`}
+ />
+ <span className="text-secondary text-sm">
+ months{customDays !== undefined ? ` (${customDays} days)` : ''}
+ </span>
+ {customCommit === 'apply' && (
+ <LemonButton
+ type="secondary"
+ size={size}
+ onClick={() => customDays !== undefined && commitCustomDays(customDays)}
+ disabledReason={customDisabledReason ?? customApplyDisabledReason}
+ data-attr={`${dataAttrPrefix}-custom-apply`}
+ >
+ Apply
+ </LemonButton>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx
index 1b0a77aacf5d..f5f02841b212 100644
--- a/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx
@@ -28,12 +28,13 @@ import { urls } from 'scenes/urls'
import { LogsRetentionRuleApi } from 'products/logs/frontend/generated/api.schemas'
+import { logsRetentionDaysLabel } from './logsRetentionPeriod'
import { logsRetentionSectionLogic } from './logsRetentionSectionLogic'
/** Read the retention tier out of the rule's config JSON for display. */
function retentionDaysLabel(rule: LogsRetentionRuleApi): string {
const days = (rule.config as Record<string, unknown> | undefined)?.retention_days
- return typeof days === 'number' ? `${days} days` : '—'
+ return typeof days === 'number' ? logsRetentionDaysLabel(days) : '—'
}
interface SortableRowProps {
diff --git a/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.test.ts b/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.test.ts
index 9305501b6e5b..10b753d0ca04 100644
--- a/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.test.ts
+++ b/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.test.ts
@@ -62,6 +62,16 @@ describe('logsRetentionFormLogic', () => {
expect(buildRetentionFormDefaults(rule).retention_days).toEqual(14)
})
+
+ it('keeps a stored custom period that is a whole number of months', () => {
+ const rule = {
+ name: 'half a year',
+ enabled: true,
+ config: { retention_days: 180, filter_group: { type: 'AND', values: [] } },
+ } as unknown as LogsRetentionRuleApi
+
+ expect(buildRetentionFormDefaults(rule).retention_days).toEqual(180)
+ })
})
/** Poll until `predicate` holds, yielding to timers/microtasks so kea listeners and loaders run. */
@@ -76,6 +86,33 @@ async function waitUntil(predicate: () => boolean, timeoutMs = 10000): Promise<v
await new Promise((resolve) => setTimeout(resolve, 20))
}
+describe('logsRetentionFormLogic validation', () => {
+ let logic: ReturnType<typeof logsRetentionFormLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = logsRetentionFormLogic({ rule: null })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it.each([0, 75])('reports an error for a retention period of %i days instead of saving it', async (days) => {
+ logic.actions.setRetentionFormValues(form({ retention_days: days }))
+ await expectLogic(logic, () => {
+ logic.actions.submitRetentionForm()
+ }).toDispatchActions(['submitRetentionFormFailure'])
+ expect(logic.values.retentionFormErrors.retention_days).toEqual(expect.stringContaining('whole number'))
+ })
+
+ it('accepts a custom whole-month period', () => {
+ logic.actions.setRetentionFormValues(form({ retention_days: 180 }))
+ expect(logic.values.retentionFormValidationErrors.retention_days).toBeUndefined()
+ })
+})
+
describe('logsRetentionFormLogic name suggestion', () => {
const EMPTY_GROUP = { type: FilterLogicalOperator.And, values: [] }
const PAYMENTS_GROUP = {
diff --git a/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.ts b/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.ts
index f46f774f93a7..877ecd4f19da 100644
--- a/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.ts
+++ b/products/logs/frontend/components/LogsRetention/logsRetentionFormLogic.ts
@@ -18,16 +18,20 @@ import {
import { LogsRetentionRuleApi, PatchedLogsRetentionRuleApi } from 'products/logs/frontend/generated/api.schemas'
import { logsRetentionRulesSettingsUrl } from 'products/logs/frontend/logsRetentionRulesSettingsUrl'
+import {
+ LOGS_RETENTION_DEFAULT_DAYS,
+ LOGS_RETENTION_MONTHS_HINT,
+ isValidLogsRetentionDays,
+} from './logsRetentionPeriod'
+
const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {
type: FilterLogicalOperator.And,
values: [],
}
-/** Retention tiers a rule may assign. Mirrors VALID_RETENTION_DAYS on the backend. */
-export const RETENTION_DAYS_OPTIONS: number[] = [14, 30]
-// 14 is the always-available free tier; 30 is entitlement-gated on the backend, so default to 14
-// to avoid a form that fails to save out of the box for orgs without the extended-retention feature.
-const DEFAULT_RETENTION_DAYS = 14
+// 14 is the always-available free tier; longer tiers are entitlement-gated on the backend, so default
+// to 14 to avoid a form that fails to save out of the box for orgs without the extended-retention feature.
+const DEFAULT_RETENTION_DAYS = LOGS_RETENTION_DEFAULT_DAYS
export interface LogsRetentionFormType {
name: string
@@ -87,8 +91,10 @@ export function buildRetentionFormDefaults(rule: LogsRetentionRuleApi | null): L
return {
name: rule.name,
enabled: rule.enabled ?? false,
+ // Keep any stored period the backend accepts, even when the flag that offered it is now off,
+ // so opening an existing rule does not silently change its retention.
retention_days:
- typeof storedDays === 'number' && RETENTION_DAYS_OPTIONS.includes(storedDays)
+ typeof storedDays === 'number' && isValidLogsRetentionDays(storedDays, true)
? storedDays
: DEFAULT_RETENTION_DAYS,
filter_group: extractFilterGroup(cfg.filter_group),
@@ -281,6 +287,10 @@ export const logsRetentionFormLogic = kea<logsRetentionFormLogicType>([
defaults: buildRetentionFormDefaults(props.rule),
errors: (form: LogsRetentionFormType) => ({
name: !form.name?.trim() ? 'Name is required' : undefined,
+ // The picker commits an invalid custom month count as it is typed, so the form must block saving it.
+ retention_days: !isValidLogsRetentionDays(form.retention_days, true)
+ ? LOGS_RETENTION_MONTHS_HINT
+ : undefined,
}),
submit: async (form: LogsRetentionFormType) => {
const projectId = String(values.currentTeamId)
diff --git a/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.test.ts b/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.test.ts
new file mode 100644
index 000000000000..3ad64d17c05a
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.test.ts
@@ -0,0 +1,29 @@
+import { isValidLogsRetentionDays, logsRetentionDaysLabel } from './logsRetentionPeriod'
+
+describe('logsRetentionPeriod', () => {
+ it.each([
+ [14, false, true],
+ [30, false, true],
+ [90, false, false],
+ [14, true, true],
+ [90, true, true],
+ [360, true, true],
+ [2580, true, true],
+ [45, true, false],
+ [2610, true, false],
+ [0, true, false],
+ [-30, true, false],
+ [30.5, true, false],
+ ])('isValidLogsRetentionDays(%i, allowCustom=%s) is %s', (days, allowCustom, expected) => {
+ expect(isValidLogsRetentionDays(days, allowCustom)).toBe(expected)
+ })
+
+ it.each([
+ [14, '14 days'],
+ [90, '90 days'],
+ [360, '1 year (360 days)'],
+ [390, '13 months (390 days)'],
+ ])('labels %i days as %s', (days, label) => {
+ expect(logsRetentionDaysLabel(days)).toBe(label)
+ })
+})
diff --git a/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.ts b/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.ts
new file mode 100644
index 000000000000..bab22c06550d
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/logsRetentionPeriod.ts
@@ -0,0 +1,48 @@
+// Mirrors `logs_retention_days_error` in `posthog/models/team/logs_retention.py`.
+export const LOGS_RETENTION_DEFAULT_DAYS = 14
+export const LOGS_RETENTION_MONTH_DAYS = 30
+// 86 thirty-day months cover 7 calendar years, the same ceiling as events retention.
+export const LOGS_RETENTION_MAX_MONTHS = 86
+export const LOGS_RETENTION_BASE_TIERS_DAYS: number[] = [14, 30]
+export const LOGS_RETENTION_PRESET_DAYS: number[] = [14, 30, 90, 360]
+export const LOGS_RETENTION_MONTHS_HINT = `Enter a whole number of months from 1 to ${LOGS_RETENTION_MAX_MONTHS}`
+
+export function isValidLogsRetentionDays(days: number, allowCustom: boolean): boolean {
+ if (!Number.isInteger(days)) {
+ return false
+ }
+ if (!allowCustom) {
+ return LOGS_RETENTION_BASE_TIERS_DAYS.includes(days)
+ }
+ if (days === LOGS_RETENTION_DEFAULT_DAYS) {
+ return true
+ }
+ return (
+ days > 0 &&
+ days <= LOGS_RETENTION_MONTH_DAYS * LOGS_RETENTION_MAX_MONTHS &&
+ days % LOGS_RETENTION_MONTH_DAYS === 0
+ )
+}
+
+export function isValidLogsRetentionMonths(months: number | undefined): months is number {
+ return typeof months === 'number' && Number.isInteger(months) && months >= 1 && months <= LOGS_RETENTION_MAX_MONTHS
+}
+
+export function logsRetentionMonthsToDays(months: number): number {
+ return months * LOGS_RETENTION_MONTH_DAYS
+}
+
+export function logsRetentionDaysToMonths(days: number): number | undefined {
+ return days > 0 && days % LOGS_RETENTION_MONTH_DAYS === 0 ? days / LOGS_RETENTION_MONTH_DAYS : undefined
+}
+
+export function logsRetentionDaysLabel(days: number): string {
+ if (days === 360) {
+ return '1 year (360 days)'
+ }
+ const months = logsRetentionDaysToMonths(days)
+ if (months !== undefined && months > 12) {
+ return `${months} months (${days} days)`
+ }
+ return `${days} days`
+}
diff --git a/products/logs/frontend/logsFeatureFlagKeys.ts b/products/logs/frontend/logsFeatureFlagKeys.ts
index 96fe7954b659..fb43e1db7535 100644
--- a/products/logs/frontend/logsFeatureFlagKeys.ts
+++ b/products/logs/frontend/logsFeatureFlagKeys.ts
@@ -3,6 +3,8 @@ import type { FeatureFlagLookupKey } from 'lib/constants'
/** `keyof FEATURE_FLAGS` for `useFeatureFlag` and settings `flag` — not remote slug strings. */
export const LogsFeatureFlagKeys = {
retentionRules: 'LOGS_SETTINGS_RETENTION_RULES',
+ customRetention: 'LOGS_SETTINGS_CUSTOM_RETENTION',
} as const satisfies {
retentionRules: FeatureFlagLookupKey
+ customRetention: FeatureFlagLookupKey
}