: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
feat(error-tracking): add fallback presigned url for symbol uploads (#86224)
Aleksander Błaszkiewiczcb17c9fbd2c2
diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.pyindex e2c29ff449bd..0014bee350e3 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -10,6 +10,7 @@ from boto3 import clientfrom botocore.client import Configfrom botocore.exceptions import ClientError+from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionlogger = structlog.get_logger(__name__)@@ -605,17 +606,38 @@ def _get_accelerated_presigned_client() -> Optional[Any]:return _accelerated_presigned_client-def get_accelerated_presigned_post(file_key: str, conditions: list[Any], expiration: int = 3600) -> Optional[dict]:+@frozen+class PresignedPostPair:+ """Presigned POSTs for one upload.++ The primary targets the transfer-acceleration endpoint when it is configured and+ presigning succeeds, and the fallback then targets the standard endpoint, for+ clients whose network blocks the accelerate domain. Otherwise the primary is a+ standard-endpoint POST and the fallback is None.+ """++ primary: Optional[dict]+ fallback: Optional[dict]+++def get_presigned_post_pair(file_key: str, conditions: list[Any], expiration: int = 3600) -> PresignedPostPair:accelerated = _get_accelerated_presigned_client()if accelerated:try:- return accelerated.generate_presigned_post(+ primary = accelerated.generate_presigned_post(settings.OBJECT_STORAGE_BUCKET, file_key, Conditions=conditions, ExpiresIn=expiration)+ return PresignedPostPair(+ primary=primary,+ fallback=get_presigned_post(file_key=file_key, conditions=conditions, expiration=expiration),+ )except Exception as e:logger.exception("object_storage.get_accelerated_presigned_post_failed", file_name=file_key, error=e)capture_exception(e)- return get_presigned_post(file_key=file_key, conditions=conditions, expiration=expiration)+ return PresignedPostPair(+ primary=get_presigned_post(file_key=file_key, conditions=conditions, expiration=expiration),+ fallback=None,+ )def head_object(file_key: str, bucket: str | None = None) -> Optional[dict]:diff --git a/products/error_tracking/backend/facade/symbol_sets.py b/products/error_tracking/backend/facade/symbol_sets.pyindex 74e9a2b30154..7042bee088e1 100644--- a/products/error_tracking/backend/facade/symbol_sets.py+++ b/products/error_tracking/backend/facade/symbol_sets.py@@ -97,7 +97,7 @@ def bulk_start_upload(release_id: str | None,force: bool,skip_on_conflict: bool,-) -> dict[str, dict[str, str]]:+) -> dict[str, dict[str, Any]]:return _logic.bulk_start_upload(team,symbol_sets=symbol_sets,diff --git a/products/error_tracking/backend/logic/symbol_sets.py b/products/error_tracking/backend/logic/symbol_sets.pyindex 2a23d66aa053..4ea177338ad8 100644--- a/products/error_tracking/backend/logic/symbol_sets.py+++ b/products/error_tracking/backend/logic/symbol_sets.py@@ -8,6 +8,7 @@ the CLI-facing upload contract and are surfaced verbatim by the views.import hashlibfrom dataclasses import dataclass+from typing import Anyfrom django.conf import settingsfrom django.db import transaction@@ -71,14 +72,19 @@ def generate_symbol_set_file_key() -> str:return f"{settings.OBJECT_STORAGE_ERROR_TRACKING_SOURCE_MAPS_FOLDER}/{str(uuid7())}"-def generate_symbol_set_upload_presigned_url(file_key: str):- # get_accelerated_presigned_post transparently falls back to a standard presigned POST- # when S3 Transfer Acceleration is not configured.- return object_storage.get_accelerated_presigned_post(+def generate_symbol_set_upload_presigned_urls(file_key: str) -> dict[str, Any]:+ pair = object_storage.get_presigned_post_pair(file_key=file_key,conditions=[["content-length-range", 0, ONE_HUNDRED_MEGABYTES]],expiration=PRESIGNED_MULTIPLE_UPLOAD_TIMEOUT,)+ urls: dict[str, Any] = {"presigned_url": pair.primary}+ if pair.fallback is not None:+ # Some networks (firewalls, egress allowlists) reset connections to the+ # transfer-acceleration domain while regular S3 works, so the CLI needs a+ # standard-endpoint presigned POST to retry against.+ urls["fallback_presigned_url"] = pair.fallback+ return urlsdef upload_content(content: bytearray) -> tuple[str, str]:@@ -143,7 +149,7 @@ def bulk_create_symbol_sets(team: Team,force: bool = False,skip_on_conflict: bool = False,-) -> dict[str, dict[str, str]]:+) -> dict[str, dict[str, Any]]:chunk_ids = [x.chunk_id for x in new_symbol_sets]# Check for dupes@@ -164,9 +170,17 @@ def bulk_create_symbol_sets(detail=f"Unknown release ID provided: {release_id}",)- id_url_map: dict[str, dict[str, str]] = {}+ id_url_map: dict[str, dict[str, Any]] = {}new_symbol_set_map = {x.chunk_id: x for x in new_symbol_sets}+ def reissue_upload(existing: ErrorTrackingSymbolSet) -> None:+ storage_ptr = generate_symbol_set_file_key()+ id_url_map[existing.ref] = {+ **generate_symbol_set_upload_presigned_urls(storage_ptr),+ "symbol_set_id": str(existing.id),+ }+ existing.storage_ptr = storage_ptr+with transaction.atomic():existing_symbol_sets = list(ErrorTrackingSymbolSet.objects.filter(team=team, ref__in=chunk_ids))existing_symbol_set_refs = [s.ref for s in existing_symbol_sets]@@ -175,8 +189,7 @@ def bulk_create_symbol_sets(symbol_sets_to_be_created = []for chunk_id in missing_sets:storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr)- id_url_map[chunk_id] = {"presigned_url": presigned_url}+ id_url_map[chunk_id] = generate_symbol_set_upload_presigned_urls(storage_ptr)# Note that on creation, we /do not set/ the content hash. We use content hashes included in# the create request only to see if we can skip updated - we set the content hash when we# get upload confirmation, during `bulk_finish_upload`, not before@@ -223,24 +236,12 @@ def bulk_create_symbol_sets()# Both sides have no hash: this is a pending upload being restarted.# Issue a fresh presigned URL so the client can retry.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr+ reissue_upload(existing)dirty = Trueelif existing.content_hash is None:# Existing record has no hash (pending upload or uploaded by old CLI# without hash support). Allow the new upload to supply one.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr+ reissue_upload(existing)dirty = Trueelif existing.content_hash == upload.content_hash:# Content is identical — no upload needed.@@ -250,13 +251,7 @@ def bulk_create_symbol_sets(# force=True: content has changed and the caller explicitly# requested an overwrite. Issue a new presigned URL and clear# the old content hash so bulk_finish_upload stores the new one.- storage_ptr = generate_symbol_set_file_key()- presigned_url = generate_symbol_set_upload_presigned_url(storage_ptr)- id_url_map[existing.ref] = {- "presigned_url": presigned_url,- "symbol_set_id": str(existing.id),- }- existing.storage_ptr = storage_ptr+ reissue_upload(existing)existing.content_hash = None # will be set by bulk_finish_uploaddirty = Trueelif skip_on_conflict:@@ -420,7 +415,7 @@ def bulk_start_upload(release_id: str | None,force: bool,skip_on_conflict: bool,-) -> dict[str, dict[str, str]]:+) -> dict[str, dict[str, Any]]:uploads = [SymbolSetUpload(**data) for data in symbol_sets]uploads.extend([SymbolSetUpload(chunk_id, release_id, None) for chunk_id in chunk_ids])diff --git a/products/error_tracking/backend/presentation/views/symbol_sets.py b/products/error_tracking/backend/presentation/views/symbol_sets.pyindex 735799babc23..11f2fdd7d91c 100644--- a/products/error_tracking/backend/presentation/views/symbol_sets.py+++ b/products/error_tracking/backend/presentation/views/symbol_sets.py@@ -86,6 +86,32 @@ class ErrorTrackingSymbolSetBulkStartUploadSerializer(serializers.Serializer):return attrs+class ErrorTrackingSymbolSetPresignedPostSerializer(serializers.Serializer):+ url = serializers.URLField(help_text="S3 endpoint URL to send the multipart POST to.")+ fields = serializers.DictField( # type: ignore[assignment]+ child=serializers.CharField(),+ help_text="Form fields to include in the multipart POST, before the file part.",+ )+++class ErrorTrackingSymbolSetBulkStartUploadEntrySerializer(serializers.Serializer):+ symbol_set_id = serializers.CharField(help_text="ID of the symbol set the upload belongs to.")+ presigned_url = ErrorTrackingSymbolSetPresignedPostSerializer(+ help_text="Presigned POST for the upload. Uses the S3 transfer-acceleration endpoint when configured."+ )+ fallback_presigned_url = ErrorTrackingSymbolSetPresignedPostSerializer(+ required=False,+ help_text="Presigned POST against the standard S3 endpoint, present only when the primary URL uses transfer acceleration. For clients whose network blocks the accelerated endpoint.",+ )+++class ErrorTrackingSymbolSetBulkStartUploadResponseSerializer(serializers.Serializer):+ id_map = serializers.DictField(+ child=ErrorTrackingSymbolSetBulkStartUploadEntrySerializer(),+ help_text="Map of chunk ID to upload details. Chunks skipped because their content is unchanged are omitted.",+ )++class ErrorTrackingSymbolSetBulkFinishUploadSerializer(serializers.Serializer):content_hashes = serializers.DictField(child=serializers.CharField(),@@ -287,7 +313,10 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewreturn Response({"success": True}, status=status.HTTP_200_OK)- @extend_schema(request=ErrorTrackingSymbolSetBulkStartUploadSerializer)+ @extend_schema(+ request=ErrorTrackingSymbolSetBulkStartUploadSerializer,+ responses={201: ErrorTrackingSymbolSetBulkStartUploadResponseSerializer},+ )@action(methods=["POST"], detail=False, parser_classes=[JSONParser])def bulk_start_upload(self, request: Request, **kwargs) -> Response:if request.user.pk: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 b3676807e2c9..4de45c2e4eab 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@@ -917,8 +917,26 @@ 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_ptr+ assert "fallback_presigned_url" not in symbol_set_upload_responseassert symbol_set.last_used is None+ def test_bulk_start_upload_includes_fallback_presigned_url_when_accelerated(self) -> None:+ chunk_id = str(uuid7())+ with (+ self.settings(OBJECT_STORAGE_TRANSFER_ACCELERATION=True),+ patch("posthog.storage.object_storage._accelerated_presigned_client", None),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/error_tracking/symbol_sets/bulk_start_upload",+ data={"chunk_ids": [chunk_id]},+ )++ entry = response.json()["id_map"][chunk_id]+ symbol_set = ErrorTrackingSymbolSet.objects.get(ref=chunk_id)+ assert "s3-accelerate" in entry["presigned_url"]["url"]+ assert "s3-accelerate" not in entry["fallback_presigned_url"]["url"]+ assert entry["fallback_presigned_url"]["fields"]["key"] == symbol_set.storage_ptr+@patch("products.error_tracking.backend.presentation.views.symbol_sets.posthoganalytics.capture")def test_bulk_start_upload_skips_uploaded_symbol_sets(self, patched_capture: Mock) -> None:release = ErrorTrackingRelease.objects.create(diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.tsindex 2ef2b385cec3..d7b32ee87a0b 100644--- a/products/error_tracking/frontend/generated/api.schemas.ts+++ b/products/error_tracking/frontend/generated/api.schemas.ts@@ -1943,6 +1943,39 @@ export interface ErrorTrackingSymbolSetBulkStartUploadApi {skip_on_conflict?: boolean}+/**+ * Form fields to include in the multipart POST, before the file part.+ */+export type ErrorTrackingSymbolSetPresignedPostApiFields = { [key: string]: string }++export interface ErrorTrackingSymbolSetPresignedPostApi {+ /** S3 endpoint URL to send the multipart POST to. */+ url: string+ /** Form fields to include in the multipart POST, before the file part. */+ fields: ErrorTrackingSymbolSetPresignedPostApiFields+}++export interface ErrorTrackingSymbolSetBulkStartUploadEntryApi {+ /** ID of the symbol set the upload belongs to. */+ symbol_set_id: string+ /** Presigned POST for the upload. Uses the S3 transfer-acceleration endpoint when configured. */+ presigned_url: ErrorTrackingSymbolSetPresignedPostApi+ /** Presigned POST against the standard S3 endpoint, present only when the primary URL uses transfer acceleration. For clients whose network blocks the accelerated endpoint. */+ fallback_presigned_url?: ErrorTrackingSymbolSetPresignedPostApi+}++/**+ * Map of chunk ID to upload details. Chunks skipped because their content is unchanged are omitted.+ */+export type ErrorTrackingSymbolSetBulkStartUploadResponseApiIdMap = {+ [key: string]: ErrorTrackingSymbolSetBulkStartUploadEntryApi+}++export interface ErrorTrackingSymbolSetBulkStartUploadResponseApi {+ /** Map of chunk ID to upload details. Chunks skipped because their content is unchanged are omitted. */+ id_map: ErrorTrackingSymbolSetBulkStartUploadResponseApiIdMap+}+export type ErrorTrackingAssignmentRulesListParams = {/*** Number of results to return per page.diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.tsindex a25f8eacf057..751c3f78c7d4 100644--- a/products/error_tracking/frontend/generated/api.ts+++ b/products/error_tracking/frontend/generated/api.ts@@ -70,6 +70,7 @@ import type {ErrorTrackingSymbolSetBulkDeleteApi,ErrorTrackingSymbolSetBulkFinishUploadApi,ErrorTrackingSymbolSetBulkStartUploadApi,+ ErrorTrackingSymbolSetBulkStartUploadResponseApi,ErrorTrackingSymbolSetFinishUploadApi,ErrorTrackingSymbolSetsListParams,GitProviderFileLinkResolveResponseApi,@@ -1856,11 +1857,14 @@ export const errorTrackingSymbolSetsBulkStartUploadCreate = async (projectId: string,errorTrackingSymbolSetBulkStartUploadApi?: ErrorTrackingSymbolSetBulkStartUploadApi,options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getErrorTrackingSymbolSetsBulkStartUploadCreateUrl(projectId), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(errorTrackingSymbolSetBulkStartUploadApi),- })+): Promise<ErrorTrackingSymbolSetBulkStartUploadResponseApi> => {+ return apiMutator<ErrorTrackingSymbolSetBulkStartUploadResponseApi>(+ getErrorTrackingSymbolSetsBulkStartUploadCreateUrl(projectId),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(errorTrackingSymbolSetBulkStartUploadApi),+ }+ )}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 7000910f9080..5f36905ef32e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -30982,6 +30982,37 @@ export namespace Schemas {skip_on_conflict?: boolean;}+ /**+ * Form fields to include in the multipart POST, before the file part.+ */+ export type ErrorTrackingSymbolSetPresignedPostFields = {[key: string]: string};++ export interface ErrorTrackingSymbolSetPresignedPost {+ /** S3 endpoint URL to send the multipart POST to. */+ url: string;+ /** Form fields to include in the multipart POST, before the file part. */+ fields: ErrorTrackingSymbolSetPresignedPostFields;+ }++ export interface ErrorTrackingSymbolSetBulkStartUploadEntry {+ /** ID of the symbol set the upload belongs to. */+ symbol_set_id: string;+ /** Presigned POST for the upload. Uses the S3 transfer-acceleration endpoint when configured. */+ presigned_url: ErrorTrackingSymbolSetPresignedPost;+ /** Presigned POST against the standard S3 endpoint, present only when the primary URL uses transfer acceleration. For clients whose network blocks the accelerated endpoint. */+ fallback_presigned_url?: ErrorTrackingSymbolSetPresignedPost;+ }++ /**+ * Map of chunk ID to upload details. Chunks skipped because their content is unchanged are omitted.+ */+ export type ErrorTrackingSymbolSetBulkStartUploadResponseIdMap = {[key: string]: ErrorTrackingSymbolSetBulkStartUploadEntry};++ export interface ErrorTrackingSymbolSetBulkStartUploadResponse {+ /** Map of chunk ID to upload details. Chunks skipped because their content is unchanged are omitted. */+ id_map: ErrorTrackingSymbolSetBulkStartUploadResponseIdMap;+ }+export interface ErrorTrackingSymbolSetFinishUpload {/** Hash of the uploaded symbol set content. */content_hash: string;