: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): close the s3 client used to size a synced table (#79800)
Tom Owers11f5cf4d02fc
diff --git a/products/data_warehouse/backend/s3.py b/products/data_warehouse/backend/s3.pyindex 74cebe389f42..cfee075e99b9 100644--- a/products/data_warehouse/backend/s3.py+++ b/products/data_warehouse/backend/s3.py@@ -12,7 +12,7 @@ import botocore.exceptionsfrom products.data_warehouse.backend.s3_proxy import boto_proxy_config_kwargs-def get_s3_client(*, endpoint_url: Optional[str] = None):+def get_s3_client(*, endpoint_url: Optional[str] = None, skip_instance_cache: bool = False):# Defaults for localhost dev and test suitesif settings.USE_LOCAL_SETUP:return s3fs.S3FileSystem(@@ -29,8 +29,18 @@ def get_s3_client(*, endpoint_url: Optional[str] = None):# why a caller-supplied endpoint_url keeps its traffic on it. endpoint_url is only forwarded when# set: fsspec's instance cache keys on the literal kwargs, so passing endpoint_url=None explicitly# would split the shared cached client into a second instance.+ #+ # fsspec's instance cache also keys on the calling thread id, so callers invoked from a thread+ # pool (e.g. Temporal's sync-activity executor) get one cached, never-evicted S3FileSystem per+ # thread instead of the single shared instance the caching comment above assumes. skip_instance_cache+ # opts a caller out of that cache entirely for one-off calls where a leaked-forever cache entry+ # (and the open sockets/file handles it holds) isn't worth the connection-reuse it'd otherwise buy.extra = {"endpoint_url": endpoint_url} if endpoint_url is not None else {}- return s3fs.S3FileSystem(config_kwargs=boto_proxy_config_kwargs(endpoint_url=endpoint_url), **extra)+ return s3fs.S3FileSystem(+ config_kwargs=boto_proxy_config_kwargs(endpoint_url=endpoint_url),+ skip_instance_cache=skip_instance_cache,+ **extra,+ )@contextlib.asynccontextmanager@@ -87,15 +97,21 @@ async def aget_s3_client(*, fresh_instance: bool = False, endpoint_url: Optionaldef get_size_of_folder(path: str) -> float:- s3 = get_s3_client()+ # skip_instance_cache: this runs from Temporal's sync-activity thread pool, so the shared+ # fsspec cache (keyed by thread id, see get_s3_client) would otherwise leak one S3FileSystem+ # per calling thread forever. A one-off client, closed below, avoids that.+ s3 = get_s3_client(skip_instance_cache=True)- files = s3.find(path, detail=True)- file_values = files.values() if isinstance(files, dict) else files-- total_bytes = sum(f["Size"] for f in file_values if f["type"] != "directory")- total_mib = total_bytes / (1024 * 1024)+ try:+ files = s3.find(path, detail=True)+ file_values = files.values() if isinstance(files, dict) else files- return total_mib+ total_bytes = sum(f["Size"] for f in file_values if f["type"] != "directory")+ return total_bytes / (1024 * 1024)+ finally:+ with contextlib.suppress(Exception):+ if s3._s3 is not None:+ s3fs.S3FileSystem.close_session(s3.loop, s3._s3creator)def ensure_bucket_exists(s3_url: str, s3_key: str, s3_secret: str, s3_endpoint: Optional[str] = None) -> None:diff --git a/products/data_warehouse/backend/tests/test_s3.py b/products/data_warehouse/backend/tests/test_s3.pyindex 6d2dedda6494..a1c61dc85025 100644--- a/products/data_warehouse/backend/tests/test_s3.py+++ b/products/data_warehouse/backend/tests/test_s3.py@@ -4,7 +4,9 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom django.test import SimpleTestCase, override_settings-from products.data_warehouse.backend.s3 import aget_s3_client+from parameterized import parameterized++from products.data_warehouse.backend.s3 import aget_s3_client, get_size_of_folderclass TestAgetS3Client(SimpleTestCase):@@ -29,3 +31,44 @@ class TestAgetS3Client(SimpleTestCase):fake_s3._s3creator.__aexit__.assert_awaited_once_with(None, None, None)fake_s3._s3.close.assert_not_awaited()+++class TestGetSizeOfFolder(SimpleTestCase):+ def _mock_s3(self) -> MagicMock:+ s3 = MagicMock()+ s3.find.return_value = {+ "bucket/path/a.parquet": {"Size": 2 * 1024 * 1024, "type": "file"},+ "bucket/path/": {"Size": 0, "type": "directory"},+ }+ s3._s3 = MagicMock()+ return s3++ @patch("products.data_warehouse.backend.s3.s3fs.S3FileSystem.close_session")+ @patch("products.data_warehouse.backend.s3.get_s3_client")+ def test_requests_an_uncached_client_and_computes_size(self, mock_get_s3_client, mock_close_session):+ # This runs from Temporal's sync-activity thread pool. A shared (thread-keyed) client+ # would leak one S3FileSystem per calling thread forever; skip_instance_cache=True is+ # what avoids that.+ mock_get_s3_client.return_value = self._mock_s3()++ total_mib = get_size_of_folder("s3://bucket/path")++ mock_get_s3_client.assert_called_once_with(skip_instance_cache=True)+ assert total_mib == 2.0++ @parameterized.expand([("listing_succeeds", None), ("listing_raises", OSError("[Errno 24] Too many open files"))])+ @patch("products.data_warehouse.backend.s3.s3fs.S3FileSystem.close_session")+ @patch("products.data_warehouse.backend.s3.get_s3_client")+ def test_closes_the_session_regardless_of_outcome(self, _name, error, mock_get_s3_client, mock_close_session):+ s3 = self._mock_s3()+ if error is not None:+ s3.find.side_effect = error+ mock_get_s3_client.return_value = s3++ if error is not None:+ with self.assertRaises(OSError):+ get_size_of_folder("s3://bucket/path")+ else:+ get_size_of_folder("s3://bucket/path")++ mock_close_session.assert_called_once_with(s3.loop, s3._s3creator)