: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
perf(error-tracking): bucket remaining symbol set scans (#90732)
Hugues Pouillotb321bfab4037
diff --git a/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py b/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.pyindex 19ce9fd677db..a2efccfc7fb2 100644--- a/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py+++ b/products/error_tracking/backend/temporal/symbol_set_cleanup/activities.py@@ -42,14 +42,6 @@ def _cleanup_branches(inputs: SymbolSetCleanupInputs) -> list[Q]:return query_branches-def _cleanup_filter(inputs: SymbolSetCleanupInputs) -> Q:- query_filters = _cleanup_branches(inputs)- query_filter = query_filters[0]- for additional_filter in query_filters[1:]:- query_filter |= additional_filter- return query_filter--def _row(*expressions: F | models.Expression) -> models.Func:return models.Func(*expressions, function="", template="(%(expressions)s)", output_field=models.Field())@@ -67,26 +59,30 @@ def _after_cursor(cursor: tuple[datetime.datetime | None, datetime.datetime, UUI)+def _bucket_queryset(*, query_filter: Q, bucket: int) -> models.QuerySet[ErrorTrackingSymbolSet]:+ return (+ ErrorTrackingSymbolSet.objects.using(_cleanup_read_database())+ .alias(cleanup_bucket=symbol_set_cleanup_bucket_expression())+ .filter(query_filter, cleanup_bucket=bucket)+ .order_by(+ "cleanup_bucket",+ F("last_used").asc(nulls_last=True),+ "created_at",+ "id",+ )+ )++def _cleanup_queryset(*,query_filter: Q,bucket: int,cursor: tuple[datetime.datetime | None, datetime.datetime, UUID] | None,) -> models.QuerySet[ErrorTrackingSymbolSet]:- queryset = (- ErrorTrackingSymbolSet.objects.using(_cleanup_read_database())- .alias(cleanup_bucket=symbol_set_cleanup_bucket_expression())- .filter(query_filter, cleanup_bucket=bucket)- )+ queryset = _bucket_queryset(query_filter=query_filter, bucket=bucket)if cursor is not None:queryset = queryset.filter(_after_cursor(cursor))-- return queryset.order_by(- "cleanup_bucket",- F("last_used").asc(nulls_last=True),- "created_at",- "id",- )+ return querysetdef _assigned_buckets(inputs: SymbolSetCleanupInputs) -> list[int]:@@ -135,14 +131,24 @@ def cleanup_symbol_sets_activity(inputs: SymbolSetCleanupInputs) -> SymbolSetCle"""Delete stale symbol sets in bounded batches, preserving model delete behavior."""# Temporal workers are long-lived, so refresh any stale Django DB connection before querying.close_old_connections()- query_filter = _cleanup_filter(inputs)+ cleanup_branches = _cleanup_branches(inputs)if inputs.dry_run:- eligible_symbol_sets = ErrorTrackingSymbolSet.objects.using(_cleanup_read_database()).filter(query_filter)- eligible_count = eligible_symbol_sets.count()+ buckets = _assigned_buckets(inputs)+ branch_querysets = [+ _bucket_queryset(query_filter=query_filter, bucket=bucket)+ for bucket in buckets+ for query_filter in cleanup_branches+ ]+ eligible_count = sum(queryset.count() for queryset in branch_querysets)# Dry runs only log a bounded sample; never log more rows than the real run would process.sample_size = min(inputs.batch_size, inputs.total_per_run, eligible_count)- for symbol_set in eligible_symbol_sets[:sample_size]:+ candidates: list[ErrorTrackingSymbolSet] = []+ for queryset in branch_querysets:+ candidates.extend(queryset[: sample_size - len(candidates)])+ if len(candidates) == sample_size:+ break+ for symbol_set in candidates:logger.info("error_tracking.symbol_set_cleanup.dry_run_candidate",symbol_set_id=str(symbol_set.id),@@ -166,7 +172,6 @@ def cleanup_symbol_sets_activity(inputs: SymbolSetCleanupInputs) -> SymbolSetCletotal_deleted = 0total_db_failed = 0total_storage_failed = 0- cleanup_branches = _cleanup_branches(inputs)for bucket in _assigned_buckets(inputs):for query_filter in cleanup_branches: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.pyindex 67e9151ad307..6f4a1fa37c6e 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@@ -19,6 +19,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom products.error_tracking.backend.models import ErrorTrackingStackFrame, ErrorTrackingSymbolSetfrom products.error_tracking.backend.temporal.symbol_set_cleanup.activities import (_assigned_buckets,+ _bucket_queryset,_cleanup_queryset,_delete_symbol_set_contents_with_pacing,cleanup_symbol_sets_activity,@@ -215,6 +216,19 @@ class TestSymbolSetCleanupActivity(BaseTest):assert queryset.db == "replica"assert not queryset.query.select_for_update+ def test_dry_run_candidates_are_an_ordered_bucket_index_range(self) -> None:+ queryset = _bucket_queryset(+ query_filter=Q(last_used__isnull=False, last_used__lt=timezone.now() - timedelta(days=30)),+ bucket=0,+ )++ with connection.cursor() as db_cursor:+ db_cursor.execute("SET LOCAL enable_seqscan = off")+ plan = queryset[:1].explain()++ assert "Index Scan using et_symset_bucket_cleanup_idx" in plan+ assert "Sort" not in plan+def test_used_cursor_is_an_ordered_bucket_index_range(self) -> None:cursor = (timezone.now() - timedelta(days=45),diff --git a/products/error_tracking/dags/symbol_set_backfill_last_used.py b/products/error_tracking/dags/symbol_set_backfill_last_used.pyindex 6b512ed6cde4..1b92b654ecfe 100644--- a/products/error_tracking/dags/symbol_set_backfill_last_used.py+++ b/products/error_tracking/dags/symbol_set_backfill_last_used.py@@ -2,13 +2,34 @@ from django.db import connectionfrom django.utils import timezoneimport dagster+import pydanticfrom posthog.dags.common import JobOwners+from products.error_tracking.backend.temporal.symbol_set_cleanup.types import SYMBOL_SET_CLEANUP_BUCKET_COUNT+class SymbolSetBackfillLastUsedConfig(dagster.Config):total_per_run: int = 300000- batch_size: int = 10000+ batch_size: int = pydantic.Field(default=10000, gt=0)+++def _backfill_last_used_bucket(*, bucket: int, batch_size: int) -> int:+ with connection.cursor() as cursor:+ cursor.execute(+ """+ UPDATE posthog_errortrackingsymbolset+ SET last_used = %s+ WHERE id IN (+ SELECT id FROM posthog_errortrackingsymbolset+ WHERE last_used IS NULL+ AND get_byte(uuid_send(id), 15) = %s+ LIMIT %s+ )+ """,+ [timezone.now().date(), bucket, batch_size],+ )+ return cursor.rowcount@dagster.asset@@ -21,30 +42,21 @@ def symbol_set_backfill_last_used(Runs hourly, updating rows in small batches to avoid long locks.Once all rows are backfilled this is a no-op."""- today = timezone.now().date()total_updated = 0- while total_updated < config.total_per_run:- with connection.cursor() as cursor:- cursor.execute(- """- UPDATE posthog_errortrackingsymbolset- SET last_used = %s- WHERE id IN (- SELECT id FROM posthog_errortrackingsymbolset- WHERE last_used IS NULL- LIMIT %s- )- """,- [today, config.batch_size],- )- updated = cursor.rowcount+ for bucket in range(SYMBOL_SET_CLEANUP_BUCKET_COUNT):+ while total_updated < config.total_per_run:+ batch_size = min(config.batch_size, config.total_per_run - total_updated)+ updated = _backfill_last_used_bucket(bucket=bucket, batch_size=batch_size)+ total_updated += updated- if updated == 0:- break+ if updated < batch_size:+ break- total_updated += updated- context.log.info(f"Updated {total_updated} symbol sets so far")+ context.log.info(f"Updated {total_updated} symbol sets so far")++ if total_updated >= config.total_per_run:+ breakcontext.log.info(f"Backfilled last_used for {total_updated} symbol sets")diff --git a/products/error_tracking/dags/tests/__init__.py b/products/error_tracking/dags/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/error_tracking/dags/tests/test_symbol_set_backfill_last_used.py b/products/error_tracking/dags/tests/test_symbol_set_backfill_last_used.pynew file mode 100644index 000000000000..4cf124cdedf0--- /dev/null+++ b/products/error_tracking/dags/tests/test_symbol_set_backfill_last_used.py@@ -0,0 +1,45 @@+import uuid++import pytest+from posthog.test.base import BaseTest++import dagster+import pydantic++from products.error_tracking.backend.models import ErrorTrackingSymbolSet+from products.error_tracking.dags.symbol_set_backfill_last_used import (+ SymbolSetBackfillLastUsedConfig,+ _backfill_last_used_bucket,+ symbol_set_backfill_last_used,+)+++def test_rejects_zero_batch_size() -> None:+ with pytest.raises(pydantic.ValidationError):+ SymbolSetBackfillLastUsedConfig(total_per_run=1, batch_size=0)+++class TestSymbolSetBackfillLastUsed(BaseTest):+ def test_backfills_only_the_requested_bucket(self) -> None:+ selected = ErrorTrackingSymbolSet.objects.create(team=self.team, ref="selected", id=uuid.UUID(int=256))+ unselected = ErrorTrackingSymbolSet.objects.create(team=self.team, ref="unselected", id=uuid.UUID(int=1))++ updated = _backfill_last_used_bucket(bucket=0, batch_size=10)++ assert updated == 1+ selected.refresh_from_db()+ unselected.refresh_from_db()+ assert selected.last_used is not None+ assert unselected.last_used is None++ def test_backfill_advances_to_the_next_bucket(self) -> None:+ symbol_set = ErrorTrackingSymbolSet.objects.create(team=self.team, ref="bucket-one", id=uuid.UUID(int=1))++ result = symbol_set_backfill_last_used(+ dagster.build_asset_context(),+ SymbolSetBackfillLastUsedConfig(total_per_run=1, batch_size=1),+ )++ symbol_set.refresh_from_db()+ assert symbol_set.last_used is not None+ assert isinstance(result, dagster.MaterializeResult)