: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): stop retrying a refused warehouse bucket check (#104465)
Tom Owers19f273dd3f91
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/common.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/common.pyindex ad21807c7286..b37137e2d794 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/common.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/common.py@@ -5,8 +5,10 @@ from datetime import UTC, datetimefrom django.conf import settingsimport structlog+import botocore.exceptionsfrom products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_client+from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableExceptionlogger = structlog.get_logger(__name__)@@ -44,6 +46,18 @@ def get_data_folder(base_folder: str) -> str:return f"{base_folder}/data"+def _is_forbidden(error: botocore.exceptions.ClientError) -> bool:+ """Whether the S3 API refused the call because of credentials or a bucket policy.++ HeadBucket sends no body, so botocore has only the HTTP status to put in "Code" and reports+ the refusal as "403" instead of AccessDenied. Stores that do return a body keep the named+ code, so both forms have to be recognized.+ """+ if error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") == 403:+ return True+ return error.response.get("Error", {}).get("Code") in ("403", "AccessDenied", "Forbidden")++def ensure_bucket() -> None:"""Ensure the S3 bucket exists for local development."""if settings.USE_LOCAL_SETUP:@@ -57,12 +71,26 @@ def ensure_bucket() -> None:"DATAWAREHOUSE_LOCAL_ACCESS_SECRET, DATAWAREHOUSE_LOCAL_BUCKET_REGION")- ensure_bucket_exists(- settings.BUCKET_URL,- settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,- settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,- settings.OBJECT_STORAGE_ENDPOINT,- )+ try:+ ensure_bucket_exists(+ settings.BUCKET_URL,+ settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,+ settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,+ settings.OBJECT_STORAGE_ENDPOINT,+ )+ except botocore.exceptions.ClientError as error:+ if not _is_forbidden(error):+ raise+ # ensure_bucket_exists already retried the refusal to let a still-registering object+ # store finish its credential bootstrap, so one that arrives here comes from the+ # credentials or the bucket policy and every later attempt gets the same answer.+ # NonRetryableException stops the activity retries and keeps a known configuration+ # failure out of error tracking.+ logger.warning("ensure_bucket_forbidden", bucket=settings.DATAWAREHOUSE_BUCKET)+ raise NonRetryableException(+ "Couldn't reach the data warehouse storage with the configured credentials. "+ "Contact support if this keeps happening."+ ) from errordef cleanup_folder(folder_path: str) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_common.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_common.pyindex 6d17a7b7c70f..7d62f9813157 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_common.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/s3/test_common.py@@ -1,11 +1,19 @@from datetime import UTC, datetime, timedelta, timezone+import pytest+from unittest.mock import patch++from django.test import override_settings++from botocore.exceptions import ClientErrorfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import (+ ensure_bucket,get_base_folder,get_date_partition,)+from products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableExceptionclass TestGetDatePartition:@@ -36,3 +44,37 @@ class TestGetBaseFolder:folder = get_base_folder(team_id=42, schema_id="schema-a", run_uuid="run-b", date_partition="dt=2026-05-22")assert folder.endswith("/data_pipelines_extract/dt=2026-05-22/42/schema-a/run-b")+++class TestEnsureBucket:+ @parameterized.expand(+ [+ ("status_only_code", {"Error": {"Code": "403"}}),+ ("named_code", {"Error": {"Code": "AccessDenied"}}),+ (+ "status_in_metadata",+ {"Error": {"Code": "SignatureDoesNotMatch"}, "ResponseMetadata": {"HTTPStatusCode": 403}},+ ),+ ]+ )+ @override_settings(USE_LOCAL_SETUP=True)+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common.ensure_bucket_exists"+ )+ def test_refused_bucket_check_is_not_retried(self, _name: str, response: dict, mock_ensure) -> None:+ # ensure_bucket_exists has already retried this refusal, so the raw ClientError only made+ # the activity retry a configuration failure and report a fresh exception on every attempt.+ mock_ensure.side_effect = ClientError(response, "HeadBucket") # type: ignore[arg-type]++ with pytest.raises(NonRetryableException):+ ensure_bucket()++ @override_settings(USE_LOCAL_SETUP=True)+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common.ensure_bucket_exists"+ )+ def test_other_client_errors_stay_retryable(self, mock_ensure) -> None:+ mock_ensure.side_effect = ClientError({"Error": {"Code": "500"}}, "HeadBucket")++ with pytest.raises(ClientError):+ ensure_bucket()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 6783680408a4..1f43f7ae2fe8 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@@ -6,6 +6,7 @@ import pytestfrom unittest.mock import MagicMock, patchimport pyarrow as pa+from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer import (S3BatchWriter,@@ -80,43 +81,32 @@ class TestBuildSchemaDict:class TestSchemaAccumulation:- @patch(- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer._write_parquet_to_s3"+ @parameterized.expand(+ [+ ("int_then_double", pa.array([1, 2], type=pa.int64()), pa.array([1.5], type=pa.float64()), pa.float64()),+ ("int_then_string", pa.array([1], type=pa.int64()), pa.array(["2"], type=pa.string()), pa.string()),+ ("double_then_string", pa.array([1.5], type=pa.float64()), pa.array(["2"], type=pa.string()), pa.string()),+ ("string_then_double", pa.array(["2"], type=pa.string()), pa.array([1.5], type=pa.float64()), pa.string()),+ ])- @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.ensure_bucket")- @patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.get_s3_client")- def test_accumulated_schema_promotes_int_to_double_across_batches(- self, mock_get_s3_client, _mock_ensure_bucket, _mock_write- ) -> None:- # Two batches of the same column can infer different numeric types within one run (whole- # values -> int64, later fractional values -> double). Unifying them must widen to double- # rather than raising ArrowTypeError, which would crash the whole extraction.- mock_get_s3_client.return_value.info.return_value = {"Size": 1}-- job = MagicMock()- job.team_id = 1- job.created_at = datetime(2026, 8, 5, tzinfo=UTC)- job.workflow_run_id = "run-1"-- writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid="run-1")-- writer.write_batch(pa.table({"consumed_quantity": pa.array([1, 2], type=pa.int64())}), 0)- writer.write_batch(pa.table({"consumed_quantity": pa.array([1.5, 2.5], type=pa.float64())}), 1)-- schema = writer.get_schema()- assert schema is not None- assert schema.field("consumed_quantity").type == pa.float64()-@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer._write_parquet_to_s3")@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.ensure_bucket")@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.writer.get_s3_client")- def test_conflicting_column_types_across_batches_fall_back_to_text(- self, mock_get_s3_client, _mock_ensure_bucket, _mock_write+ def test_accumulated_schema_resolves_batches_that_disagree_on_a_column(+ self,+ _name: str,+ first: pa.Array,+ second: pa.Array,+ expected_type: pa.DataType,+ mock_get_s3_client,+ _mock_ensure_bucket,+ _mock_write,) -> None:- # A vendor sending the same id as int in one page and string in the next used to abort- # the whole table's sync with ArrowTypeError when the batch schemas were folded together.+ # Batches infer their own types, so a sparse column can land double in one batch and string+ # in the next. Folding those schemas together used to abort the whole table's sync with+ # ArrowTypeError: numeric widens where it can, and falls back to text where it can't.mock_get_s3_client.return_value.info.return_value = {"Size": 1}job = MagicMock()@@ -126,9 +116,9 @@ class TestSchemaAccumulation:writer = S3BatchWriter(MagicMock(), job, schema_id="schema-1", run_uuid="run-1")- writer.write_batch(pa.table({"owner_id": pa.array([1], type=pa.int64())}), 0)- writer.write_batch(pa.table({"owner_id": pa.array(["2"], type=pa.string())}), 1)+ writer.write_batch(pa.table({"consumed_quantity": first}), 0)+ writer.write_batch(pa.table({"consumed_quantity": second}), 1)schema = writer.get_schema()assert schema is not None- assert schema.field("owner_id").type == pa.string()+ assert schema.field("consumed_quantity").type == expected_type