: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): retry transient S3 write errors in the v3 pipeline writer (#73620)
Tom Owers923bf9870d69
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.pyindex f7dbb56f49f5..04a12691c53c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_writer.py@@ -1,8 +1,64 @@import json+import errno++import pytest+from unittest.mock import MagicMock, patchimport pyarrow as pa-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import build_schema_dict+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import (+ _write_parquet_to_s3,+ build_schema_dict,+)+++def _fake_s3(open_side_effect: list) -> MagicMock:+ s3 = MagicMock()+ s3.open.return_value.__enter__.side_effect = open_side_effect+ # A MagicMock's auto-mocked __exit__ returns a truthy MagicMock by default, which would+ # suppress the exception pyarrow.parquet.write_table raises inside the `with` block.+ s3.open.return_value.__exit__.return_value = False+ return s3+++class TestWriteParquetToS3:+ @patch("tenacity.nap.time.sleep")+ @patch("pyarrow.parquet.write_table")+ def test_retries_transient_os_error_then_succeeds(self, mock_write_table, _mock_sleep) -> None:+ # s3fs translates a truncated-upload S3 response (e.g. IncompleteBody) into a plain+ # OSError; a single dropped connection shouldn't fail the whole batch write.+ f = MagicMock()+ s3 = _fake_s3([f, f])+ mock_write_table.side_effect = [OSError(errno.EINVAL, "The request body terminated unexpectedly"), None]++ _write_parquet_to_s3(s3, "bucket/part-0000.parquet", pa.table({"id": [1]}), "zstd")++ assert mock_write_table.call_count == 2++ @patch("tenacity.nap.time.sleep")+ @patch("pyarrow.parquet.write_table")+ def test_reraises_after_persistent_os_error(self, mock_write_table, _mock_sleep) -> None:+ f = MagicMock()+ s3 = _fake_s3([f, f, f, f])+ mock_write_table.side_effect = OSError(errno.EINVAL, "The request body terminated unexpectedly")++ with pytest.raises(OSError):+ _write_parquet_to_s3(s3, "bucket/part-0000.parquet", pa.table({"id": [1]}), "zstd")++ assert mock_write_table.call_count == 4++ @patch("pyarrow.parquet.write_table")+ def test_does_not_retry_permission_error(self, mock_write_table) -> None:+ # PermissionError (e.g. AccessDenied/InvalidAccessKeyId) is an OSError subclass but not+ # transient — retrying it just delays a failure that will happen on every attempt.+ f = MagicMock()+ s3 = _fake_s3([f])+ mock_write_table.side_effect = PermissionError("Access Denied")++ with pytest.raises(PermissionError):+ _write_parquet_to_s3(s3, "bucket/part-0000.parquet", pa.table({"id": [1]}), "zstd")++ assert mock_write_table.call_count == 1class TestBuildSchemaDict:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.pyindex b33465eb2c8f..b7acb4ec80e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/writer.py@@ -8,6 +8,7 @@ import pyarrow as paimport pyarrow.parquet as pqfrom structlog.types import FilteringBoundLoggerfrom temporalio import activity+from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential_jitterfrom products.data_warehouse.backend.facade.api import get_s3_clientfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -53,6 +54,28 @@ def build_schema_dict(schema: pa.Schema) -> dict:}+def _is_transient_s3_write_error(exc: BaseException) -> bool:+ # s3fs translates most S3-side write failures (IncompleteBody, InternalError,+ # SlowDown/ServiceUnavailable, ...) into a plain OSError. PermissionError,+ # FileNotFoundError, and TimeoutError are also OSError subclasses but signal+ # non-transient causes (bad credentials, deleted bucket) that retrying won't fix,+ # so only the exact base type is treated as retryable here.+ return type(exc) is OSError+++@retry(+ retry=retry_if_exception(_is_transient_s3_write_error),+ stop=stop_after_attempt(4),+ wait=wait_exponential_jitter(initial=1, max=10),+ reraise=True,+)+def _write_parquet_to_s3(+ s3: s3fs.S3FileSystem, s3_path: str, pa_table: pa.Table, compression: ParquetCompression+) -> None:+ with s3.open(s3_path, "wb") as f:+ pq.write_table(pa_table, f, compression=compression)++class S3BatchWriter:_job: ExternalDataJob_schema_id: str@@ -103,8 +126,7 @@ class S3BatchWriter:write_start = time.perf_counter()try:s3_path_without_protocol = strip_s3_protocol(s3_path)- with self._s3.open(s3_path_without_protocol, "wb") as f:- pq.write_table(pa_table, f, compression=self._compression)+ _write_parquet_to_s3(self._s3, s3_path_without_protocol, pa_table, self._compression)except Exception as e:if activity.in_activity():get_s3_write_errors_metric(type(e).__name__).add(1)