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(error-tracking): schedule temporal cleanup jobs (#61861)

Hugues Pouilloteef058cc4e47
diff --git a/posthog/dags/locations/error_tracking.py b/posthog/dags/locations/error_tracking.py
deleted file mode 100644
index 38419fe88ebd..000000000000
--- a/posthog/dags/locations/error_tracking.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import dagster
-
-from products.error_tracking.dags import spike_event_cleanup, symbol_set_cleanup
-
-from . import loggers, resources
-
-defs = dagster.Definitions(
- assets=[
- symbol_set_cleanup.symbol_set_cleanup,
- spike_event_cleanup.spike_events_cleanup,
- ],
- jobs=[
- symbol_set_cleanup.symbol_set_cleanup_job,
- spike_event_cleanup.spike_event_cleanup_job,
- ],
- schedules=[
- symbol_set_cleanup.hourly_symbol_set_cleanup_schedule,
- spike_event_cleanup.daily_spike_event_cleanup_schedule,
- ],
- loggers=loggers,
- resources=resources,
-)
diff --git a/posthog/dags/tests/test_loggers.py b/posthog/dags/tests/test_loggers.py
index 430d6b46157b..e2c36af6050f 100644
--- a/posthog/dags/tests/test_loggers.py
+++ b/posthog/dags/tests/test_loggers.py
@@ -15,7 +15,6 @@ LOCATION_MODULES = [
"billing",
"clickhouse",
"data_stack",
- "error_tracking",
"growth",
"ingestion",
"logs",
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 8bafaa81e59b..b653a26c39da 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -78,6 +78,12 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo
from posthog.temporal.weekly_digest.types import WeeklyDigestInput
from products.business_knowledge.backend.temporal.schedule import create_business_knowledge_refresh_coordinator_schedule
+from products.error_tracking.backend.temporal.spike_event_cleanup.schedule import (
+ create_error_tracking_spike_event_cleanup_schedule,
+)
+from products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import (
+ create_error_tracking_symbol_set_cleanup_schedule,
+)
from products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.signals.backend.temporal.agentic.schedule import create_signals_scout_coordinator_schedule
@@ -609,6 +615,8 @@ schedules = [
create_health_check_schedules,
create_conversations_signals_coordinator_schedule,
create_business_knowledge_refresh_coordinator_schedule,
+ create_error_tracking_symbol_set_cleanup_schedule,
+ create_error_tracking_spike_event_cleanup_schedule,
create_wa_weekly_digest_schedule,
create_logs_alert_check_schedule,
create_schedule_due_alert_checks_schedule,
diff --git a/products/error_tracking/backend/temporal/spike_event_cleanup/schedule.py b/products/error_tracking/backend/temporal/spike_event_cleanup/schedule.py
new file mode 100644
index 000000000000..9d883e42ec06
--- /dev/null
+++ b/products/error_tracking/backend/temporal/spike_event_cleanup/schedule.py
@@ -0,0 +1,47 @@
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleCalendarSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleRange,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.error_tracking.backend.temporal.spike_event_cleanup.types import SpikeEventCleanupInputs
+from products.error_tracking.backend.temporal.spike_event_cleanup.workflow import WORKFLOW_NAME
+
+SCHEDULE_ID = "error-tracking-spike-event-cleanup-schedule"
+SCHEDULE_CATCHUP_WINDOW = timedelta(days=1)
+
+
+async def create_error_tracking_spike_event_cleanup_schedule(client: Client) -> None:
+ spike_event_cleanup_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ WORKFLOW_NAME,
+ SpikeEventCleanupInputs(),
+ id=SCHEDULE_ID,
+ task_queue=settings.ERROR_TRACKING_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Daily at 4 AM UTC",
+ hour=[ScheduleRange(start=4, end=4)],
+ )
+ ]
+ ),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=SCHEDULE_CATCHUP_WINDOW),
+ )
+
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, spike_event_cleanup_schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, spike_event_cleanup_schedule, trigger_immediately=False)
diff --git a/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup_schedule.py b/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup_schedule.py
new file mode 100644
index 000000000000..52c82501cc7a
--- /dev/null
+++ b/products/error_tracking/backend/temporal/spike_event_cleanup/test/test_spike_event_cleanup_schedule.py
@@ -0,0 +1,82 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from django.conf import settings
+
+from temporalio.client import ScheduleActionStartWorkflow, ScheduleCalendarSpec, ScheduleOverlapPolicy, ScheduleRange
+
+from products.error_tracking.backend.temporal.spike_event_cleanup.schedule import (
+ SCHEDULE_CATCHUP_WINDOW,
+ SCHEDULE_ID,
+ create_error_tracking_spike_event_cleanup_schedule,
+)
+from products.error_tracking.backend.temporal.spike_event_cleanup.types import SpikeEventCleanupInputs
+from products.error_tracking.backend.temporal.spike_event_cleanup.workflow import WORKFLOW_NAME
+
+
+def schedule_helpers():
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.spike_event_cleanup.schedule.a_create_schedule",
+ new_callable=AsyncMock,
+ ) as create,
+ patch(
+ "products.error_tracking.backend.temporal.spike_event_cleanup.schedule.a_update_schedule",
+ new_callable=AsyncMock,
+ ) as update,
+ patch(
+ "products.error_tracking.backend.temporal.spike_event_cleanup.schedule.a_schedule_exists",
+ new_callable=AsyncMock,
+ ) as exists,
+ ):
+ yield {"create": create, "update": update, "exists": exists}
+
+
+def mock_client():
+ return object()
+
+
+def assert_spike_event_cleanup_schedule(schedule) -> None:
+ assert isinstance(schedule.action, ScheduleActionStartWorkflow)
+ assert schedule.action.workflow == WORKFLOW_NAME
+ assert schedule.action.args == [SpikeEventCleanupInputs()]
+ assert schedule.action.id == SCHEDULE_ID
+ assert schedule.action.task_queue == settings.ERROR_TRACKING_TASK_QUEUE
+ assert schedule.policy is not None
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.policy.catchup_window == SCHEDULE_CATCHUP_WINDOW
+ assert schedule.spec.calendars == [
+ ScheduleCalendarSpec(comment="Daily at 4 AM UTC", hour=[ScheduleRange(start=4, end=4)])
+ ]
+
+
+class TestCreateErrorTrackingSpikeEventCleanupSchedule:
+ @pytest.mark.asyncio
+ async def test_creates_daily_schedule_when_missing(self, mock_client, schedule_helpers) -> None:
+ schedule_helpers["exists"].return_value = False
+
+ await create_error_tracking_spike_event_cleanup_schedule(mock_client)
+
+ schedule_helpers["create"].assert_awaited_once()
+ schedule_helpers["update"].assert_not_called()
+ client, schedule_id, schedule = schedule_helpers["create"].call_args.args
+ assert client is mock_client
+ assert schedule_id == SCHEDULE_ID
+ assert schedule_helpers["create"].call_args.kwargs["trigger_immediately"] is False
+
+ assert_spike_event_cleanup_schedule(schedule)
+
+ @pytest.mark.asyncio
+ async def test_updates_existing_schedule(self, mock_client, schedule_helpers) -> None:
+ schedule_helpers["exists"].return_value = True
+
+ await create_error_tracking_spike_event_cleanup_schedule(mock_client)
+
+ schedule_helpers["create"].assert_not_called()
+ schedule_helpers["update"].assert_awaited_once()
+ client, schedule_id, schedule = schedule_helpers["update"].call_args.args
+ assert client is mock_client
+ assert schedule_id == SCHEDULE_ID
+ assert_spike_event_cleanup_schedule(schedule)
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/schedule.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/schedule.py
new file mode 100644
index 000000000000..611d835acbb5
--- /dev/null
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/schedule.py
@@ -0,0 +1,39 @@
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.error_tracking.backend.temporal.symbol_set_cleanup.types import SymbolSetCleanupInputs
+from products.error_tracking.backend.temporal.symbol_set_cleanup.workflow import WORKFLOW_NAME
+
+SCHEDULE_ID = "error-tracking-symbol-set-cleanup-schedule"
+SCHEDULE_INTERVAL = timedelta(hours=1)
+
+
+async def create_error_tracking_symbol_set_cleanup_schedule(client: Client) -> None:
+ symbol_set_cleanup_schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ WORKFLOW_NAME,
+ SymbolSetCleanupInputs(),
+ id=SCHEDULE_ID,
+ task_queue=settings.ERROR_TRACKING_TASK_QUEUE,
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP, catchup_window=SCHEDULE_INTERVAL),
+ )
+
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, symbol_set_cleanup_schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, symbol_set_cleanup_schedule, trigger_immediately=False)
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup_schedule.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup_schedule.py
new file mode 100644
index 000000000000..e1c4cd868c68
--- /dev/null
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup_schedule.py
@@ -0,0 +1,80 @@
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from django.conf import settings
+
+from temporalio.client import ScheduleActionStartWorkflow, ScheduleIntervalSpec, ScheduleOverlapPolicy
+
+from products.error_tracking.backend.temporal.symbol_set_cleanup.schedule import (
+ SCHEDULE_ID,
+ SCHEDULE_INTERVAL,
+ create_error_tracking_symbol_set_cleanup_schedule,
+)
+from products.error_tracking.backend.temporal.symbol_set_cleanup.types import SymbolSetCleanupInputs
+from products.error_tracking.backend.temporal.symbol_set_cleanup.workflow import WORKFLOW_NAME
+
+
+def schedule_helpers():
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.symbol_set_cleanup.schedule.a_create_schedule",
+ new_callable=AsyncMock,
+ ) as create,
+ patch(
+ "products.error_tracking.backend.temporal.symbol_set_cleanup.schedule.a_update_schedule",
+ new_callable=AsyncMock,
+ ) as update,
+ patch(
+ "products.error_tracking.backend.temporal.symbol_set_cleanup.schedule.a_schedule_exists",
+ new_callable=AsyncMock,
+ ) as exists,
+ ):
+ yield {"create": create, "update": update, "exists": exists}
+
+
+def mock_client():
+ return object()
+
+
+def assert_symbol_set_cleanup_schedule(schedule) -> None:
+ assert isinstance(schedule.action, ScheduleActionStartWorkflow)
+ assert schedule.action.workflow == WORKFLOW_NAME
+ assert schedule.action.args == [SymbolSetCleanupInputs()]
+ assert schedule.action.id == SCHEDULE_ID
+ assert schedule.action.task_queue == settings.ERROR_TRACKING_TASK_QUEUE
+ assert schedule.policy is not None
+ assert schedule.policy.overlap == ScheduleOverlapPolicy.SKIP
+ assert schedule.policy.catchup_window == SCHEDULE_INTERVAL
+ assert schedule.spec.intervals == [ScheduleIntervalSpec(every=SCHEDULE_INTERVAL)]
+
+
+class TestCreateErrorTrackingSymbolSetCleanupSchedule:
+ @pytest.mark.asyncio
+ async def test_creates_hourly_schedule_when_missing(self, mock_client, schedule_helpers) -> None:
+ schedule_helpers["exists"].return_value = False
+
+ await create_error_tracking_symbol_set_cleanup_schedule(mock_client)
+
+ schedule_helpers["create"].assert_awaited_once()
+ schedule_helpers["update"].assert_not_called()
+ client, schedule_id, schedule = schedule_helpers["create"].call_args.args
+ assert client is mock_client
+ assert schedule_id == SCHEDULE_ID
+ assert schedule_helpers["create"].call_args.kwargs["trigger_immediately"] is False
+
+ assert_symbol_set_cleanup_schedule(schedule)
+
+ @pytest.mark.asyncio
+ async def test_updates_existing_schedule(self, mock_client, schedule_helpers) -> None:
+ schedule_helpers["exists"].return_value = True
+
+ await create_error_tracking_symbol_set_cleanup_schedule(mock_client)
+
+ schedule_helpers["create"].assert_not_called()
+ schedule_helpers["update"].assert_awaited_once()
+ client, schedule_id, schedule = schedule_helpers["update"].call_args.args
+ assert client is mock_client
+ assert schedule_id == SCHEDULE_ID
+ assert_symbol_set_cleanup_schedule(schedule)
diff --git a/products/error_tracking/dags/spike_event_cleanup.py b/products/error_tracking/dags/spike_event_cleanup.py
deleted file mode 100644
index c1909fd41ead..000000000000
--- a/products/error_tracking/dags/spike_event_cleanup.py
+++ /dev/null
@@ -1,53 +0,0 @@
-import datetime
-
-from django.utils import timezone
-
-import dagster
-
-from posthog.dags.common import JobOwners
-
-from products.error_tracking.backend.models import ErrorTrackingSpikeEvent
-
-SPIKE_EVENT_RETENTION_DAYS = 30
-
-
-class SpikeEventCleanupConfig(dagster.Config):
- days_old: int = SPIKE_EVENT_RETENTION_DAYS
-
-
[email protected](tags={"owner": JobOwners.TEAM_ERROR_TRACKING.value})
-def spike_events_cleanup(
- context: dagster.AssetExecutionContext,
- config: SpikeEventCleanupConfig,
-) -> dagster.MaterializeResult:
- cutoff = timezone.now() - datetime.timedelta(days=config.days_old)
- qs = ErrorTrackingSpikeEvent.objects.filter(detected_at__lt=cutoff)
-
- deleted, _ = qs.delete()
- context.log.info("Deleted %d spike events older than %s", deleted, cutoff.isoformat())
-
- return dagster.MaterializeResult(metadata={"deleted_count": dagster.MetadataValue.int(deleted)})
-
-
-spike_event_cleanup_job = dagster.define_asset_job(
- name="spike_event_cleanup_job",
- selection=[spike_events_cleanup.key],
- tags={"owner": JobOwners.TEAM_ERROR_TRACKING.value},
-)
-
-
- job=spike_event_cleanup_job,
- cron_schedule="0 4 * * *", # Daily at 4 AM UTC
- execution_timezone="UTC",
- default_status=dagster.DefaultScheduleStatus.RUNNING,
-)
-def daily_spike_event_cleanup_schedule(context):
- return dagster.RunRequest(
- run_key=f"spike_event_cleanup_{context.scheduled_execution_time.strftime('%Y%m%d')}",
- run_config={
- "ops": {
- "spike_events_cleanup": {"config": SpikeEventCleanupConfig().model_dump()},
- }
- },
- )
diff --git a/products/error_tracking/dags/symbol_set_cleanup.py b/products/error_tracking/dags/symbol_set_cleanup.py
deleted file mode 100644
index 9d95b3a39bed..000000000000
--- a/products/error_tracking/dags/symbol_set_cleanup.py
+++ /dev/null
@@ -1,119 +0,0 @@
-import datetime
-
-from django.db.models import Q
-from django.utils import timezone
-
-import dagster
-
-from posthog.dags.common import JobOwners
-
-from products.error_tracking.backend.models import ErrorTrackingSymbolSet
-
-
-class SymbolSetCleanupConfig(dagster.Config):
- days_old: int = 30
- delete_unused: bool = True
- total_per_run: int = 50000
- batch_size: int = 2000
- dry_run: bool = False
-
-
-def symbol_set_cleanup(
- context: dagster.AssetExecutionContext,
- config: SymbolSetCleanupConfig,
-) -> dagster.MaterializeResult:
- """
- Delete symbol sets older than the cutoff date in small chunks.
- Each delete() also removes the underlying S3 object, so the loop is I/O bound.
- """
- cutoff_date = timezone.now() - datetime.timedelta(days=config.days_old)
-
- query_filter = Q(last_used__isnull=False) & Q(last_used__lt=cutoff_date)
- if config.delete_unused:
- query_filter = query_filter | (Q(last_used__isnull=True) & Q(created_at__lt=cutoff_date))
-
- if config.dry_run:
- eligible_count = ErrorTrackingSymbolSet.objects.filter(query_filter).count()
- sample_size = min(config.batch_size, config.total_per_run, eligible_count)
- for symbol_set in ErrorTrackingSymbolSet.objects.filter(query_filter)[:sample_size]:
- last_used_str = symbol_set.last_used.isoformat() if symbol_set.last_used else "never"
- context.log.info(
- f"DRY RUN: Would delete symbol set {symbol_set.id} "
- f"(ref: {symbol_set.ref}, team: {symbol_set.team_id}, "
- f"last_used: {last_used_str})"
- )
- context.log.info(
- f"DRY RUN: {eligible_count} symbol set(s) eligible for deletion "
- f"(would process up to {config.total_per_run} per run)"
- )
- return dagster.MaterializeResult(
- metadata={
- "objects_processed": dagster.MetadataValue.int(0),
- "objects_deleted": dagster.MetadataValue.int(0),
- "objects_failed": dagster.MetadataValue.int(0),
- "eligible_count": dagster.MetadataValue.int(eligible_count),
- "dry_run": dagster.MetadataValue.bool(True),
- }
- )
-
- total_processed = 0
- total_deleted = 0
- total_failed = 0
- failed_ids: set[int] = set()
-
- while total_processed < config.total_per_run:
- remaining = config.total_per_run - total_processed
- chunk_size = min(config.batch_size, remaining)
- symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(query_filter).exclude(id__in=failed_ids)[:chunk_size])
-
- if not symbol_sets:
- break
-
- for symbol_set in symbol_sets:
- try:
- symbol_set.delete()
- total_deleted += 1
- except Exception as e:
- total_failed += 1
- failed_ids.add(symbol_set.id)
- context.log.exception(
- f"Failed to delete symbol set {symbol_set.id} "
- f"(ref: {symbol_set.ref}, team: {symbol_set.team_id}): {str(e)}"
- )
-
- total_processed += len(symbol_sets)
- context.log.info(
- f"Processed {total_processed} symbol sets so far (deleted: {total_deleted}, failed: {total_failed})"
- )
-
- if total_failed > 0:
- context.log.warning(f"Failed to delete {total_failed} symbol sets out of {total_processed}")
-
- return dagster.MaterializeResult(
- metadata={
- "objects_processed": dagster.MetadataValue.int(total_processed),
- "objects_deleted": dagster.MetadataValue.int(total_deleted),
- "objects_failed": dagster.MetadataValue.int(total_failed),
- "dry_run": dagster.MetadataValue.bool(config.dry_run),
- }
- )
-
-
-symbol_set_cleanup_job = dagster.define_asset_job(
- name="symbol_set_cleanup_job",
- selection=[symbol_set_cleanup.key],
- tags={"owner": JobOwners.TEAM_ERROR_TRACKING.value},
-)
-
-
- job=symbol_set_cleanup_job,
- cron_schedule="0 * * * *",
- execution_timezone="UTC",
- default_status=dagster.DefaultScheduleStatus.RUNNING,
-)
-def hourly_symbol_set_cleanup_schedule(context):
- return dagster.RunRequest(
- run_key=f"symbol_set_cleanup_{context.scheduled_execution_time.strftime('%Y%m%d_%H%M%S')}",
- )