: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 a transient S3 read blip before dropping a CDP file (#113289)
Tom Owers2ff451a3fafd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.pyindex 18bfe1ce893e..0169b45697a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py@@ -33,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdpemitted_rows_key,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (+ aretry_staged_read,aretry_staged_write,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_name@@ -343,8 +344,12 @@ class CDPProducer:row_index = 0+ async def _open_staged_file(path: str = file_path) -> pa.NativeFile:+ return await asyncio.to_thread(fs.open_input_file, path)+try:- with fs.open_input_file(file_path) as f:+ input_file = await aretry_staged_read(_open_staged_file, path=file_path, logger=self.logger)+ with input_file as f:pf = pq.ParquetFile(f)for batch in pf.iter_batches(batch_size=10_000):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.pyindex 92ef2d6baa03..5b1d0bd68b06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/errors.py@@ -1,3 +1,4 @@+import reimport errnofrom django.db import InterfaceError, InternalError, OperationalError@@ -32,6 +33,20 @@ TRANSIENT_OBJECT_STORE_ERRORS = ("The difference between the request time and the current time is too large.",)+# pyarrow's S3FileSystem (the AWS SDK for C++) reports a response it can't classify as the fixed+# "UNKNOWN" error code, which happens whenever AWS replies with no parseable XML error body. A+# bodyless 5xx is always a transient server-side blip - the same class the named 5xx messages above+# cover - and clears on retry. But AWS also omits the body for a HeadObject 403 or 404 (it never+# includes one for HEAD requests, regardless of status), so the bare "AWS Error UNKNOWN" string alone+# can't tell a blip apart from a permanent permission or missing-object error. The HTTP status pyarrow+# puts in the message is the only thing that distinguishes them.+_BODYLESS_UNKNOWN_STATUS_RE = re.compile(r"AWS Error UNKNOWN \(HTTP status (\d{3})\)")+++def _is_bodyless_5xx_unknown_error(error: BaseException) -> bool:+ match = _BODYLESS_UNKNOWN_STATUS_RE.search(str(error))+ return match is not None and match.group(1).startswith("5")+class TransientObjectStoreError(NonReportableError):"""A known-transient object-store blip (see is_transient_object_store_error), re-raised as this@@ -70,6 +85,11 @@ def is_transient_object_store_error(error: BaseException) -> bool:(`_is_too_many_open_files_error`): a descriptor frees the moment another connection/client inthis worker closes, so it's fd pressure on our side, never an object-store or customer problem.+ A bodyless 5xx that pyarrow's S3FileSystem reports as "AWS Error UNKNOWN" (see+ `_is_bodyless_5xx_unknown_error`) is also transient - but only once its status is confirmed to be+ 5xx, because AWS omits the error body (and so reports the same UNKNOWN code) for a permanent+ HeadObject 403 or 404 too.+Deliberately does not cover `ensure_bucket_exists`'s own exhausted `HeadBucket` 403 retry (see`_is_exhausted_head_bucket_forbidden` below) — that check only runs under `USE_LOCAL_SETUP`,where the bucket credentials are operator-configured rather than our own IAM instance role, so an@@ -90,6 +110,8 @@ def is_transient_object_store_error(error: BaseException) -> bool:return Trueif isinstance(error, OSError) and error.errno in (errno.EMFILE, errno.ENFILE):return True+ if isinstance(error, OSError) and _is_bodyless_5xx_unknown_error(error):+ return Truereturn isinstance(error, OSError | deltalake.exceptions.DeltaError) and any(needle in str(error) for needle in TRANSIENT_OBJECT_STORE_ERRORS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.pyindex 717f6e2cf42f..13abd575b0c0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/test/test_delta_errors.py@@ -89,6 +89,28 @@ class TestIsTransientObjectStoreError:PermissionError("The difference between the request time and the current time is too large."),True,),+ (+ # S3 omits the usual XML error body on some 5xx responses, so the AWS SDK for C+++ # (pyarrow's S3FileSystem) can't classify the response and reports it as the fixed+ # "UNKNOWN" code instead of a specific, permanent one like AccessDenied.+ "bodyless_5xx_reported_as_unknown",+ OSError(+ "When reading information for key 'chunk_0.parquet' in bucket 'example-bucket': "+ "AWS Error UNKNOWN (HTTP status 503) during HeadObject operation: No response body."+ ),+ True,+ ),+ (+ # AWS omits the error body for every HeadObject response regardless of status, so a+ # permanent 403/404 reports the same "UNKNOWN" code as the 5xx case above. Only the+ # status in the message tells them apart, and this one must not be retried.+ "bodyless_4xx_reported_as_unknown_not_transient",+ OSError(+ "When reading information for key 'chunk_0.parquet' in bucket 'example-bucket': "+ "AWS Error UNKNOWN (HTTP status 404) during HeadObject operation: No response body."+ ),+ False,+ ),# `get_delta_table` re-raises a recognized transient blip as this wrapper (see# `_capture_unless_transient`) instead of the original OSError/DeltaError. A caller# further up the stack that catches broadly and re-runs this classifier on the caughtdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.pyindex 9e013e8abc88..caa8272be129 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.py@@ -2,7 +2,7 @@import asynciofrom collections.abc import Callable, Coroutine-from typing import Any+from typing import Any, TypeVarfrom structlog.types import FilteringBoundLogger@@ -16,10 +16,13 @@ from posthog.temporal.common.errors import NonReportableError# of the store.PERMANENT_OBJECT_STORE_ERRORS = ("ACCESS_DENIED", "PermanentRedirect")-# Initiating the upload is a single network call, so one blip on it costs the whole chunk. Three-# attempts spend at most 6s of backoff, which is short against a sync that runs for minutes, and-# enough for the object store to serve a request that its own SDK-level retries could not.-_STAGED_WRITE_MAX_ATTEMPTS = 3+# Initiating an upload or opening a file for read is a single network call, so one blip on it costs+# the whole chunk. Three attempts spend at most 6s of backoff, which is short against a sync that+# runs for minutes, and enough for the object store to serve a request that its own SDK-level+# retries could not.+_STAGED_OPERATION_MAX_ATTEMPTS = 3++T = TypeVar("T")class ObjectStoreConfigurationError(NonReportableError):@@ -45,18 +48,18 @@ def is_object_store_configuration_error(error: BaseException) -> bool:return isinstance(error, OSError) and any(needle in str(error) for needle in PERMANENT_OBJECT_STORE_ERRORS)-async def aretry_staged_write(- operation: Callable[[], Coroutine[Any, Any, None]], *, path: str, logger: FilteringBoundLogger-) -> None:- """Run one staged parquet write, retrying a transient object-store failure with backoff.+async def _aretry_staged_operation(+ operation: Callable[[], Coroutine[Any, Any, T]], *, verb: str, path: str, logger: FilteringBoundLogger+) -> T:+ """Run one staged read or write, retrying a transient object-store failure with backoff.Pass a zero-arg callable that produces the awaitable, not the awaitable itself, so a retry can- reissue the write.+ reissue the operation.- A refused write raises ``ObjectStoreConfigurationError`` on the first attempt, because retrying- a grant or an endpoint that the deployment got wrong only delays the same failure. An error the- shared classifier does not recognize is not retried either, so a defect in the pipeline still- fails as fast as it did before.+ A refused operation raises ``ObjectStoreConfigurationError`` on the first attempt, because+ retrying a grant or an endpoint that the deployment got wrong only delays the same failure. An+ error the shared classifier does not recognize is not retried either, so a defect in the+ pipeline still fails as fast as it did before."""from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import pathis_transient_object_store_error,@@ -66,15 +69,37 @@ async def aretry_staged_write(while True:attempt += 1try:- await operation()- return+ return await operation()except Exception as e:if is_object_store_configuration_error(e):- raise ObjectStoreConfigurationError(f"Object store refused the staged write to {path}") from e- if attempt >= _STAGED_WRITE_MAX_ATTEMPTS or not is_transient_object_store_error(e):+ raise ObjectStoreConfigurationError(f"Object store refused the staged {verb} of {path}") from e+ if attempt >= _STAGED_OPERATION_MAX_ATTEMPTS or not is_transient_object_store_error(e):raiseawait logger.awarning(- f"Transient object-store error staging {path} "- f"(attempt {attempt}/{_STAGED_WRITE_MAX_ATTEMPTS}), retrying: {e}"+ f"Transient object-store error on the staged {verb} of {path} "+ f"(attempt {attempt}/{_STAGED_OPERATION_MAX_ATTEMPTS}), retrying: {e}")await asyncio.sleep(2**attempt)+++async def aretry_staged_write(+ operation: Callable[[], Coroutine[Any, Any, None]], *, path: str, logger: FilteringBoundLogger+) -> None:+ """Run one staged parquet write, retrying a transient object-store failure with backoff.++ Pass a zero-arg callable that produces the awaitable, not the awaitable itself, so a retry can+ reissue the write.+ """+ await _aretry_staged_operation(operation, verb="write", path=path, logger=logger)+++async def aretry_staged_read(+ operation: Callable[[], Coroutine[Any, Any, T]], *, path: str, logger: FilteringBoundLogger+) -> T:+ """Open one staged file for read, retrying a transient object-store failure with backoff.++ Pass a zero-arg callable that produces the awaitable, not the awaitable itself, so a retry can+ reissue the open. Safe to retry: opening a staged file is a HeadObject call that reads nothing+ and produces no rows, so a retried open can't duplicate anything a prior attempt already sent.+ """+ return await _aretry_staged_operation(operation, verb="open", path=path, logger=logger)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.pyindex 5b2df439b69c..1b6bcf70f6d3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py@@ -612,6 +612,74 @@ async def test_produce_to_kafka_from_s3_s3_read_failure(mock_capture_exception,mock_fs.delete_file.assert_called_once()[email protected]_db(transaction=True)+@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")+@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.capture_exception")+async def test_produce_to_kafka_from_s3_retries_a_transient_s3_read_failure(+ mock_capture_exception, mock_get_s3_client, team+):+ # A HeadObject 503 that pyarrow surfaces as "AWS Error UNKNOWN" is a known-transient S3 blip+ # (see is_transient_object_store_error), not a bug in our code: the open must be retried before+ # the per-file swallow-and-delete path (which would otherwise drop the file's rows for good) is+ # reached.+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ mock_s3_client = mock.AsyncMock()+ mock_s3_client._ls.return_value = [{"Key": "path/chunk_0.parquet", "type": "file"}]+ mock_get_s3_client.return_value.__aenter__ = mock.AsyncMock(return_value=mock_s3_client)+ mock_get_s3_client.return_value.__aexit__ = mock.AsyncMock(return_value=False)++ mock_kafka_producer = MagicMock()+ mock_kafka_producer.produce = mock.AsyncMock()+ mock_kafka_producer.flush = mock.AsyncMock()+ mock_kafka_producer.close = mock.AsyncMock()++ test_data = pa.table({"id": [1], "name": ["Alice"]})+ parquet_buffer = BytesIO()+ pq.write_table(test_data, parquet_buffer, compression="zstd")+ parquet_buffer.seek(0)++ mock_file = MagicMock()+ mock_file.__enter__ = MagicMock(return_value=parquet_buffer)+ mock_file.__exit__ = MagicMock(return_value=False)++ transient_error = OSError(+ "When reading information for key 'chunk_0.parquet' in bucket 'example-bucket': "+ "AWS Error UNKNOWN (HTTP status 503) during HeadObject operation: No response body."+ )+ mock_fs = MagicMock()+ mock_fs.open_input_file.side_effect = [transient_error, mock_file]+ mock_fs.delete_file = MagicMock()++ producer = CDPProducer.for_source(+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()+ )++ with (+ patch.object(producer, "_get_fs", return_value=mock_fs),+ _patch_async_producer_scope(mock_kafka_producer),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store.asyncio.sleep",+ new=mock.AsyncMock(),+ ),+ ):+ await producer.produce_to_kafka_from_s3()++ assert mock_fs.open_input_file.call_count == 2+ mock_kafka_producer.produce.assert_called_once()+ mock_fs.delete_file.assert_called_once()+ mock_capture_exception.assert_not_called()++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")