: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
fix(error-tracking): stop retention deleting live symbol sets (#91734)
Aleksander Błaszkiewicz9fcf7f04616c
diff --git a/products/error_tracking/backend/logic/symbol_sets.py b/products/error_tracking/backend/logic/symbol_sets.pyindex 4ea177338ad8..b6bb4b22e600 100644--- a/products/error_tracking/backend/logic/symbol_sets.py+++ b/products/error_tracking/backend/logic/symbol_sets.py@@ -7,12 +7,14 @@ the CLI-facing upload contract and are surfaced verbatim by the views."""import hashlib+import datetimefrom dataclasses import dataclassfrom typing import Anyfrom django.conf import settingsfrom django.db import transactionfrom django.db.models import Q+from django.utils import timezoneimport structlogimport posthoganalytics@@ -30,6 +32,12 @@ logger = structlog.get_logger(__name__)ONE_HUNDRED_MEGABYTES = 1024 * 1024 * 100PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT = 60 * 5+# An upload rewrites `last_used` only when the stored value is older than this. `last_used` is part+# of `et_symset_bucket_cleanup_idx`, so every write churns that index, and a monorepo that uploads+# thousands of chunks per merge would rewrite all of them on each run. Cymbal throttles its own+# `last_used` writes over the same window for the same reason.+LAST_USED_UPLOAD_REFRESH_INTERVAL = datetime.timedelta(hours=12)+class SymbolSetNotFoundError(Exception):pass@@ -143,6 +151,23 @@ def create_symbol_set(return symbol_set+def refresh_last_used(team: Team, chunk_ids: list[str]) -> None:+ """Mark every symbol set the upload referenced as still in use.++ Retention deletes a symbol set once `last_used` falls outside its window. In event release+ mode the chunk id is derived from the chunk content, so one row serves every release that+ ships that chunk, and re-uploading an unchanged chunk writes nothing. Without this call the+ row ages out while the chunk is still deployed, and the next exception from it cannot be+ symbolicated until a later deploy recreates the row.+ """+ now = timezone.now()+ ErrorTrackingSymbolSet.objects.filter(+ Q(last_used__isnull=True) | Q(last_used__lt=now - LAST_USED_UPLOAD_REFRESH_INTERVAL),+ team=team,+ ref__in=chunk_ids,+ ).update(last_used=now)++@posthoganalytics.scoped()def bulk_create_symbol_sets(new_symbol_sets: list[SymbolSetUpload],@@ -275,6 +300,8 @@ def bulk_create_symbol_sets(# during a prior attempt or something).ErrorTrackingSymbolSet.objects.bulk_update(to_update, ["release", "content_hash", "storage_ptr"])+ refresh_last_used(team, chunk_ids)+return id_url_mapdiff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.pyindex 923472168d2f..7be036471198 100644--- a/products/error_tracking/backend/models.py+++ b/products/error_tracking/backend/models.py@@ -387,8 +387,10 @@ class ErrorTrackingSymbolSet(UUIDTModel):# with onerelease = models.ForeignKey(ErrorTrackingRelease, null=True, on_delete=models.CASCADE)- # When a symbol set is loaded, last_used is set, so we can track how often- # symbol sets are used, and cleanup ones not used for a long time+ # Retention deletes a symbol set once last_used falls outside its window. Two paths write it:+ # symbolication, when it loads the set, and a bulk upload, for every chunk id in the request.+ # The upload must write it because event release mode derives chunk ids from content, so one+ # row can serve many releases without symbolication ever touching it.last_used = models.DateTimeField(null=True, blank=True)def delete(self, *args, **kwargs):diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.pyindex d64a7defe244..1f73c6f4cd9c 100644--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py@@ -1,5 +1,5 @@import os-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest@@ -989,7 +989,7 @@ class TestErrorTracking(APIBaseTest):assert str(symbol_set.id) == symbol_set_upload_response["symbol_set_id"]assert symbol_set_upload_response["presigned_url"]["fields"]["key"] == symbol_set.storage_ptrassert "fallback_presigned_url" not in symbol_set_upload_response- assert symbol_set.last_used is None+ assert symbol_set.last_used is not Nonedef test_bulk_start_upload_includes_fallback_presigned_url_when_accelerated(self) -> None:chunk_id = str(uuid7())@@ -1055,10 +1055,11 @@ class TestErrorTracking(APIBaseTest):existing_symbol_set.refresh_from_db()assert existing_symbol_set.storage_ptr == "existing"assert existing_symbol_set.release_id == release.id+ assert existing_symbol_set.last_used is not Nonenew_symbol_set = ErrorTrackingSymbolSet.objects.get(ref=new_chunk_id)assert new_symbol_set.release_id == release.id- assert new_symbol_set.last_used is None+ assert new_symbol_set.last_used is not Noneassert id_map[str(new_chunk_id)]["symbol_set_id"] == str(new_symbol_set.id)assert patched_capture.call_args.args[0] == "error_tracking_symbol_set_upload_started"@@ -1071,6 +1072,44 @@ class TestErrorTracking(APIBaseTest):"chunks_skipped": 1,}+ @parameterized.expand(+ [+ ("never_used", None, True),+ ("used_before_the_refresh_interval", timedelta(hours=13), True),+ ("used_within_the_refresh_interval", timedelta(hours=1), False),+ ]+ )+ def test_bulk_start_upload_marks_unchanged_symbol_sets_as_used(+ self, _name: str, last_used_age: timedelta | None, expect_refresh: bool+ ) -> None:+ chunk_id = str(uuid7())+ last_used = None if last_used_age is None else timezone.now() - last_used_age+ symbol_set = ErrorTrackingSymbolSet.objects.create(+ team=self.team,+ ref=chunk_id,+ storage_ptr="existing",+ content_hash="already_uploaded",+ last_used=last_used,+ )++ before_upload = timezone.now()+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/symbol_sets/bulk_start_upload",+ data={"symbol_sets": [{"chunk_id": chunk_id, "content_hash": "already_uploaded"}]},+ format="json",+ )+ after_upload = timezone.now()++ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["id_map"] == {}++ symbol_set.refresh_from_db()+ if expect_refresh:+ assert symbol_set.last_used is not None+ assert before_upload <= symbol_set.last_used <= after_upload+ else:+ assert symbol_set.last_used == last_used+@parameterized.expand([("default_rejects", {}, status.HTTP_400_BAD_REQUEST, "content_hash_mismatch", "unchanged"),