: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): support 30-day retention pricing (#72707)
Abheek Basud0058b3e10c6
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 5f44308e42c4..63bcaa1382cd 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -21,6 +21,7 @@ from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Organizationfrom posthog.models.organization import OrganizationMembership, OrganizationUsageInfo+from posthog.models.team.logs_retention import reset_revoked_logs_retentionfrom posthog.models.user import Userfrom ee.billing.billing_types import BillingProvider, BillingStatus@@ -263,9 +264,21 @@ class BillingManager:available_product_features_json = res.json()available_product_features = available_product_features_json.get("available_product_features", [])+ previous_feature_keys = {+ feature.get("key") for feature in (organization.available_product_features or []) if feature+ }organization.available_product_features = available_product_featuresorganization.save()+ # Only reset on a non-empty list: the retention reset is not self-healing, so an+ # empty error-path response must not permanently downgrade team settings.+ if available_product_features:+ revoked_feature_keys = previous_feature_keys - {+ feature.get("key") for feature in available_product_features if feature+ }+ if revoked_feature_keys:+ reset_revoked_logs_retention(organization, revoked_feature_keys)+return available_product_featuresdef update_billing_organization_users(self, organization: Organization) -> None:@@ -486,7 +499,16 @@ class BillingManager:should_update_org_billing_quotas = usage_changed or had_quota_limiting_markersavailable_product_features = data.get("available_product_features", None)+ revoked_feature_keys: set[str] = set()+ # An empty list is deliberately ignored: this runs on hot paths (get_billing, usage+ # reports) and a partial or error-path billing response must not downgrade the org.+ # Genuine cancellations still send the (non-empty) free-tier feature list.if available_product_features and available_product_features != organization.available_product_features:+ previous_feature_keys = {+ feature.get("key") for feature in (organization.available_product_features or []) if feature+ }+ new_feature_keys = {feature.get("key") for feature in available_product_features if feature}+ revoked_feature_keys = previous_feature_keys - new_feature_keysorganization.available_product_features = data["available_product_features"]org_modified = True@@ -523,6 +545,9 @@ class BillingManager:if org_modified:organization.save()+ if revoked_feature_keys:+ reset_revoked_logs_retention(organization, revoked_feature_keys)+if should_update_org_billing_quotas:update_org_billing_quotas(organization)diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.pyindex c221ef438713..b46e306baa18 100644--- a/ee/billing/test/test_billing_manager.py+++ b/ee/billing/test/test_billing_manager.py@@ -324,6 +324,106 @@ class TestBillingManager(BaseTest):assert organization.usage["events"].get("quota_limited_until") is Noneassert organization.usage["events"].get("quota_limiting_suspended_until") is None+ def test_update_org_details_resets_logs_retention_when_entitlement_revoked(self):+ organization = self.organization+ organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]+ organization.save()+ self.team.logs_settings = {"retention_days": 30, "json_parse_logs": True}+ self.team.save()++ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ billing_status = {"customer": {"available_product_features": [{"key": "surveys", "name": "Surveys"}]}}++ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))++ self.team.refresh_from_db()+ # Retention drops to the default; unrelated Logs settings survive.+ assert self.team.logs_settings == {"retention_days": 14, "json_parse_logs": True}++ def test_update_org_details_keeps_logs_retention_while_entitled(self):+ organization = self.organization+ organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]+ organization.save()+ self.team.logs_settings = {"retention_days": 30}+ self.team.save()++ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ billing_status = {+ "customer": {+ "available_product_features": [+ {"key": "logs_retention_30d", "name": "30-day logs retention"},+ {"key": "surveys", "name": "Surveys"},+ ]+ }+ }++ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))++ self.team.refresh_from_db()+ assert self.team.logs_settings == {"retention_days": 30}++ def test_update_org_details_ignores_empty_feature_list(self):+ """A partial or error-path billing response must not downgrade the org or reset retention."""+ organization = self.organization+ organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]+ organization.save()+ self.team.logs_settings = {"retention_days": 30}+ self.team.save()++ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ billing_status: dict[str, Any] = {"customer": {"available_product_features": []}}++ BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))++ organization.refresh_from_db()+ self.team.refresh_from_db()+ assert organization.available_product_features == [+ {"key": "logs_retention_30d", "name": "30-day logs retention"}+ ]+ assert self.team.logs_settings == {"retention_days": 30}++ @patch("ee.billing.billing_manager.requests.get")+ def test_update_available_product_features_resets_revoked_logs_retention(self, mock_get: MagicMock):+ organization = self.organization+ organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]+ organization.save()+ self.team.logs_settings = {"retention_days": 30}+ self.team.save()++ license = super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::key123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )++ # A cancellation lands the customer on free plans, which still carry (other) features.+ mock_get.return_value.status_code = 200+ mock_get.return_value.json.return_value = {+ "available_product_features": [{"key": "surveys", "name": "Surveys"}]+ }++ BillingManager(license).update_available_product_features(organization)++ organization.refresh_from_db()+ self.team.refresh_from_db()+ assert organization.available_product_features == [{"key": "surveys", "name": "Surveys"}]+ assert self.team.logs_settings == {"retention_days": 14}+@patch("ee.billing.billing_manager.update_org_billing_quotas", side_effect=Exception("Redis unavailable"))def test_update_org_details_saves_org_fields_before_recomputing_existing_quota_limits(self, update_org_billing_quotas_mock: MagicMockdiff --git a/ee/hogai/tools/read_billing_tool/tool.py b/ee/hogai/tools/read_billing_tool/tool.pyindex ae23c7b5550c..cff14570e33e 100644--- a/ee/hogai/tools/read_billing_tool/tool.py+++ b/ee/hogai/tools/read_billing_tool/tool.py@@ -41,6 +41,7 @@ USAGE_TYPES = [{"label": "Workflow push notifications", "value": "workflow_push_sent_in_period"},{"label": "Workflow destinations", "value": "workflow_billable_invocations_in_period"},{"label": "Logs ingested (MB)", "value": "logs_mb_in_period"},+ {"label": "Logs 30-day retention (MB)", "value": "logs_retention_30d_mb_in_period"},]diff --git a/frontend/src/scenes/billing/BillingProduct.tsx b/frontend/src/scenes/billing/BillingProduct.tsxindex 8afdf5ab5d53..c40b83a39cdf 100644--- a/frontend/src/scenes/billing/BillingProduct.tsx+++ b/frontend/src/scenes/billing/BillingProduct.tsx@@ -109,6 +109,13 @@ export const BillingProduct = ({ product }: { product: BillingProductV2Type }):const isTemporaryFreeProduct =(!product.tiered && !product.free_allocation && !product.inclusion_only) ||(product.tiered && product.tiers?.length === 1 && product.tiers[0].unit_amount_usd === '0')+ const monetaryGaugeProduct = {+ ...product,+ unit: '$',+ display_unit: null,+ display_decimals: null,+ display_divisor: null,+ }// If the feature flag `billing_hide_product_{product.type}` is true,// don't show the product in the billing page.@@ -230,10 +237,7 @@ export const BillingProduct = ({ product }: { product: BillingProductV2Type }):<div className="mt-6 mb-4 ml-2"><div className="grid grid-cols-[1fr_130px_100px] gap-4 items-center"><div>- <BillingGauge- items={combinedMonetaryGaugeItems}- product={{ ...product, unit: '$' }}- />+ <BillingGauge items={combinedMonetaryGaugeItems} product={monetaryGaugeProduct} /></div><Tooltiptitle={`The current ${diff --git a/frontend/src/scenes/billing/BillingProductPricingTable.tsx b/frontend/src/scenes/billing/BillingProductPricingTable.tsxindex aa5cb7428677..5837884e6c3f 100644--- a/frontend/src/scenes/billing/BillingProductPricingTable.tsx+++ b/frontend/src/scenes/billing/BillingProductPricingTable.tsx@@ -232,9 +232,13 @@ export const BillingProductPricingTable = ({})}+ const shouldShowPricingTable =+ !!tableTierData &&+ (product.tiered || product.tiers?.some((tier) => parseFloat(tier.unit_amount_usd || '0') > 0))+return (<div className="pl-16 pb-8">- {product.tiered && tableTierData ? (+ {shouldShowPricingTable ? (<><LemonTablestealth@@ -250,9 +254,11 @@ export const BillingProductPricingTable = ({rowExpandable: (row) => !!row.subrows?.rows?.length,}}/>- <LemonBanner type="warning" className="text-sm pt-2 mt-2">- Tier breakdowns are updated once daily and may differ from the gauge above.- </LemonBanner>+ {product.tiered && (+ <LemonBanner type="warning" className="text-sm pt-2 mt-2">+ Tier breakdowns are updated once daily and may differ from the gauge above.+ </LemonBanner>+ )}</>) : parseFloat(product.unit_amount_usd || '0') > 0 ? (<LemonTablediff --git a/frontend/src/scenes/billing/billing-utils.ts b/frontend/src/scenes/billing/billing-utils.tsindex ad206272ebf4..49c2c2d5a5b5 100644--- a/frontend/src/scenes/billing/billing-utils.ts+++ b/frontend/src/scenes/billing/billing-utils.ts@@ -19,10 +19,16 @@ import type { BillingFilters, BillingSeriesForCsv, BillingUsageInteractionProps,import { BillingGaugeItemKind, BillingGaugeItemType } from './types'export const isProductVariantPrimary = (productType: string): boolean =>- ['session_replay', 'realtime_destinations', 'data_warehouse', 'workflows_emails'].includes(productType)+ ['session_replay', 'realtime_destinations', 'data_warehouse', 'workflows_emails', 'logs'].includes(productType)export const isProductVariantSecondary = (productType: string): boolean =>- ['mobile_replay', 'batch_exports', 'data_warehouse_historical', 'workflows_destinations'].includes(productType)+ [+ 'mobile_replay',+ 'batch_exports',+ 'data_warehouse_historical',+ 'workflows_destinations',+ 'logs_retention_30d',+ ].includes(productType)export const calculateFreeTier = (product: BillingProductV2Type | BillingProductV2AddonType): number => {// If subscribed and has tiers, check if the first tier is freediff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.tsindex eebe36749e06..c1a361519160 100644--- a/frontend/src/scenes/billing/billingProductLogic.ts+++ b/frontend/src/scenes/billing/billingProductLogic.ts@@ -1004,6 +1004,8 @@ export const billingProductLogic = kea<billingProductLogicType>([session_replay: 'Web session replay',data_warehouse: 'Synced rows',data_warehouse_historical: 'Free historical synced rows',+ logs: 'Logs ingestion (14-day retention)',+ logs_retention_30d: '30-day retention',}const mainProduct = product as BillingProductV2Typediff --git a/frontend/src/scenes/billing/constants.ts b/frontend/src/scenes/billing/constants.tsindex 3f7bb9fed682..e29a3d77e34a 100644--- a/frontend/src/scenes/billing/constants.ts+++ b/frontend/src/scenes/billing/constants.ts@@ -23,6 +23,7 @@ export const USAGE_TYPES = [{ label: 'Workflow push notifications', value: 'workflow_push_sent_in_period' },{ label: 'Workflow destinations', value: 'workflow_billable_invocations_in_period' },{ label: 'Logs ingested (MB)', value: 'logs_mb_in_period' },+ { label: 'Logs 30-day retention (MB)', value: 'logs_retention_30d_mb_in_period' },] as constexport type UsageTypeOption = (typeof USAGE_TYPES)[number]diff --git a/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx b/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsxindex ead67d24e7a8..f484796685c8 100644--- a/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx+++ b/frontend/src/scenes/settings/environment/LogsCaptureSettings.tsx@@ -7,10 +7,11 @@ import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArimport { TeamMembershipLevel } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'-import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { AccessControlLevel, AccessControlResourceType, AvailableFeature } from '~/types'-const VALID_RETENTION_DAYS = [14, 30, 90] as const+const VALID_RETENTION_DAYS = [14, 30] as consttype LogsRetentionDays = (typeof VALID_RETENTION_DAYS)[number]export function LogsCaptureSettings(): JSX.Element {@@ -115,6 +116,7 @@ export function LogsPiiScrubSettings(): JSX.Element {export function LogsRetentionSettings(): JSX.Element {const { updateCurrentTeam } = useActions(teamLogic)const { currentTeam, currentTeamLoading } = useValues(teamLogic)+ const { hasAvailableFeature } = useValues(userLogic)const restrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,@@ -139,6 +141,12 @@ export function LogsRetentionSettings(): JSX.Element {}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)@@ -152,15 +160,9 @@ export function LogsRetentionSettings(): JSX.Element {{value: 30,label: '30 days',- disabledReason,+ disabledReason: disabledReason ?? retentionFeatureDisabledReason(30),'data-attr': 'logs-retention-button-30d',},- {- value: 90,- label: '90 days',- disabledReason,- 'data-attr': 'logs-retention-button-90d',- },]}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 2de6a41d53e7..fbe1cdab98b5 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -111,6 +111,7 @@ export enum AvailableFeature {DATA_PIPELINES = 'data_pipelines',RECORDINGS_PLAYLISTS = 'recordings_playlists',SESSION_REPLAY_DATA_RETENTION = 'session_replay_data_retention',+ LOGS_RETENTION_30D = 'logs_retention_30d',CONSOLE_LOGS = 'console_logs',RECORDINGS_PERFORMANCE = 'recordings_performance',SESSION_REPLAY_NETWORK_PAYLOADS = 'session_replay_network_payloads',diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 00e757585dbc..a57f8dc7d4b0 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -27,7 +27,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import TeamBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication-from posthog.constants import AvailableFeature+from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS, AvailableFeaturefrom posthog.decorators import disallow_if_impersonatedfrom posthog.event_usage import report_user_actionfrom posthog.geoip import get_geoip_properties@@ -46,7 +46,7 @@ from posthog.models.data_color_theme import DataColorThemefrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfigfrom posthog.models.filters.utils import validate_group_type_indexfrom posthog.models.group_type_mapping import cached_group_types_for_team-from posthog.models.organization import OrganizationMembership+from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.product_intent.product_intent import (ProductIntentSerializer,cached_product_intents_for_team,@@ -792,6 +792,22 @@ def get_or_mint_live_events_token(team: Team, user_id: int | None) -> str:return token+def _get_organization_for_logs_settings_check(serializer: serializers.BaseSerializer) -> Organization | None:+ if serializer.instance is not None:+ team = (+ serializer.instance.passthrough_team+ if hasattr(serializer.instance, "passthrough_team")+ else serializer.instance+ )+ return team.organization++ get_organization = serializer.context.get("get_organization")+ if callable(get_organization):+ return cast(Organization | None, get_organization())++ return None++class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin, UserAccessControlSerializerMixin):instance: Team | None_group_types_cache: list[dict[str, Any]] | None = None@@ -1451,10 +1467,10 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinreturn value- VALID_RETENTION_DAYS = {14, 30, 90}+ VALID_RETENTION_DAYS = {14, 30}def validate_logs_settings(self, value: dict | None) -> dict | None:- if value is None or not self.instance:+ if value is None:return valuenew_retention = value.get("retention_days")@@ -1463,14 +1479,25 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinf"retention_days must be one of {sorted(TeamSerializer.VALID_RETENTION_DAYS)}")- # Only validate retention changes if we have an existing instance- logs_settings = (- self.instance.passthrough_team.logs_settings- if hasattr(self.instance, "passthrough_team")- else self.instance.logs_settings+ 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++ if new_retention is not None and old_retention != new_retention:+ required_feature = LOGS_RETENTION_FEATURES_BY_DAYS.get(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):+ raise exceptions.PermissionDenied(+ f"This organization does not have permission to set Logs retention to {new_retention} days."+ )++ # Only validate retention throttling if we have an existing retention settingif self.instance and logs_settings:- old_retention = logs_settings.get("retention_days")old_last_updated = logs_settings.get("retention_last_updated")# Check if retention_days is being changeddiff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex a0e08c3dd352..6ba0f8b48db2 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -130,6 +130,62 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.organization.available_product_features = featuresself.organization.save()+ def _set_unlimited_projects_with_logs_retention(self, *features: AvailableFeature) -> None:+ self._set_unlimited_projects()+ self.organization.available_product_features = [+ *(self.organization.available_product_features or []),+ *[{"key": feature.value, "name": feature.value.replace("_", " ")} for feature in features],+ ]+ self.organization.save()++ def test_project_creation_rejects_paid_logs_retention_without_feature(self):+ self._set_unlimited_projects()++ response = self.client.post(+ "/api/projects/",+ {"name": "Logs Project", "logs_settings": {"retention_days": 30}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertIn("30 days", response.json()["detail"])++ def test_project_creation_allows_base_logs_retention_without_feature(self):+ self._set_unlimited_projects()++ response = self.client.post(+ "/api/projects/",+ {"name": "Logs Project", "logs_settings": {"retention_days": 14}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["logs_settings"]["retention_days"], 14)++ def test_project_creation_allows_paid_logs_retention_with_matching_feature(self):+ self._set_unlimited_projects_with_logs_retention(AvailableFeature.LOGS_RETENTION_30D)++ response = self.client.post(+ "/api/projects/",+ {"name": "Logs Project", "logs_settings": {"retention_days": 30}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["logs_settings"]["retention_days"], 30)++ def test_project_creation_rejects_invalid_logs_retention(self):+ self._set_unlimited_projects()++ response = self.client.post(+ "/api/projects/",+ {"name": "Logs Project", "logs_settings": {"retention_days": 45}},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("retention_days must be one of", response.json()["detail"])+def test_member_cannot_create_project_by_default(self):self._set_unlimited_projects()self.organization_membership.level = OrganizationMembership.Level.MEMBERdiff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 9d3eff3b4cfb..c4c6494c6e82 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -1715,7 +1715,15 @@ def team_api_test_factory():response = self.client.post(f"/api/environments/{self.team.id}/generate_conversations_public_token/")assert response.status_code == status.HTTP_403_FORBIDDEN+ def _grant_logs_retention_features(self, *features: AvailableFeature) -> None:+ self.organization.available_product_features = [+ {"key": feature.value, "name": feature.value.replace("_", " ")} for feature in features+ ]+ self.organization.save()+def test_logs_settings_retention_24_hour_restriction(self):+ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)+# Set initial retention - first update doesn't set retention_last_updatedwith freeze_time("2025-01-01T00:00:00Z"):response = self.client.patch(@@ -1738,7 +1746,7 @@ def team_api_test_factory():with freeze_time("2025-01-01T12:00:00Z"):response = self.client.patch("/api/environments/@current/",- {"logs_settings": {"retention_days": 90}},+ {"logs_settings": {"retention_days": 30}},)assert response.status_code == status.HTTP_400_BAD_REQUESTassert "24 hours" in response.json()["detail"]@@ -1747,12 +1755,12 @@ def team_api_test_factory():with freeze_time("2025-01-02T00:00:01Z"):response = self.client.patch("/api/environments/@current/",- {"logs_settings": {"retention_days": 90}},+ {"logs_settings": {"retention_days": 30}},)assert response.status_code == status.HTTP_200_OKdef test_logs_settings_retention_invalid_values_rejected(self):- for invalid_days in [7, 15, 20, 45, 100]:+ for invalid_days in [7, 15, 20, 45, 90, 100]:response = self.client.patch("/api/environments/@current/",{"logs_settings": {"retention_days": invalid_days}},@@ -1762,7 +1770,40 @@ def team_api_test_factory():)assert "retention_days must be one of" in response.json()["detail"]+ def test_logs_settings_retention_requires_matching_feature(self):+ response = self.client.patch(+ "/api/environments/@current/",+ {"logs_settings": {"retention_days": 30}},+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert "30 days" in response.json()["detail"]++ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)+ response = self.client.patch(+ "/api/environments/@current/",+ {"logs_settings": {"retention_days": 30}},+ )+ assert response.status_code == status.HTTP_200_OK++ def test_logs_settings_retention_downgrade_allowed_after_feature_removed(self):+ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)++ response = self.client.patch(+ "/api/environments/@current/",+ {"logs_settings": {"retention_days": 30}},+ )+ assert response.status_code == status.HTTP_200_OK++ self._grant_logs_retention_features()+ response = self.client.patch(+ "/api/environments/@current/",+ {"logs_settings": {"retention_days": 14}},+ )+ assert response.status_code == status.HTTP_200_OK+def test_logs_settings_non_retention_changes_not_restricted(self):+ self._grant_logs_retention_features(AvailableFeature.LOGS_RETENTION_30D)+# Set initial retentionwith freeze_time("2025-01-01T00:00:00Z"):response = self.client.patch(diff --git a/posthog/constants.py b/posthog/constants.pyindex 3bed294c2f53..851deb6310c7 100644--- a/posthog/constants.py+++ b/posthog/constants.py@@ -49,12 +49,18 @@ class AvailableFeature(StrEnum):ORGANIZATION_APP_QUERY_CONCURRENCY_LIMIT = "organization_app_query_concurrency_limit"SESSION_REPLAY_DATA_RETENTION = "session_replay_data_retention"PRODUCT_ANALYTICS_DATA_RETENTION = "product_analytics_data_retention"+ LOGS_RETENTION_30D = "logs_retention_30d"AUDIT_LOGS = "audit_logs"APPROVALS = "approvals"XAA_AUTHENTICATION = "xaa_authentication"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/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.pyindex 6f4452c6c25f..3cf9c69cc652 100644--- a/posthog/management/commands/execute_temporal_workflow.py+++ b/posthog/management/commands/execute_temporal_workflow.py@@ -30,6 +30,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWSfrom posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS+from products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -152,6 +153,7 @@ class Command(BaseCommand):+ DATA_MODELING_WORKFLOWS+ LLM_ANALYTICS_WORKFLOWS+ EVENT_SCREENSHOTS_WORKFLOWS+ + LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS+ RASTERIZE_RECORDING_WORKFLOWS+ SUMMARIZATION_SWEEP_WORKFLOWS+ WA_DIGEST_WORKFLOWSdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 55a0b3d83906..47be3e988c31 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -213,6 +213,10 @@ from products.logs.backend.facade.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,)+from products.logs.backend.temporal.retention_entitlements import (+ ACTIVITIES as LOGS_RETENTION_ENTITLEMENTS_ACTIVITIES,+ WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS,+)from products.notebooks.backend.facade.temporal import (ACTIVITIES as NOTEBOOKS_ACTIVITIES,WORKFLOWS as NOTEBOOKS_WORKFLOWS,@@ -321,7 +325,8 @@ _task_queue_specs = [+ JOB_LOGS_WORKFLOWS+ CI_SIGNALS_WORKFLOWS+ NOTEBOOKS_WORKFLOWS- + SIGNUP_ENRICHMENT_WORKFLOWS,+ + SIGNUP_ENRICHMENT_WORKFLOWS+ + LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ DELETE_TEAMS_ACTIVITIES@@ -341,7 +346,8 @@ _task_queue_specs = [+ JOB_LOGS_ACTIVITIES+ CI_SIGNALS_ACTIVITIES+ NOTEBOOKS_ACTIVITIES- + SIGNUP_ENRICHMENT_ACTIVITIES,+ + SIGNUP_ENRICHMENT_ACTIVITIES+ + LOGS_RETENTION_ENTITLEMENTS_ACTIVITIES,),# Dedicated landing zone for signup enrichment. Defaults to the general-purpose queue name (so it# merges into that fleet until a dedicated worker exists); setting SIGNUP_ENRICHMENT_TASK_QUEUE on a@@ -504,7 +510,7 @@ _task_queue_specs = [_workflows: defaultdict[str, set[type[PostHogWorkflow]]] = defaultdict(set)_activities: defaultdict[str, set[typing.Callable[..., typing.Any]]] = defaultdict(set)for task_queue_name, workflows_for_queue, activities_for_queue in _task_queue_specs:- _workflows[task_queue_name].update(workflows_for_queue) # type: ignore+ _workflows[task_queue_name].update(workflows_for_queue)_activities[task_queue_name].update(activities_for_queue)WORKFLOWS_DICT = _workflowsdiff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.pyindex 92392b13ae0d..27cd41f99f45 100644--- a/posthog/management/commands/start_temporal_workflow.py+++ b/posthog/management/commands/start_temporal_workflow.py@@ -30,6 +30,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWSfrom posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS+from products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -156,6 +157,7 @@ class Command(BaseCommand):+ WEEKLY_DIGEST_WORKFLOWS+ EVENT_SCREENSHOTS_WORKFLOWS+ HEALTH_CHECK_WORKFLOWS+ + LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS+ WA_DIGEST_WORKFLOWS+ SURFACING_SCORING_SWEEP_WORKFLOWS)diff --git a/posthog/models/team/logs_retention.py b/posthog/models/team/logs_retention.pynew file mode 100644index 000000000000..95edf35eb5c6--- /dev/null+++ b/posthog/models/team/logs_retention.py@@ -0,0 +1,42 @@+import structlog++from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS+from posthog.models.organization import Organization+from posthog.models.team.team import Team++logger = structlog.get_logger(__name__)++DEFAULT_LOGS_RETENTION_DAYS = 14+++def reset_revoked_logs_retention(organization: Organization, revoked_feature_keys: set[str]) -> int:+ """Reset team Logs retention to the default when its required feature was revoked.++ Called from the billing feature-refresh paths (customer update messages, trial+ cancellation) so that cancellations immediately stop applying paid retention to+ 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:+ return 0++ teams = list(+ Team.objects.filter(organization=organization, logs_settings__retention_days__in=revoked_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}++ if teams:+ Team.objects.bulk_update(teams, ["logs_settings"])+ logger.info(+ "Logs retention reset after entitlement revocation",+ organization_id=str(organization.id),+ teams_reset=len(teams),+ )+ return len(teams)diff --git a/products/logs/backend/temporal/retention_entitlements/__init__.py b/products/logs/backend/temporal/retention_entitlements/__init__.pynew file mode 100644index 000000000000..b48df2c31c4d--- /dev/null+++ b/products/logs/backend/temporal/retention_entitlements/__init__.py@@ -0,0 +1,12 @@+from products.logs.backend.temporal.retention_entitlements.activities import enforce_logs_retention_entitlements+from products.logs.backend.temporal.retention_entitlements.workflow import EnforceLogsRetentionEntitlementsWorkflow++WORKFLOWS: list = [EnforceLogsRetentionEntitlementsWorkflow]+ACTIVITIES: list = [enforce_logs_retention_entitlements]++__all__ = [+ "ACTIVITIES",+ "EnforceLogsRetentionEntitlementsWorkflow",+ "WORKFLOWS",+ "enforce_logs_retention_entitlements",+]diff --git a/products/logs/backend/temporal/retention_entitlements/activities.py b/products/logs/backend/temporal/retention_entitlements/activities.pynew file mode 100644index 000000000000..1cf8b61a42dd--- /dev/null+++ b/products/logs/backend/temporal/retention_entitlements/activities.py@@ -0,0 +1,83 @@+from temporalio import activity++from posthog.constants import LOGS_RETENTION_FEATURES_BY_DAYS+from posthog.models import Team+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.temporal.retention_entitlements.types import (+ EnforceLogsRetentionEntitlementsInput,+ EnforceLogsRetentionEntitlementsOutput,+)++LOGGER = get_write_only_logger(__name__)++[email protected](name="enforce-logs-retention-entitlements")+async def enforce_logs_retention_entitlements(+ input: EnforceLogsRetentionEntitlementsInput,+) -> EnforceLogsRetentionEntitlementsOutput:+ """Reset saved paid Logs retention settings when the organization no longer has the matching feature."""+ async with Heartbeater():+ logger = LOGGER.bind(dry_run=input.dry_run)+ batch_size = max(1, input.batch_size)+ teams_to_update: list[Team] = []+ teams_checked = 0++ # 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()))+ .select_related("organization")+ .only("id", "name", "organization", "organization__available_product_features", "logs_settings")+ ):+ logs_settings = team.logs_settings or {}+ retention_days = logs_settings.get("retention_days")+ if not isinstance(retention_days, int):+ continue++ required_feature = LOGS_RETENTION_FEATURES_BY_DAYS.get(retention_days)+ if not required_feature:+ continue++ teams_checked += 1+ organization = team.organization+ if organization.is_feature_available(required_feature):+ continue++ # Preserve unrelated Logs settings such as JSON parsing and PII scrubbing.+ team.logs_settings = {+ **logs_settings,+ "retention_days": 14,+ }+ teams_to_update.append(team)++ logger.info(+ "Logs retention period setting forcibly reduced",+ team_id=team.id,+ team_name=team.name,+ organization_id=organization.id,+ retention_period_before=retention_days,+ retention_period_after=14,+ )++ if teams_checked % batch_size == 0:+ logger.info("Processed Logs retention entitlement batch", teams_checked=teams_checked)++ if not input.dry_run and teams_to_update:+ await database_sync_to_async(Team.objects.bulk_update)(+ teams_to_update,+ ["logs_settings"],+ batch_size=batch_size,+ )++ logger.info(+ "Logs retention entitlement enforcement complete",+ teams_checked=teams_checked,+ teams_reset=len(teams_to_update),+ )+ return EnforceLogsRetentionEntitlementsOutput(+ teams_checked=teams_checked,+ teams_reset=len(teams_to_update),+ )diff --git a/products/logs/backend/temporal/retention_entitlements/types.py b/products/logs/backend/temporal/retention_entitlements/types.pynew file mode 100644index 000000000000..b803f781c975--- /dev/null+++ b/products/logs/backend/temporal/retention_entitlements/types.py@@ -0,0 +1,13 @@+from dataclasses import dataclass+++@dataclass(frozen=True)+class EnforceLogsRetentionEntitlementsInput:+ dry_run: bool+ batch_size: int = 100+++@dataclass(frozen=True)+class EnforceLogsRetentionEntitlementsOutput:+ teams_checked: int+ teams_reset: intdiff --git a/products/logs/backend/temporal/retention_entitlements/workflow.py b/products/logs/backend/temporal/retention_entitlements/workflow.pynew file mode 100644index 000000000000..633822a108d9--- /dev/null+++ b/products/logs/backend/temporal/retention_entitlements/workflow.py@@ -0,0 +1,36 @@+from datetime import timedelta++from temporalio import common, workflow++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from products.logs.backend.temporal.retention_entitlements.activities import enforce_logs_retention_entitlements+ from products.logs.backend.temporal.retention_entitlements.types import (+ EnforceLogsRetentionEntitlementsInput,+ EnforceLogsRetentionEntitlementsOutput,+ )++[email protected](name="enforce-logs-retention-entitlements")+class EnforceLogsRetentionEntitlementsWorkflow(PostHogWorkflow):+ """Manual reconciliation workflow for Logs retention entitlements.++ This workflow is registered for explicit runs via Temporal management commands,+ but is not added to `posthog.temporal.schedule.schedules`.+ """++ inputs_cls = EnforceLogsRetentionEntitlementsInput++ @workflow.run+ async def run(self, input: EnforceLogsRetentionEntitlementsInput) -> EnforceLogsRetentionEntitlementsOutput:+ return await workflow.execute_activity(+ enforce_logs_retention_entitlements,+ input,+ start_to_close_timeout=timedelta(minutes=15),+ retry_policy=common.RetryPolicy(+ maximum_attempts=2,+ initial_interval=timedelta(minutes=1),+ ),+ heartbeat_timeout=timedelta(minutes=5),+ )diff --git a/products/logs/backend/test/test_retention_entitlements.py b/products/logs/backend/test/test_retention_entitlements.pynew file mode 100644index 000000000000..36107313484e--- /dev/null+++ b/products/logs/backend/test/test_retention_entitlements.py@@ -0,0 +1,86 @@+import uuid++import pytest++from asgiref.sync import sync_to_async+from temporalio.testing import ActivityEnvironment++from posthog.constants import AvailableFeature+from posthog.models import Organization, Team++from products.logs.backend.temporal.retention_entitlements.activities import enforce_logs_retention_entitlements+from products.logs.backend.temporal.retention_entitlements.types import (+ EnforceLogsRetentionEntitlementsInput,+ EnforceLogsRetentionEntitlementsOutput,+)+++async def _create_organization(features: list[AvailableFeature]) -> Organization:+ organization = await sync_to_async(Organization.objects.create)(name=f"Test org {uuid.uuid4()}")+ organization.available_product_features = [{"key": feature, "name": feature.value} for feature in features]+ await sync_to_async(organization.save)()+ return organization+++async def _create_team(organization: Organization, retention_days: int, **logs_settings: object) -> Team:+ return await sync_to_async(Team.objects.create)(+ organization=organization,+ name=f"Test team {uuid.uuid4()}",+ api_token=str(uuid.uuid4()),+ logs_settings={+ "retention_days": retention_days,+ **logs_settings,+ },+ )+++async def _refresh_team(team: Team) -> Team:+ return await sync_to_async(Team.objects.get)(id=team.id)++[email protected]_db(transaction=True)+async def test_enforce_logs_retention_entitlements_resets_only_over_entitled_teams() -> None:+ org_with_30d = await _create_organization([AvailableFeature.LOGS_RETENTION_30D])+ org_without_retention = await _create_organization([])++ team_14d = await _create_team(org_without_retention, 14)+ team_30d_allowed = await _create_team(org_with_30d, 30)+ team_30d_blocked = await _create_team(+ org_without_retention,+ 30,+ capture_console_logs=True,+ retention_last_updated="2026-06-01T00:00:00Z",+ )++ output: EnforceLogsRetentionEntitlementsOutput = await ActivityEnvironment().run(+ enforce_logs_retention_entitlements,+ EnforceLogsRetentionEntitlementsInput(dry_run=False),+ )++ assert output.teams_checked == 2+ assert output.teams_reset == 1++ assert (await _refresh_team(team_14d)).logs_settings["retention_days"] == 14+ assert (await _refresh_team(team_30d_allowed)).logs_settings["retention_days"] == 30++ blocked_30d_settings = (await _refresh_team(team_30d_blocked)).logs_settings+ assert blocked_30d_settings["retention_days"] == 14+ assert blocked_30d_settings["capture_console_logs"] is True+ assert blocked_30d_settings["retention_last_updated"] == "2026-06-01T00:00:00Z"++[email protected]_db(transaction=True)+async def test_enforce_logs_retention_entitlements_dry_run_does_not_update_team() -> None:+ organization = await _create_organization([])+ team = await _create_team(organization, 30)++ output: EnforceLogsRetentionEntitlementsOutput = await ActivityEnvironment().run(+ enforce_logs_retention_entitlements,+ EnforceLogsRetentionEntitlementsInput(dry_run=True),+ )++ assert output.teams_checked == 1+ assert output.teams_reset == 1+ assert (await _refresh_team(team)).logs_settings["retention_days"] == 30