Skip to content

: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.

fix(data-warehouse): size the warehouse worker thread pools from its concurrency (#112956)

Tom Owers278cf019cec7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
index c965028df362..4949f1766478 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
@@ -20,6 +20,7 @@ import json
import uuid
import dataclasses
from collections.abc import Callable, Iterable
+from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, date, datetime, timedelta
from decimal import Decimal, localcontext
from typing import Any
@@ -694,9 +695,15 @@ async def compute_table_statistics_activity(inputs: ComputeTableStatisticsInputs
"""Activity wrapper. Heartbeats and runs the (sync) computation off the event loop."""
async with Heartbeater():
try:
- return await database_sync_to_async(compute_table_statistics_sync, thread_sensitive=False)(
- inputs.team_id, inputs.schema_id
- )
+ # The sync computation bridges back to async while opening the Delta table. Its own
+ # executor keeps the outer call from occupying the pool needed by that nested work.
+ executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="warehouse-table-statistics")
+ try:
+ return await database_sync_to_async(
+ compute_table_statistics_sync, thread_sensitive=False, executor=executor
+ )(inputs.team_id, inputs.schema_id)
+ finally:
+ executor.shutdown(wait=False, cancel_futures=True)
except Exception as e:
# get_delta_table already re-raises known-transient object-store blips as
# NonReportableError (see DeltaTableRef._capture_unless_transient) and intentionally
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index 8777fee827a6..650b81993aee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -4,6 +4,7 @@ import asyncio
import datetime as dt
import functools
import dataclasses
+from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, Any, NoReturn, Optional
from django.conf import settings
@@ -669,19 +670,25 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
resumable_source_manager: ResumableSourceManager | None = None
try:
- if isinstance(new_source, ResumableSource):
- resumable_source_manager = new_source.get_resumable_source_manager(source_inputs)
- source_response = await database_sync_to_async_pool(new_source.source_for_pipeline)(
- config, resumable_source_manager, source_inputs
- )
- elif isinstance(new_source, SimpleSource):
- source_response = await database_sync_to_async_pool(new_source.source_for_pipeline)(
- config, source_inputs
- )
- else:
- raise TypeError(
- f"{new_source.__class__.__name__} does not implement either SimpleSource or ResumableSource"
- )
+ # Some source setup functions bridge back to async code. Keep their outer blocking
+ # call off the shared default executor so that nested work cannot deadlock behind it.
+ executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="warehouse-source-setup")
+ try:
+ if isinstance(new_source, ResumableSource):
+ resumable_source_manager = new_source.get_resumable_source_manager(source_inputs)
+ source_response = await database_sync_to_async_pool(
+ new_source.source_for_pipeline, executor=executor
+ )(config, resumable_source_manager, source_inputs)
+ elif isinstance(new_source, SimpleSource):
+ source_response = await database_sync_to_async_pool(
+ new_source.source_for_pipeline, executor=executor
+ )(config, source_inputs)
+ else:
+ raise TypeError(
+ f"{new_source.__class__.__name__} does not implement either SimpleSource or ResumableSource"
+ )
+ finally:
+ executor.shutdown(wait=False, cancel_futures=True)
except SourceExtractionNotImplementedError as e:
# Web refuses to create a source whose implementation it does not have, so the
# stub is only reachable while this worker still runs the build from before the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
index ceb36530f093..8fa7b9981c4f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
@@ -1,6 +1,7 @@
import json
import uuid
import datetime as dt
+import threading
from decimal import Decimal
from typing import Any
@@ -956,6 +957,19 @@ class TestComputeTableStatisticsSync:
@pytest.mark.django_db(transaction=True)
class TestComputeTableStatisticsActivity:
+ async def test_activity_uses_a_dedicated_executor(self) -> None:
+ thread_names: list[str] = []
+
+ def record_thread(*_args) -> dict[str, Any]:
+ thread_names.append(threading.current_thread().name)
+ return {"status": "done"}
+
+ with patch.object(comp, "compute_table_statistics_sync", side_effect=record_thread):
+ inputs = ComputeTableStatisticsInputs(team_id=1, schema_id=uuid.uuid4())
+ await ActivityEnvironment().run(compute_table_statistics_activity, inputs)
+
+ assert thread_names[0].startswith("warehouse-table-statistics")
+
async def test_activity_returns_sync_result(self) -> None:
with patch.object(
comp, "compute_table_statistics_sync", return_value={"status": "done", "columns": 1, "row_count": 5}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 3a6bb376da75..6fa1bd6d1646 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -1,4 +1,7 @@
import uuid
+import asyncio
+import functools
+import threading
import contextlib
import dataclasses
from datetime import UTC, datetime, timedelta
@@ -74,11 +77,13 @@ class _FakeAsyncCM:
pass
-def _passthrough(fn):
- """Stand-in for database_sync_to_async_pool that just calls the wrapped fn."""
+def _passthrough(fn, *, executor=None):
+ """Stand-in for database_sync_to_async_pool that honors an explicitly selected executor."""
async def _inner(*args, **kwargs):
- return fn(*args, **kwargs)
+ if executor is None:
+ return fn(*args, **kwargs)
+ return await asyncio.get_running_loop().run_in_executor(executor, functools.partial(fn, *args, **kwargs))
return _inner
@@ -977,6 +982,20 @@ def _inputs_no_reset() -> ImportDataActivityInputs:
)
+async def test_source_setup_uses_a_dedicated_executor():
+ thread_names: list[str] = []
+ source = mock.MagicMock(spec=SimpleSource)
+ source.parse_config.return_value = {}
+ source.source_for_pipeline.side_effect = lambda *_args: thread_names.append(threading.current_thread().name)
+ schema = _incremental_schema(is_incremental=False, lookback_seconds=None)
+
+ with _patched_activity_reaching_run(source, schema):
+ await import_data_activity_sync(_inputs_no_reset())
+
+ assert thread_names[0].startswith("warehouse-source-setup")
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"is_incremental,expected_last_value,expected_before_lookback",