: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): reuse the S3 filesystem in CDP and person-property sinks (#79816)
Tom Owers48e853bd951f
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 cec86b9927a8..8914de0685e0 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@@ -35,6 +35,7 @@ class CDPProducer:logger: FilteringBoundLogger_should_run_cache: bool | None_table_name_cache: str | None+ _fs_cache: pa_fs.S3FileSystem | Nonedef __init__(self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger) -> None:self.team_id = team_id@@ -43,8 +44,16 @@ class CDPProducer:self.logger = loggerself._should_run_cache = Noneself._table_name_cache = None+ self._fs_cache = Nonedef _get_fs(self) -> pa_fs.S3FileSystem:+ # Cached per instance: stage_chunk() calls this once per chunk, and a producer lives for+ # a whole sync (potentially thousands of chunks). A fresh S3FileSystem per call opens its+ # own AWS SDK client/connections that outlive the call, exhausting the process' file+ # descriptor limit over a long sync.+ if self._fs_cache is not None:+ return self._fs_cache+if settings.USE_LOCAL_SETUP:ensure_bucket_exists(f"s3://{self._get_path_prefix()}",@@ -53,13 +62,15 @@ class CDPProducer:settings.OBJECT_STORAGE_ENDPOINT,)- return pa_fs.S3FileSystem(+ self._fs_cache = pa_fs.S3FileSystem(access_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,secret_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,endpoint_override=settings.OBJECT_STORAGE_ENDPOINT,)+ else:+ self._fs_cache = pa_fs.S3FileSystem()- return pa_fs.S3FileSystem()+ return self._fs_cachedef _get_path_prefix(self) -> str:return f"{settings.DATAWAREHOUSE_BUCKET}/cdp_producer/{self.team_id}/{self.schema_id}/{self.job_id}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.pyindex 68248951ffda..f415fbceb46d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py@@ -56,8 +56,16 @@ class PersonPropertyRowSink:self._attempt_token = str(int(time.time()))self._projection: list[PersonPropertySourceProjection] | None = Noneself._projection_resolved = False+ self._fs_cache: pa_fs.S3FileSystem | None = Nonedef _get_fs(self) -> pa_fs.S3FileSystem:+ # Cached per instance: stage_chunk() calls this once per chunk, and a sink lives for a+ # whole sync (potentially thousands of chunks). A fresh S3FileSystem per call opens its+ # own AWS SDK client/connections that outlive the call, exhausting the process' file+ # descriptor limit over a long sync.+ if self._fs_cache is not None:+ return self._fs_cache+if settings.USE_LOCAL_SETUP:ensure_bucket_exists(f"s3://{self._get_path_prefix()}",@@ -65,13 +73,15 @@ class PersonPropertyRowSink:settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,settings.OBJECT_STORAGE_ENDPOINT,)- return pa_fs.S3FileSystem(+ self._fs_cache = pa_fs.S3FileSystem(access_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,secret_key=settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,endpoint_override=settings.OBJECT_STORAGE_ENDPOINT,)+ else:+ self._fs_cache = pa_fs.S3FileSystem()- return pa_fs.S3FileSystem()+ return self._fs_cachedef _get_schema_prefix(self) -> str:return f"{settings.DATAWAREHOUSE_BUCKET}/person_property_sync/{self.team_id}/{self.schema_id}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.pyindex e9fd6e8e91dc..d001daeb5fd0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py@@ -3,7 +3,10 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.conf import settings+import pyarrow as pa+from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import (PersonPropertySourceProjection,@@ -177,6 +180,26 @@ async def test_stage_chunk_filenames_are_unique_per_attempt():assert len(set(paths)) == 2[email protected]([("local_setup", True), ("non_local_setup", False)])+def test_get_fs_reuses_the_same_filesystem_across_calls(_name, use_local_setup):+ # stage_chunk() calls _get_fs() once per chunk over a whole sync (potentially thousands of+ # chunks); constructing a fresh S3FileSystem per call leaks its underlying connections/file+ # descriptors until the process runs out of them. Both branches build their own S3FileSystem,+ # so both must cache it.+ sink = _sink()++ with (+ patch.object(settings, "USE_LOCAL_SETUP", use_local_setup),+ patch(f"{_MODULE}.pa_fs.S3FileSystem") as mock_s3_filesystem,+ patch(f"{_MODULE}.ensure_bucket_exists"),+ ):+ first = sink._get_fs()+ second = sink._get_fs()++ mock_s3_filesystem.assert_called_once()+ assert first is second++@pytest.mark.asyncioasync def test_clear_tolerates_missing_prefixes():# First sync of a schema has nothing staged anywhere; clearing must not fail the sync.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 3e0cd7a614d7..ca1bf3afd688 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@@ -7,11 +7,13 @@ import pytestfrom unittest import mockfrom unittest.mock import MagicMock, patch+from django.conf import settingsfrom django.db.utils import OperationalError as DjangoOperationalErrorimport pyarrow as paimport pyarrow.parquet as pqfrom asgiref.sync import sync_to_async+from parameterized import parameterizedfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -891,6 +893,30 @@ def _make_producer(job_id: str) -> CDPProducer:return CDPProducer(team_id=1, schema_id="schema_1", job_id=job_id, logger=mock.AsyncMock())[email protected]([("local_setup", True), ("non_local_setup", False)])+def test_get_fs_reuses_the_same_filesystem_across_calls(_name, use_local_setup):+ # stage_chunk() calls _get_fs() once per chunk over a whole sync (potentially thousands of+ # chunks); constructing a fresh S3FileSystem per call leaks its underlying connections/file+ # descriptors until the process runs out of them. Both branches build their own S3FileSystem,+ # so both must cache it.+ producer = _make_producer("job_1")++ with (+ patch.object(settings, "USE_LOCAL_SETUP", use_local_setup),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.pa_fs.S3FileSystem"+ ) as mock_s3_filesystem,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.ensure_bucket_exists"+ ),+ ):+ first = producer._get_fs()+ second = producer._get_fs()++ mock_s3_filesystem.assert_called_once()+ assert first is second++def test_build_event_id_is_a_valid_uuid():event_id = _make_producer("job_1")._build_event_id({"id": 1, "name": "Alice"})assert str(uuid.UUID(event_id)) == event_id