: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 an ambiguous HeadBucket 403 in the local bucket check (#88878)
Tom Owers5982cd4bdcf9
diff --git a/products/data_warehouse/backend/s3.py b/products/data_warehouse/backend/s3.pyindex 257b4b7d1e2b..622b20563156 100644--- a/products/data_warehouse/backend/s3.py+++ b/products/data_warehouse/backend/s3.py@@ -1,3 +1,4 @@+import timeimport contextlibfrom typing import Optionalfrom urllib.parse import urlparse@@ -114,6 +115,14 @@ def get_size_of_folder(path: str) -> float:s3fs.S3FileSystem.close_session(s3.loop, s3._s3creator)+# HeadBucket returns no body on either success or failure, so a 403 from it carries only the HTTP+# status as its "Code" — it can't be told apart from a still-registering local object store (e.g.+# SeaweedFS's credential bootstrap loop, see docker-compose.base.yml) by message here, same ambiguity+# `_is_retryable_purge_error` documents for the sibling HeadObject case. Retry the bounded budget below+# to let that race self-heal; a persistent misconfiguration still raises once it's exhausted.+_HEAD_BUCKET_MAX_ATTEMPTS = 4++def ensure_bucket_exists(s3_url: str, s3_key: str, s3_secret: str, s3_endpoint: Optional[str] = None) -> None:try:s3_client = boto3.client(@@ -136,26 +145,36 @@ def ensure_bucket_exists(s3_url: str, s3_key: str, s3_secret: str, s3_endpoint:bucket_name = parsed.netloc- try:- s3_client.head_bucket(Bucket=bucket_name)- except botocore.exceptions.ClientError as e:- error = e.response.get("Error")- if not error:- raise-- error_code = error.get("Code")- if not error_code:- raise-- if int(error_code) == 404:- try:- s3_client.create_bucket(Bucket=bucket_name)- except botocore.exceptions.ClientError as create_error:- # Concurrent callers can both see the 404 above before either creates the bucket; the- # loser's create_bucket then reports it already owns the bucket the winner just made.- # That's the intended end state, not a failure.- create_error_code = create_error.response.get("Error", {}).get("Code")- if create_error_code != "BucketAlreadyOwnedByYou":- raise- else:- raise+ attempt = 0+ while True:+ try:+ s3_client.head_bucket(Bucket=bucket_name)+ return+ except botocore.exceptions.ClientError as e:+ error = e.response.get("Error")+ if not error:+ raise++ error_code = error.get("Code")+ if not error_code:+ raise++ if int(error_code) == 404:+ try:+ s3_client.create_bucket(Bucket=bucket_name)+ except botocore.exceptions.ClientError as create_error:+ # Concurrent callers can both see the 404 above before either creates the bucket;+ # the loser's create_bucket then reports it already owns the bucket the winner just+ # made. That's the intended end state, not a failure.+ create_error_code = create_error.response.get("Error", {}).get("Code")+ if create_error_code != "BucketAlreadyOwnedByYou":+ raise+ return++ if int(error_code) != 403:+ raise++ attempt += 1+ if attempt >= _HEAD_BUCKET_MAX_ATTEMPTS:+ raise+ time.sleep(2**attempt)diff --git a/products/data_warehouse/backend/tests/test_s3.py b/products/data_warehouse/backend/tests/test_s3.pyindex 88be67ce0fc4..7997bcbf6b73 100644--- a/products/data_warehouse/backend/tests/test_s3.py+++ b/products/data_warehouse/backend/tests/test_s3.py@@ -137,8 +137,9 @@ class TestEnsureBucketExists(SimpleTestCase):with self.assertRaises(ValueError):ensure_bucket_exists("s3://my-bucket", "key", "secret")+ @patch("products.data_warehouse.backend.s3.time.sleep")@patch("products.data_warehouse.backend.s3.boto3.client")- def test_reraises_non_404_head_bucket_errors(self, mock_boto3_client) -> None:+ def test_reraises_non_404_head_bucket_errors(self, mock_boto3_client, mock_sleep) -> None:s3_client = MagicMock()s3_client.head_bucket.side_effect = _client_error("403")mock_boto3_client.return_value = s3_client@@ -146,4 +147,22 @@ class TestEnsureBucketExists(SimpleTestCase):with self.assertRaises(ClientError):ensure_bucket_exists("s3://my-bucket", "key", "secret")+ # A persistent 403 retries (it's indistinguishable from a transient one, see+ # test_retries_head_bucket_403_then_succeeds) but still gives up and raises.+ assert s3_client.head_bucket.call_count > 1+ s3_client.create_bucket.assert_not_called()++ @patch("products.data_warehouse.backend.s3.time.sleep")+ @patch("products.data_warehouse.backend.s3.boto3.client")+ def test_retries_head_bucket_403_then_succeeds(self, mock_boto3_client, mock_sleep) -> None:+ # HeadBucket carries no body, so a 403 from it can't be told apart from a still-registering+ # local object store (e.g. SeaweedFS's credential bootstrap loop) by message alone. That+ # transient race must self-heal on retry instead of surfacing as a hard failure.+ s3_client = MagicMock()+ s3_client.head_bucket.side_effect = [_client_error("403"), _client_error("403"), None]+ mock_boto3_client.return_value = s3_client++ ensure_bucket_exists("s3://my-bucket", "key", "secret")++ assert s3_client.head_bucket.call_count == 3s3_client.create_bucket.assert_not_called()