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.

fix(error-tracking): parallelize symbol set cleanup (#71080)

Hugues Pouillot3d6acbd4f2d7
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py
index 4f4292c83c0c..40174de7fa8d 100644
--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py
@@ -89,20 +89,22 @@ def cleanup_symbol_sets_activity(inputs: SymbolSetCleanupInputs) -> SymbolSetCle
while total_processed < inputs.total_per_run:
remaining = inputs.total_per_run - total_processed
chunk_size = min(inputs.batch_size, remaining)
- symbol_sets = list(
- ErrorTrackingSymbolSet.objects.filter(query_filter)
- .exclude(id__in=failed_ids)
- .order_by("id")
- .values_list("id", "storage_ptr")[:chunk_size]
- )
+ with transaction.atomic():
+ symbol_sets = list(
+ ErrorTrackingSymbolSet.objects.select_for_update(skip_locked=True)
+ .filter(query_filter)
+ .exclude(id__in=failed_ids)
+ .order_by("last_used", "created_at")
+ .values_list("id", "storage_ptr")[:chunk_size]
+ )
- if not symbol_sets:
- break
+ if not symbol_sets:
+ break
- symbol_set_ids = [str(symbol_set_id) for symbol_set_id, _ in symbol_sets]
- storage_ptrs_by_id = {str(symbol_set_id): storage_ptr for symbol_set_id, storage_ptr in symbol_sets}
+ symbol_set_ids = [str(symbol_set_id) for symbol_set_id, _ in symbol_sets]
+ storage_ptrs_by_id = {str(symbol_set_id): storage_ptr for symbol_set_id, storage_ptr in symbol_sets}
+ deleted_count, batch_failed_ids = _delete_symbol_set_batch(symbol_set_ids)
- deleted_count, batch_failed_ids = _delete_symbol_set_batch(symbol_set_ids)
total_deleted += deleted_count
total_db_failed += len(batch_failed_ids)
failed_ids.update(batch_failed_ids)
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
index 4954acdd242f..35c18aec45e7 100644
--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/test/test_symbol_set_cleanup.py
@@ -1,10 +1,11 @@
import uuid
+from collections.abc import Callable
from datetime import timedelta
import pytest
from freezegun import freeze_time
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
from django.utils import timezone
@@ -152,14 +153,14 @@ class TestSymbolSetCleanupActivity(BaseTest):
async def _run_workflow_with_mock_activity(
inputs: SymbolSetCleanupInputs | None,
- activity_result: SymbolSetCleanupResult,
-) -> tuple[SymbolSetCleanupResult, SymbolSetCleanupInputs]:
- captured: dict[str, SymbolSetCleanupInputs] = {}
+ activity_result: Callable[[SymbolSetCleanupInputs], SymbolSetCleanupResult],
+) -> tuple[SymbolSetCleanupResult, list[SymbolSetCleanupInputs]]:
+ captured: list[SymbolSetCleanupInputs] = []
@activity.defn(name="cleanup_symbol_sets_activity")
async def mock_activity(activity_inputs: SymbolSetCleanupInputs) -> SymbolSetCleanupResult:
- captured["inputs"] = activity_inputs
- return activity_result
+ captured.append(activity_inputs)
+ return activity_result(activity_inputs)
task_queue = str(uuid.uuid4())
async with await WorkflowEnvironment.start_time_skipping() as env:
@@ -177,7 +178,7 @@ async def _run_workflow_with_mock_activity(
task_queue=task_queue,
)
- return result, captured["inputs"]
+ return result, captured
class TestSymbolSetCleanupWorkflow:
@@ -186,26 +187,65 @@ class TestSymbolSetCleanupWorkflow:
assert ErrorTrackingSymbolSetCleanupWorkflow.parse_inputs([]) == SymbolSetCleanupInputs(
days_old=30,
delete_unused=True,
- total_per_run=500000,
+ total_per_run=1000000,
batch_size=10000,
+ parallelism=8,
dry_run=False,
)
@pytest.mark.asyncio
- async def test_workflow_calls_activity_with_defaults(self) -> None:
- expected = SymbolSetCleanupResult(objects_processed=1, objects_deleted=1, objects_failed=0)
+ async def test_workflow_splits_total_limit_across_parallel_activities(self) -> None:
+ inputs = SymbolSetCleanupInputs(total_per_run=10, batch_size=5, parallelism=3)
+
+ result, activity_inputs = await _run_workflow_with_mock_activity(
+ inputs,
+ lambda activity_inputs: SymbolSetCleanupResult(
+ objects_processed=activity_inputs.total_per_run,
+ objects_deleted=activity_inputs.total_per_run,
+ objects_failed=0,
+ ),
+ )
+
+ assert result == SymbolSetCleanupResult(objects_processed=10, objects_deleted=10, objects_failed=0)
+ assert sorted(activity_input.total_per_run for activity_input in activity_inputs) == [3, 3, 4]
+ assert all(activity_input.batch_size == 5 for activity_input in activity_inputs)
+ assert all(activity_input.parallelism == 1 for activity_input in activity_inputs)
+
+ @pytest.mark.asyncio
+ async def test_workflow_runs_dry_run_once(self) -> None:
+ inputs = SymbolSetCleanupInputs(
+ days_old=10,
+ delete_unused=False,
+ total_per_run=100,
+ batch_size=5,
+ parallelism=3,
+ dry_run=True,
+ )
+ expected = SymbolSetCleanupResult(objects_processed=0, objects_deleted=0, objects_failed=0, eligible_count=3)
- result, activity_inputs = await _run_workflow_with_mock_activity(None, expected)
+ result, activity_inputs = await _run_workflow_with_mock_activity(inputs, lambda _: expected)
assert result == expected
- assert activity_inputs == SymbolSetCleanupInputs()
+ assert activity_inputs == [inputs]
@pytest.mark.asyncio
- async def test_workflow_forwards_inputs(self) -> None:
- inputs = SymbolSetCleanupInputs(days_old=10, delete_unused=False, total_per_run=100, batch_size=5, dry_run=True)
- expected = SymbolSetCleanupResult(objects_processed=0, objects_deleted=0, objects_failed=0, eligible_count=3)
+ async def test_workflow_preserves_single_activity_for_unpatched_histories(self) -> None:
+ inputs = SymbolSetCleanupInputs(total_per_run=100, parallelism=4)
+ expected = SymbolSetCleanupResult(objects_processed=100, objects_deleted=100, objects_failed=0)
- result, activity_inputs = await _run_workflow_with_mock_activity(inputs, expected)
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.symbol_set_cleanup.workflow.workflow.patched",
+ return_value=False,
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.symbol_set_cleanup.workflow.workflow.execute_activity",
+ new_callable=AsyncMock,
+ return_value=expected,
+ ) as execute_activity,
+ ):
+ result = await ErrorTrackingSymbolSetCleanupWorkflow().run(inputs)
assert result == expected
- assert activity_inputs == inputs
+ execute_activity.assert_awaited_once()
+ assert execute_activity.call_args.args[1] == inputs
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/types.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/types.py
index 94882c8034c9..877a50d0c5e6 100644
--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/types.py
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/types.py
@@ -5,8 +5,9 @@ import dataclasses
class SymbolSetCleanupInputs:
days_old: int = 30
delete_unused: bool = True
- total_per_run: int = 500000
+ total_per_run: int = 1000000
batch_size: int = 10000
+ parallelism: int = 8
dry_run: bool = False
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/workflow.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/workflow.py
index d5fa4362c9c6..5ae2fcda987a 100644
--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/workflow.py
+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/workflow.py
@@ -1,4 +1,5 @@
import json
+import asyncio
from datetime import timedelta
from temporalio import common, workflow
@@ -13,11 +14,42 @@ with workflow.unsafe.imports_passed_through():
)
WORKFLOW_NAME = "error-tracking-symbol-set-cleanup"
+PARALLEL_CLEANUP_PATCH_ID = "error-tracking-parallel-symbol-set-cleanup"
ACTIVITY_RETRY_POLICY = common.RetryPolicy(maximum_attempts=1)
ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(hours=2)
+def _activity_inputs(inputs: SymbolSetCleanupInputs) -> list[SymbolSetCleanupInputs]:
+ if inputs.dry_run or inputs.total_per_run <= 0:
+ return [inputs]
+
+ parallelism = max(1, min(inputs.parallelism, inputs.total_per_run))
+ per_activity_limit, remainder = divmod(inputs.total_per_run, parallelism)
+ return [
+ SymbolSetCleanupInputs(
+ days_old=inputs.days_old,
+ delete_unused=inputs.delete_unused,
+ total_per_run=per_activity_limit + (1 if index < remainder else 0),
+ batch_size=inputs.batch_size,
+ parallelism=1,
+ dry_run=False,
+ )
+ for index in range(parallelism)
+ ]
+
+
+def _combine_results(results: list[SymbolSetCleanupResult]) -> SymbolSetCleanupResult:
+ eligible_counts = [result.eligible_count for result in results if result.eligible_count is not None]
+ return SymbolSetCleanupResult(
+ objects_processed=sum(result.objects_processed for result in results),
+ objects_deleted=sum(result.objects_deleted for result in results),
+ objects_failed=sum(result.objects_failed for result in results),
+ storage_objects_failed=sum(result.storage_objects_failed for result in results),
+ eligible_count=sum(eligible_counts) if eligible_counts else None,
+ )
+
+
@workflow.defn(name=WORKFLOW_NAME)
class ErrorTrackingSymbolSetCleanupWorkflow(PostHogWorkflow):
@staticmethod
@@ -32,9 +64,23 @@ class ErrorTrackingSymbolSetCleanupWorkflow(PostHogWorkflow):
if inputs is None:
inputs = SymbolSetCleanupInputs()
- return await workflow.execute_activity(
- cleanup_symbol_sets_activity,
- inputs,
- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
- retry_policy=ACTIVITY_RETRY_POLICY,
+ if not workflow.patched(PARALLEL_CLEANUP_PATCH_ID):
+ return await workflow.execute_activity(
+ cleanup_symbol_sets_activity,
+ inputs,
+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
+ results = await asyncio.gather(
+ *[
+ workflow.execute_activity(
+ cleanup_symbol_sets_activity,
+ activity_inputs,
+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ for activity_inputs in _activity_inputs(inputs)
+ ]
)
+ return _combine_results(results)