: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(data-imports): don't report transient S3 timeouts during query-folder cleanup (#73395)
Tom Owers1f013bb74392
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.pyindex b016d373242d..78186c307d37 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_util.py@@ -1,9 +1,19 @@+import contextlibfrom types import SimpleNamespace-from unittest.mock import AsyncMock, patch+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++import botocore.exceptions+from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports import util as util_module-from products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying+from products.warehouse_sources.backend.temporal.data_imports.util import (+ _is_transient_s3_connection_error,+ prepare_s3_files_for_querying,+)++_UTIL_MODULE = "products.warehouse_sources.backend.temporal.data_imports.util"def _fake_s3(**kwargs):@@ -48,3 +58,97 @@ class TestPrepareS3FilesForQuerying:assert s3._cp_file.await_count == 2s3._copy.assert_not_awaited()+++ [+ (+ "connect_timeout",+ botocore.exceptions.ConnectTimeoutError(endpoint_url="https://example.s3.amazonaws.com"),+ True,+ ),+ (+ "endpoint_connection_error",+ botocore.exceptions.EndpointConnectionError(endpoint_url="https://example.s3.amazonaws.com"),+ True,+ ),+ (+ "read_timeout",+ botocore.exceptions.ReadTimeoutError(endpoint_url="https://example.s3.amazonaws.com"),+ True,+ ),+ (+ "connection_closed",+ botocore.exceptions.ConnectionClosedError(endpoint_url="https://example.s3.amazonaws.com"),+ True,+ ),+ (+ "client_error_access_denied",+ botocore.exceptions.ClientError({"Error": {"Code": "AccessDenied"}}, "DeleteObject"),+ False,+ ),+ ("generic_value_error", ValueError("some other cleanup failure"), False),+ ]+)+def test_is_transient_s3_connection_error(name: str, error: BaseException, expected: bool) -> None:+ assert _is_transient_s3_connection_error(error) is expected+++def _mock_s3_context(mock_s3: AsyncMock):+ """Patch aget_s3_client to yield a mock async context manager wrapping mock_s3."""+ with patch(f"{_UTIL_MODULE}.aget_s3_client") as mock_get_s3:+ mock_get_s3.return_value.__aenter__ = AsyncMock(return_value=mock_s3)+ mock_get_s3.return_value.__aexit__ = AsyncMock(return_value=False)+ yield mock_get_s3+++def _mock_s3() -> AsyncMock:+ s3 = AsyncMock()+ s3.invalidate_cache = MagicMock()+ s3._exists = AsyncMock(return_value=True)+ s3._copy = AsyncMock()+ return s3+++@patch(f"{_UTIL_MODULE}.capture_exception")+async def test_delete_folder_swallows_transient_s3_connection_error(mock_capture_exception: MagicMock) -> None:+ # A best-effort old-folder delete hitting a connect timeout must not mint an error-tracking+ # issue - the folder is timestamped and gets picked up by the next sync's cleanup pass anyway.+ s3 = _mock_s3()+ s3._rm = AsyncMock(+ side_effect=botocore.exceptions.ConnectTimeoutError(endpoint_url="https://example.s3.amazonaws.com")+ )++ with _mock_s3_context(s3):+ await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="events",+ file_uris=[],+ use_timestamped_folders=False,+ delete_existing=True,+ )++ s3._rm.assert_awaited_once()+ mock_capture_exception.assert_not_called()+++@patch(f"{_UTIL_MODULE}.capture_exception")+async def test_delete_folder_still_captures_non_transient_error(mock_capture_exception: MagicMock) -> None:+ # A genuine cleanup failure (not a network blip) must still be reported.+ s3 = _mock_s3()+ s3._rm = AsyncMock(side_effect=ValueError("unexpected failure"))++ with _mock_s3_context(s3):+ await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="events",+ file_uris=[],+ use_timestamped_folders=False,+ delete_existing=True,+ )++ s3._rm.assert_awaited_once()+ mock_capture_exception.assert_called_once()diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.pyindex 7e556297fe38..6e5f9a9f3027 100644--- a/products/warehouse_sources/backend/temporal/data_imports/util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py@@ -6,6 +6,7 @@ from uuid import uuid4from django.conf import settings+import botocore.exceptionsfrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions import capture_exception@@ -15,6 +16,20 @@ from posthog.utils import str_to_boolfrom products.data_warehouse.backend.facade.api import aget_s3_clientfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+# A best-effort delete of old query folders can hit a transient S3 connectivity blip+# (connect/read timeout, dropped connection). The folder is timestamped and simply gets+# picked up by the age-based GC on a later sync, so these aren't worth an error-tracking+# issue - unlike a real failure (permissions, missing bucket), which still gets captured.+_TRANSIENT_S3_CONNECTION_EXCEPTIONS = (+ botocore.exceptions.ConnectionError, # covers ConnectTimeoutError, EndpointConnectionError+ botocore.exceptions.ReadTimeoutError,+ botocore.exceptions.ConnectionClosedError,+)+++def _is_transient_s3_connection_error(error: BaseException) -> bool:+ return isinstance(error, _TRANSIENT_S3_CONNECTION_EXCEPTIONS)+class NonRetryableException(Exception):@property@@ -179,7 +194,8 @@ async def prepare_s3_files_for_querying(await s3._rm(file, recursive=True)except Exception as e:await _log(f"Error while deleting old query folder {file}: {e}", level="error")- capture_exception(e)+ if not _is_transient_s3_connection_error(e):+ capture_exception(e)await asyncio.gather(*[delete_folder(file) for file in files_to_delete])