: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(batch-exports): return clear error when Redshift can't read staged S3 files (#61603)
Rossd81a8ed81d79
diff --git a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.pyindex 70a68af8321b..97694d792ab2 100644--- a/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py+++ b/products/batch_exports/backend/temporal/destinations/redshift_batch_export.py@@ -101,6 +101,11 @@ NON_RETRYABLE_ERROR_TYPES = ("InvalidCredentialsError",# Raised by Redshift client when the cluster has insufficient system resources."InsufficientSystemResourcesError",+ # The S3 credentials provided for the COPY can't read the staged files.+ "InsufficientS3PermissionsError",+ # Redshift failed to COPY the staged files from S3 (IAM role auth, cause not locally confirmable).+ # These (read access, region, manifest) don't self-heal, so retrying is pointless.+ "RedshiftS3CopyError",)@@ -131,6 +136,41 @@ class InsufficientSystemResourcesError(Exception):pass+class InsufficientS3PermissionsError(Exception):+ """Error raised when Redshift cannot read the staged files from S3 during COPY.++ Redshift surfaces a missing read permission as the misleading "COPY with MANIFEST parameter+ requires full path of an S3 object" error rather than a clean access-denied. We translate it+ into something actionable once we've confirmed S3 read is denied with the same credentials.+ """++ def __init__(self, bucket: str):+ super().__init__(+ f"Redshift could not read the staged files from S3 bucket '{bucket}'."+ " The S3 credentials provided for the Redshift COPY are missing read access"+ " (Redshift requires both 's3:GetObject' and 's3:ListBucket')."+ " If the bucket uses SSE-KMS encryption, 'kms:Decrypt' on the key is also required."+ " Grant read access and retry."+ )+++class RedshiftS3CopyError(Exception):+ """Error raised when Redshift fails to COPY the staged files from S3 and we can't pin down why.++ Used for IAM role auth, which we can't probe locally to confirm a read denial. The message points+ at the common causes of a failed COPY so the user knows where to look.+ """++ def __init__(self, bucket: str):+ super().__init__(+ f"Redshift could not COPY the staged files from S3 bucket '{bucket}'."+ " Common causes: the IAM role provided for the Redshift COPY lacks read access to the"+ " bucket (Redshift requires 's3:GetObject' and 's3:ListBucket', plus 'kms:Decrypt' if the"+ " bucket uses SSE-KMS encryption), or the bucket is in a different AWS region than the"+ " Redshift cluster. Verify the role's permissions and the bucket region, then retry."+ )++class ClientErrorGroup(ExceptionGroup):"""Exception group wrapping multiple `botocore.exceptions.ClientError`.@@ -1121,6 +1161,83 @@ async def delete_uploaded_files(tg.create_task(delete_key(manifest_key))+async def is_s3_read_access_denied(+ bucket: str,+ region_name: str,+ credentials: AWSCredentials,+ keys: collections.abc.Sequence[str],+) -> bool:+ """Return True only if a HEAD positively confirms read access is denied for any of `keys`.++ We `head_object` each key with the same credentials Redshift uses for the COPY. A 403 / Access+ Denied / Forbidden confirms a read-permission problem (including the SSE-KMS 'kms:Decrypt' case,+ which also fails the HEAD). Anything else returns False — a successful HEAD, a non-permission+ error (e.g. a 404), or an unexpected probe failure (e.g. a connection error). This is best-effort+ by design: callers should only escalate to a hard error on a confirmed denial, and never mask an+ original failure just because the probe itself couldn't run.+ """+ try:+ session = aioboto3.Session()+ async with session.client(+ "s3",+ region_name=region_name,+ aws_access_key_id=credentials.aws_access_key_id,+ aws_secret_access_key=credentials.aws_secret_access_key,+ ) as client:+ for key in keys:+ try:+ await client.head_object(Bucket=bucket, Key=key)+ except botocore.exceptions.ClientError as err:+ status = err.response.get("ResponseMetadata", {}).get("HTTPStatusCode")+ code = err.response.get("Error", {}).get("Code")+ if status == 403 or code in ("403", "AccessDenied", "Forbidden"):+ return True+ except Exception:+ LOGGER.warning("S3 read-access probe failed; treating as not confirmed", exc_info=True)+ return False+++async def check_and_raise_redshift_copy_error(+ err: psycopg.errors.InternalError_,+ *,+ authorization: IAMRole | AWSCredentials,+ bucket: str,+ region_name: str,+ manifest_key: str,+ files_uploaded: collections.abc.Sequence[str],+) -> None:+ """Translate a failed Redshift COPY into an actionable error.++ Redshift reports a missing read permission as the misleading "requires full path of an S3 object"+ error. We always generate a well-formed manifest, so for credential auth we confirm the real+ cause by probing S3 read access (HEAD on the manifest + a staged file) with the same credentials+ Redshift uses for the COPY: a confirmed denial raises `InsufficientS3PermissionsError`, otherwise+ we return so the caller re-raises the original (it's some other COPY problem).++ IAM role auth can't be probed locally, so we can't confirm the cause. We only translate when the+ error matches a known S3 read/access marker, raising the more generic `RedshiftS3CopyError` that+ points at the likely culprits (role read access or bucket region). Any other COPY error returns+ unchanged so it keeps its original message and retry behaviour.+ """+ if isinstance(authorization, AWSCredentials):+ probe_keys = [manifest_key, *files_uploaded[:1]]+ if await is_s3_read_access_denied(+ bucket=bucket, region_name=region_name, credentials=authorization, keys=probe_keys+ ):+ raise InsufficientS3PermissionsError(bucket) from err+ return++ markers = (+ "requires full path of an S3 object",+ "Access Denied",+ "S3ServiceException",+ "Forbidden",+ )+ diagnostics = (str(err), err.diag.message_primary or "", err.diag.message_detail or "")+ if any(marker in text for text in diagnostics for marker in markers):+ raise RedshiftS3CopyError(bucket) from err++@activity.defn@handle_non_retryable_errors(NON_RETRYABLE_ERROR_TYPES)async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInputs) -> BatchExportResult:@@ -1331,14 +1448,25 @@ async def copy_into_redshift_activity_from_stage(inputs: RedshiftCopyActivityInptry:external_logger.info(f"Copying {len(consumer.files_uploaded)} file/s into Redshift")- await redshift_client.acopy_from_s3_bucket(- table_name=redshift_stage_table,- parquet_fields=[field.name for field in transformer.schema],- schema_name=inputs.table.schema_name,- s3_bucket=inputs.copy.s3_bucket.name,- manifest_key=manifest_key,- authorization=inputs.copy.authorization,- )+ try:+ await redshift_client.acopy_from_s3_bucket(+ table_name=redshift_stage_table,+ parquet_fields=[field.name for field in transformer.schema],+ schema_name=inputs.table.schema_name,+ s3_bucket=inputs.copy.s3_bucket.name,+ manifest_key=manifest_key,+ authorization=inputs.copy.authorization,+ )+ except psycopg.errors.InternalError_ as err:+ await check_and_raise_redshift_copy_error(+ err,+ authorization=inputs.copy.authorization,+ bucket=inputs.copy.s3_bucket.name,+ region_name=inputs.copy.s3_bucket.region_name,+ manifest_key=manifest_key,+ files_uploaded=consumer.files_uploaded,+ )+ raiseif merge_settings.requires_merge is True:await redshift_client.amerge_tables(diff --git a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.pyindex 555cf1809a3c..14d513b9355b 100644--- a/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/redshift/test_redshift_utils.py@@ -1,17 +1,24 @@import jsonimport uuid+from typing import Anyimport pytestfrom unittest import mockfrom django.conf import settings+import psycopgimport aioboto3import pytest_asyncioimport botocore.exceptions+from products.batch_exports.backend.service import AWSCredentialsfrom products.batch_exports.backend.temporal.destinations.redshift_batch_export import (ClientErrorGroup,+ InsufficientS3PermissionsError,+ RedshiftS3CopyError,+ check_and_raise_redshift_copy_error,+ is_s3_read_access_denied,upload_manifest_file,)from products.batch_exports.backend.temporal.temporary_file import remove_escaped_whitespace_recursive@@ -143,3 +150,137 @@ async def test_upload_manifest_file_raises_on_client_error(minio_client, bucket_)assert all(isinstance(exc, botocore.exceptions.ClientError) for exc in exc_info.value.exceptions)assert exc_info.value.ops == {"list_objects_v2": {"AccessDenied"}} # type: ignore+++def _mock_s3_session_with_head_object(head_object: mock.AsyncMock) -> mock.MagicMock:+ """Build a mocked aioboto3 Session whose S3 client uses the given head_object mock."""+ mock_client = mock.MagicMock()+ mock_client.head_object = head_object++ mock_context_manager = mock.MagicMock()+ mock_context_manager.__aenter__.return_value = mock_client+ mock_context_manager.__aexit__.return_value = None++ mock_session_instance = mock.MagicMock()+ mock_session_instance.client.return_value = mock_context_manager+ return mock_session_instance+++ "error_code,status_code,expected",+ [+ ("AccessDenied", 403, True),+ ("403", 403, True),+ (None, None, False),+ ("404", 404, False),+ ],+)+async def test_is_s3_read_access_denied(error_code, status_code, expected):+ """Test we report read access as denied only on a 403/AccessDenied HEAD."""+ if error_code is None:+ head_object = mock.AsyncMock(return_value={})+ else:+ # Typed as Any to skip the botocore response TypedDict's required-key checks.+ response: Any = {"Error": {"Code": error_code}, "ResponseMetadata": {"HTTPStatusCode": status_code}}+ head_object = mock.AsyncMock(side_effect=botocore.exceptions.ClientError(response, "HeadObject"))++ with mock.patch(+ "products.batch_exports.backend.temporal.destinations.redshift_batch_export.aioboto3.Session"+ ) as mock_session_class:+ mock_session_class.return_value = _mock_s3_session_with_head_object(head_object)++ denied = await is_s3_read_access_denied(+ bucket="test-bucket",+ region_name="us-east-1",+ credentials=AWSCredentials(aws_access_key_id="key", aws_secret_access_key="secret"),+ keys=["some/manifest.json", "some/file-0.parquet.zst"],+ )++ assert denied is expected+++async def test_is_s3_read_access_denied_swallows_unexpected_error():+ """An unexpected probe failure (e.g. a connection error) is treated as 'not confirmed' (False)."""+ head_object = mock.AsyncMock(side_effect=botocore.exceptions.EndpointConnectionError(endpoint_url="https://s3"))++ with mock.patch(+ "products.batch_exports.backend.temporal.destinations.redshift_batch_export.aioboto3.Session"+ ) as mock_session_class:+ mock_session_class.return_value = _mock_s3_session_with_head_object(head_object)++ denied = await is_s3_read_access_denied(+ bucket="test-bucket",+ region_name="us-east-1",+ credentials=AWSCredentials(aws_access_key_id="key", aws_secret_access_key="secret"),+ keys=["some/manifest.json"],+ )++ assert denied is False+++class _FakeDiag:+ def __init__(self, primary: str | None = None, detail: str | None = None):+ self.message_primary = primary+ self.message_detail = detail+++class _FakeInternalError(psycopg.errors.InternalError_):+ """Stand-in for a Redshift COPY error. psycopg builds `diag` from driver state we can't fake, so+ we override it to expose the message fields the code inspects."""++ def __init__(self, message: str = "", *, primary: str | None = None, detail: str | None = None):+ super().__init__(message)+ self._fake_diag = _FakeDiag(primary, detail)++ @property+ def diag(self) -> Any:+ return self._fake_diag++[email protected]("denied", [True, False])+async def test_check_and_raise_redshift_copy_error_credentials(denied):+ """With credential auth we probe S3 and only raise the specific error when read is denied."""+ credentials = AWSCredentials(aws_access_key_id="key", aws_secret_access_key="secret")++ with mock.patch(+ "products.batch_exports.backend.temporal.destinations.redshift_batch_export.is_s3_read_access_denied",+ new=mock.AsyncMock(return_value=denied),+ ):+ call = check_and_raise_redshift_copy_error(+ _FakeInternalError("COPY failed"),+ authorization=credentials,+ bucket="test-bucket",+ region_name="us-east-1",+ manifest_key="prefix/manifest.json",+ files_uploaded=["prefix/file-0.parquet.zst"],+ )+ if denied:+ with pytest.raises(InsufficientS3PermissionsError):+ await call+ else:+ await call # should not raise+++ "error,should_raise",+ [+ (_FakeInternalError("COPY with MANIFEST parameter requires full path of an S3 object"), True),+ (_FakeInternalError("copy failed", detail="S3ServiceException: Access Denied"), True),+ (_FakeInternalError("syntax error at or near 'foo'"), False),+ ],+)+async def test_check_and_raise_redshift_copy_error_iam_role(error, should_raise):+ """IAM role auth can't be probed, so we translate only recognised S3 read/access failures."""+ call = check_and_raise_redshift_copy_error(+ error,+ authorization="arn:aws:iam::123456789012:role/redshift-copy",+ bucket="test-bucket",+ region_name="us-east-1",+ manifest_key="prefix/manifest.json",+ files_uploaded=["prefix/file-0.parquet.zst"],+ )+ if should_raise:+ with pytest.raises(RedshiftS3CopyError):+ await call+ else:+ await call # should not raise