: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-warehouse): retry throttled s3 cleanup and wrap fatal errors (#104467)
Tom Owersa487625f2836
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 aca97c0dc14d..d5b7c6cf4850 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,3 +1,4 @@+import errnoimport contextlibfrom types import SimpleNamespace@@ -13,10 +14,23 @@ from posthog.temporal.common.errors import NonReportableErrorfrom products.warehouse_sources.backend.temporal.data_imports import util as util_modulefrom products.warehouse_sources.backend.temporal.data_imports.util import (NonRetryableException,+ S3OperationError,_is_transient_s3_connection_error,prepare_s3_files_for_querying,)+# An S3 throttling response, in the two shapes it reaches these helpers in: translated by s3fs into+# an OSError carrying errno EBUSY, and as the untranslated botocore ClientError.+_THROTTLING_ERRORS = [+ ("os_error_ebusy", OSError(errno.EBUSY, "Reduce your request rate for this prefix.")),+ (+ "untranslated_client_error",+ botocore.exceptions.ClientError(+ {"Error": {"Code": "SlowDown", "Message": "Reduce your request rate for this prefix."}}, "DeleteObjects"+ ),+ ),+]+_UTIL_MODULE = "products.warehouse_sources.backend.temporal.data_imports.util"@@ -222,11 +236,20 @@ class TestPrepareS3FilesForQuerying:delete_existing=False,)- async def test_retries_transient_s3_internal_error_during_copy(self):- # S3's CopyObject can return its own InternalError after boto's own request retries are- # already exhausted, which s3fs surfaces as a bare OSError. Regression for that surfacing- # straight through the activity instead of retrying the (idempotent) copy batch.- transient_error = OSError("[Errno 121] We encountered an internal error. Please try again.")+ @parameterized.expand(+ [+ # S3's CopyObject can return its own InternalError after boto's own request retries are+ # already exhausted, which s3fs surfaces as a bare OSError.+ ("internal_error", OSError("[Errno 121] We encountered an internal error. Please try again.")),+ # A throttled CopyObject is the same class of blip. It is recognized by the errno s3fs+ # translates every back-off response code to, so a store whose wording the message+ # needles don't match is still retried rather than failing the sync.+ ("throttled", OSError(errno.EBUSY, "Reduce your request rate for this prefix.")),+ ]+ )+ async def test_retries_transient_s3_error_during_copy(self, name: str, transient_error: OSError):+ # Regression for these surfacing straight through the activity instead of retrying the+ # (idempotent) copy batch.cp_file = AsyncMock(side_effect=[transient_error, None])s3 = _fake_s3(_cp_file=cp_file)@@ -243,22 +266,44 @@ class TestPrepareS3FilesForQuerying:assert cp_file.await_count == 2- async def test_propagates_non_transient_os_error_without_retry(self):- # A genuine OSError that isn't a recognized transient S3 blip must surface immediately -- # otherwise a real bug would burn through the retry budget before being reported.- cp_file = AsyncMock(side_effect=OSError("Permission denied: bucket policy forbids this operation"))+ @parameterized.expand(+ [+ # s3fs maps every S3 auth-failure code onto PermissionError, with the server's own+ # message and no errno.+ ("access_denied", PermissionError("Access Denied: s3://example-bucket/job/widgets/part-0.parquet")),+ # An object store with no free space rejects the CopyObject under a code s3fs has no+ # mapping for, so it arrives as a bare OSError with errno EIO.+ (+ "storage_backend_full",+ OSError(+ errno.EIO,+ "An error occurred (StorageFull) when calling the CopyObject operation on "+ "s3://example-bucket/job/widgets/part-0.parquet: the storage backend is out of free space.",+ ),+ ),+ ]+ )+ async def test_reports_fatal_copy_failure_without_the_bucket_or_key(self, name: str, fatal_error: OSError):+ # A failure a retry can't fix must surface immediately rather than burning the retry budget,+ # and it must not surface as the raw s3fs text: that text names our bucket and one team's+ # object key, and an unclassified activity failure's message is both the error the customer+ # reads and the title error tracking groups on.+ cp_file = AsyncMock(side_effect=fatal_error)s3 = _fake_s3(_cp_file=cp_file)with patch.object(util_module, "aget_s3_client", return_value=_FakeS3CM(s3)):- with pytest.raises(OSError):+ with pytest.raises(S3OperationError) as raised:await prepare_s3_files_for_querying(folder_path="job",- table_name="my_table",- file_uris=["s3://bucket/job/my_table/part-0.parquet"],+ table_name="widgets",+ file_uris=["s3://example-bucket/job/widgets/part-0.parquet"],delete_existing=False,)assert cp_file.await_count == 1+ assert "query folder" in str(raised.value)+ assert "example-bucket" not in str(raised.value)+ assert raised.value.__cause__ is fatal_errorasync def test_tolerates_job_folder_missing_on_first_materialization(self):# A brand new table/model has no prior content in S3, so listing the job folder to@@ -371,3 +416,80 @@ async def test_delete_folder_still_captures_non_transient_error(mock_capture_excs3._rm.assert_awaited_once()mock_capture_exception.assert_called_once()++[email protected](_THROTTLING_ERRORS)+async def test_delete_folder_retries_a_throttled_delete(name: str, throttling_error: BaseException) -> None:+ # One recursive delete of a query folder is a list plus a batched DeleteObjects against a single+ # prefix, which S3 answers with a back-off response when a bulk cleanup outruns its request-rate+ # limit. The delete is idempotent, so it must be retried rather than reported as a failure.+ s3 = _mock_s3()+ s3._rm = AsyncMock(side_effect=[throttling_error, None])++ with (+ _mock_s3_context(s3),+ patch(f"{_UTIL_MODULE}.capture_exception") as mock_capture_exception,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="widgets",+ file_uris=[],+ use_timestamped_folders=False,+ delete_existing=True,+ )++ assert s3._rm.await_count == 2+ mock_capture_exception.assert_not_called()+++async def test_delete_folder_reports_throttling_that_outlasts_the_retry_budget() -> None:+ # The retries are bounded, and a store that keeps throttling us is no longer a blip that clears+ # on its own. Guards the silent-cleanup regression the other direction: the budget running out+ # must still report, and report the sanitized error rather than the raw path.+ throttling_error = OSError(errno.EBUSY, "Reduce your request rate for this prefix.")+ s3 = _mock_s3()+ s3._rm = AsyncMock(side_effect=throttling_error)++ with (+ _mock_s3_context(s3),+ patch(f"{_UTIL_MODULE}.capture_exception") as mock_capture_exception,+ patch("asyncio.sleep", new_callable=AsyncMock),+ ):+ await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="widgets",+ file_uris=[],+ use_timestamped_folders=False,+ delete_existing=True,+ )++ assert s3._rm.await_count == util_module._DELETE_FOLDER_MAX_ATTEMPTS+ mock_capture_exception.assert_called_once()+ captured = mock_capture_exception.call_args.args[0]+ assert isinstance(captured, S3OperationError)+ assert captured.__cause__ is throttling_error+++@patch(f"{_UTIL_MODULE}.capture_exception")+async def test_delete_folder_treats_an_already_deleted_folder_as_done(mock_capture_exception: MagicMock) -> None:+ # Two cleanup passes can pick the same timestamped folder, and s3fs raises FileNotFoundError for+ # a prefix with no objects under it. The folder being gone is what this delete wanted, so it is+ # not worth an error-tracking issue.+ s3 = _mock_s3()+ s3._rm = AsyncMock(side_effect=FileNotFoundError("s3://example-bucket/job/widgets__query_1700000000"))++ with _mock_s3_context(s3):+ await prepare_s3_files_for_querying(+ folder_path="job",+ table_name="widgets",+ file_uris=[],+ use_timestamped_folders=False,+ delete_existing=True,+ )++ s3._rm.assert_awaited_once()+ mock_capture_exception.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/util.py b/products/warehouse_sources/backend/temporal/data_imports/util.pyindex 5d7def9d5e65..9f5391573c86 100644--- a/products/warehouse_sources/backend/temporal/data_imports/util.py+++ b/products/warehouse_sources/backend/temporal/data_imports/util.py@@ -1,4 +1,5 @@import re+import errnoimport asynciofrom collections.abc import Awaitable, Callablefrom datetime import datetime@@ -21,7 +22,8 @@ from products.warehouse_sources.backend.temporal.data_imports.naming_convention# 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.+# issue - unlike a failure that needs a human (denied permissions, a storage backend with no+# free space), which still gets captured._TRANSIENT_S3_CONNECTION_EXCEPTIONS = (botocore.exceptions.ConnectionError, # covers ConnectTimeoutError, EndpointConnectionErrorbotocore.exceptions.ReadTimeoutError,@@ -33,6 +35,62 @@ def _is_transient_s3_connection_error(error: BaseException) -> bool:return isinstance(error, _TRANSIENT_S3_CONNECTION_EXCEPTIONS)+# s3fs turns an S3 error response into a Python exception by error code+# (``s3fs/errors.py::translate_boto_error``) and keeps the original ``ClientError`` on ``__cause__``.+# Every code S3 uses to ask a client to back off - ``SlowDown``, ``ServiceUnavailable``,+# ``OperationAborted`` and the bare 503/409 statuses - maps onto ``errno.EBUSY``, so the errno+# identifies "busy, come back later" without matching a vendor's free-text message. The code itself+# is read too, for a ``ClientError`` that reaches us untranslated.+_S3_THROTTLING_ERROR_CODES = frozenset({"SlowDown", "ServiceUnavailable", "OperationAborted", "503", "409"})+++def _s3_error_code(error: BaseException) -> Optional[str]:+ client_error = error if isinstance(error, botocore.exceptions.ClientError) else error.__cause__+ if not isinstance(client_error, botocore.exceptions.ClientError):+ return None+ code = client_error.response.get("Error", {}).get("Code")+ return str(code) if code is not None else None+++def _is_s3_throttling_error(error: BaseException) -> bool:+ """True when the object store refused the request to protect itself, rather than failing it.++ The same request succeeds once the rate drops, so the caller retries with backoff instead of+ reporting. Bulk operations hit this the hardest: one recursive delete of a query folder is a+ list plus a batched DeleteObjects against a single prefix, which is exactly the shape S3+ rate-limits.+ """+ if isinstance(error, OSError) and error.errno == errno.EBUSY:+ return True+ return _s3_error_code(error) in _S3_THROTTLING_ERROR_CODES+++class S3OperationError(Exception):+ """An operation on PostHog's own data-warehouse bucket failed for a reason a retry cannot fix.++ Denied permissions and a storage backend out of free space both reach us as the raw s3fs text,+ which names our bucket, one team's folder and the object key. That text is not only logged: an+ activity failure we do not classify has its message stored as the ``latest_error`` a customer+ reads (``external_data_job.py::_customer_facing_error``), and it is also the title error+ tracking groups on, where a per-object message splits one condition across many issues. This+ error's message names the operation and the kind of path instead, and the original error stays+ on ``__cause__`` for the logs and the captured exception chain.++ Deliberately not a ``NonReportableError``: these conditions need a human, so they must still+ reach error tracking.+ """++ def __init__(self, operation: str, cause: BaseException) -> None:+ super().__init__(+ f"PostHog couldn't {operation}. The problem is in PostHog's own storage, not in "+ "your data. The next scheduled run will try again."+ )+ self.operation = operation+ # Set here rather than through ``raise ... from cause`` so a site that reports this error+ # without raising it keeps the original too.+ self.__cause__ = cause++class NonRetryableException(NonReportableError):"""Raised only for errors already classified as a permanent customer/upstream condition(bad credentials, denied permissions, a deleted remote) via a source's@@ -72,6 +130,11 @@ S3_DELETE_TIME_BUFFER = 600# past that documented worst case; 4 attempts (~14s) wasn't._COPY_FILES_MAX_ATTEMPTS = 6+# A recursive delete is idempotent (a folder already gone is the outcome it wanted), so retrying the+# whole delete after a throttling response is as safe as retrying one call. 4 attempts gives ~14s of+# cumulative backoff (2+4+8s), the same budget `_purge_s3_prefix` uses against the same condition.+_DELETE_FOLDER_MAX_ATTEMPTS = 4+def is_posthog_team(team_id: int) -> bool:DEBUG: bool = get_from_env("DEBUG", False, type_cast=str_to_bool)@@ -248,8 +311,13 @@ async def prepare_s3_files_for_querying(# s3fs wraps a CopyObject/PutObject 5xx (e.g. S3's InternalError, already retried to# exhaustion at the boto layer) as a plain OSError. That's a blip on S3's side, not a# bug here - retry the whole (idempotent) copy batch with backoff before giving up.- if attempt >= _COPY_FILES_MAX_ATTEMPTS or not is_transient_object_store_error(e):- raise+ if attempt >= _COPY_FILES_MAX_ATTEMPTS or not (+ is_transient_object_store_error(e) or _is_s3_throttling_error(e)+ ):+ # Either the failure needs a human (denied permissions, a storage backend with no+ # free space) or the retries ran out. Both leave the raw s3fs message, so re-raise+ # as the typed error that names the operation without the bucket and key.+ raise S3OperationError("copy this table's files into its query folder", e)await _log(f"Transient S3 error while copying files (attempt {attempt}/{_COPY_FILES_MAX_ATTEMPTS}), "f"retrying: {e}",@@ -263,12 +331,35 @@ async def prepare_s3_files_for_querying(async def delete_folder(file: str) -> None:async with semaphore:- try:- await s3._rm(file, recursive=True)- except Exception as e:- await _log(f"Error while deleting old query folder {file}: {e}", level="error")- if not _is_transient_s3_connection_error(e):- capture_exception(e)+ delete_attempt = 0+ while True:+ delete_attempt += 1+ try:+ await s3._rm(file, recursive=True)+ return+ except FileNotFoundError:+ # The folder is already gone: another sync's cleanup pass took it, or an+ # earlier attempt of this one deleted it and lost the response. That is+ # the outcome this delete wanted, so there is nothing to report.+ await _log(f"Old query folder was already deleted: {file}")+ return+ except Exception as e:+ if _is_s3_throttling_error(e) and delete_attempt < _DELETE_FOLDER_MAX_ATTEMPTS:+ await _log(+ f"S3 throttled the delete of old query folder {file} (attempt "+ f"{delete_attempt}/{_DELETE_FOLDER_MAX_ATTEMPTS}), retrying: {e}",+ level="error",+ )+ await asyncio.sleep(2**delete_attempt)+ continue++ await _log(f"Error while deleting old query folder {file}: {e}", level="error")+ if not _is_transient_s3_connection_error(e):+ capture_exception(S3OperationError("delete an old query folder for this table", e))+ # Cleanup stays best effort: the folder is timestamped, so the age-based+ # GC above picks it up on a later sync. Failing the sync over it would+ # throw away a load that has already landed.+ returnawait asyncio.gather(*[delete_folder(file) for file in files_to_delete])