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(retention): slo-track the sync and emit per-team change events (#76029)

Andy Zhaof97bebc1eaec
diff --git a/posthog/slo/types.py b/posthog/slo/types.py
index b384ea9eb4ca..ce9bf2db1d3e 100644
--- a/posthog/slo/types.py
+++ b/posthog/slo/types.py
@@ -18,6 +18,7 @@ class SloOperation(StrEnum):
QUERY_SERVICE = "query_service"
DASHBOARD_WIDGET_DELIVERY = "dashboard_widget_delivery"
PULSE_BRIEF_GENERATION = "pulse-brief-generation"
+ SYNC_EVENTS_RETENTION = "sync_events_retention"
class SloOutcome(StrEnum):
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 9665be2c62b8..2e525c475368 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -20,6 +20,7 @@ from temporalio.client import (
ScheduleSpec,
)
+from posthog.slo.types import SloArea, SloConfig, SloOperation
from posthog.temporal.ai.checkpoint_compaction.schedule import (
create_checkpoint_compaction_schedule,
should_register_checkpoint_compaction_schedule,
@@ -383,7 +384,16 @@ async def create_sync_events_retention_schedule(client: Client):
sync_events_retention_schedule = Schedule(
action=ScheduleActionStartWorkflow(
"sync-events-retention",
- SyncEventsRetentionInput(dry_run=False),
+ SyncEventsRetentionInput(
+ dry_run=False,
+ slo=SloConfig(
+ operation=SloOperation.SYNC_EVENTS_RETENTION,
+ area=SloArea.ANALYTIC_PLATFORM,
+ team_id=0,
+ resource_id="sync-events-retention",
+ distinct_id="sync-events-retention",
+ ),
+ ),
id="sync-events-retention-schedule",
task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,
retry_policy=common.RetryPolicy(
diff --git a/posthog/temporal/sync_events_retention/activities.py b/posthog/temporal/sync_events_retention/activities.py
index 2a71fc09731a..3c4d5c2a01b1 100644
--- a/posthog/temporal/sync_events_retention/activities.py
+++ b/posthog/temporal/sync_events_retention/activities.py
@@ -1,17 +1,37 @@
+import asyncio
+
+from django.conf import settings
+
from temporalio import activity
from posthog.constants import AvailableFeature
from posthog.models.team import Team
from posthog.models.team.event_retention import parse_events_feature_to_months
+from posthog.ph_client import ph_scoped_capture
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_write_only_logger
-from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput
+from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput, SyncEventsRetentionResult
LOGGER = get_write_only_logger()
+def _capture_retention_changes(changes: list[dict]) -> None:
+ with ph_scoped_capture() as capture:
+ for change in changes:
+ capture(
+ distinct_id="sync-events-retention",
+ event="events_retention_changed",
+ properties={
+ **change,
+ "cloud_deployment": settings.CLOUD_DEPLOYMENT,
+ # Personless: a mass change (e.g. a policy flip) must not mint one person per team.
+ "$process_person_profile": False,
+ },
+ )
+
+
@activity.defn(name="sync-events-retention")
-async def sync_events_retention(input: SyncEventsRetentionInput) -> None:
+async def sync_events_retention(input: SyncEventsRetentionInput) -> SyncEventsRetentionResult:
"""Reconcile every team's events retention window with its billing entitlement.
Events retention is plan-derived and not user-editable, so we set it outright — unlike replay enforcement, which
@@ -40,17 +60,28 @@ async def sync_events_retention(input: SyncEventsRetentionInput) -> None:
last_pk = teams[-1].pk
teams_to_update: list[Team] = []
+ changes: list[dict] = []
for team in teams:
retention_feature = team.organization.get_available_feature(
AvailableFeature.PRODUCT_ANALYTICS_DATA_RETENTION
)
target_months = parse_events_feature_to_months(retention_feature)
if team.event_retention_months != target_months:
+ changes.append(
+ {
+ "team_id": team.pk,
+ "organization_id": str(team.organization_id),
+ "retention_months_before": team.event_retention_months,
+ "retention_months_after": target_months,
+ }
+ )
team.event_retention_months = target_months
teams_to_update.append(team)
if teams_to_update and not input.dry_run:
await Team.objects.abulk_update(teams_to_update, ["event_retention_months"])
+ # Per batch and off-thread so a mass change can't stall heartbeats or overflow the client queue.
+ await asyncio.to_thread(_capture_retention_changes, changes)
total_processed += len(teams)
total_updated += len(teams_to_update)
@@ -60,3 +91,5 @@ async def sync_events_retention(input: SyncEventsRetentionInput) -> None:
logger.info(f"DRY RUN: Would have updated {total_updated} of {total_processed} teams")
else:
logger.info(f"Updated {total_updated} of {total_processed} teams")
+
+ return SyncEventsRetentionResult(total_processed=total_processed, total_updated=total_updated)
diff --git a/posthog/temporal/sync_events_retention/types.py b/posthog/temporal/sync_events_retention/types.py
index 3f321ae078e0..e452d38cf3c9 100644
--- a/posthog/temporal/sync_events_retention/types.py
+++ b/posthog/temporal/sync_events_retention/types.py
@@ -1,7 +1,17 @@
from dataclasses import dataclass
+from typing import Optional
+
+from posthog.slo.types import SloConfig
@dataclass(frozen=True)
class SyncEventsRetentionInput:
dry_run: bool
batch_size: int = 1000
+ slo: Optional[SloConfig] = None
+
+
+@dataclass(frozen=True)
+class SyncEventsRetentionResult:
+ total_processed: int
+ total_updated: int
diff --git a/posthog/temporal/sync_events_retention/workflow.py b/posthog/temporal/sync_events_retention/workflow.py
index eabea5dfb759..b8865904362e 100644
--- a/posthog/temporal/sync_events_retention/workflow.py
+++ b/posthog/temporal/sync_events_retention/workflow.py
@@ -4,7 +4,7 @@ from temporalio import common, workflow
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.sync_events_retention.activities import sync_events_retention
-from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput
+from posthog.temporal.sync_events_retention.types import SyncEventsRetentionInput, SyncEventsRetentionResult
@workflow.defn(name="sync-events-retention")
@@ -13,7 +13,7 @@ class SyncEventsRetentionWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, input: SyncEventsRetentionInput) -> None:
- await workflow.execute_activity(
+ result: SyncEventsRetentionResult = await workflow.execute_activity(
sync_events_retention,
input,
start_to_close_timeout=timedelta(minutes=120),
@@ -23,3 +23,7 @@ class SyncEventsRetentionWorkflow(PostHogWorkflow):
),
heartbeat_timeout=timedelta(minutes=5),
)
+ if input.slo is not None:
+ input.slo.completion_properties.update(
+ {"total_processed": result.total_processed, "total_updated": result.total_updated}
+ )
diff --git a/posthog/temporal/tests/sync_events_retention/test_activities.py b/posthog/temporal/tests/sync_events_retention/test_activities.py
index 29a2bd96e754..1779b92819a1 100644
--- a/posthog/temporal/tests/sync_events_retention/test_activities.py
+++ b/posthog/temporal/tests/sync_events_retention/test_activities.py
@@ -1,4 +1,7 @@
+from contextlib import contextmanager
+
import pytest
+from unittest.mock import patch
from asgiref.sync import sync_to_async
from temporalio.testing import ActivityEnvironment
@@ -46,6 +49,30 @@ async def test_syncs_event_retention_months_from_billing(features: list[dict], e
assert team.event_retention_months == expected_months
[email protected]_db(transaction=True)
+async def test_emits_change_events_and_returns_totals():
+ team = await _team_with_features(
+ [{"key": "product_analytics_data_retention", "limit": 1, "unit": "year"}], current_months=999
+ )
+ captured: list[dict] = []
+
+ @contextmanager
+ def fake_scoped_capture():
+ yield lambda **kwargs: captured.append(kwargs)
+
+ with patch("posthog.temporal.sync_events_retention.activities.ph_scoped_capture", fake_scoped_capture):
+ result = await ActivityEnvironment().run(sync_events_retention, SyncEventsRetentionInput(dry_run=False))
+
+ assert [c["event"] for c in captured] == ["events_retention_changed"]
+ change = captured[0]["properties"]
+ assert change["team_id"] == team.pk
+ assert change["retention_months_before"] == 999
+ assert change["retention_months_after"] == 12
+ assert result.total_processed == 1
+ assert result.total_updated == 1
+
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_syncs_all_teams_across_batches():