: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): size the loader thread pools from its concurrency (#112671)
Tom Owerse30b19118f27
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.pyindex 76f8e2a283aa..5b10e90cdb15 100644--- a/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_sources_load.py@@ -1,4 +1,5 @@import asyncio+from functools import partialfrom django.core.management.base import BaseCommand, CommandError@@ -19,6 +20,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineprocess_batch,process_batches,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.thread_pools import (+ LoaderThreadPools,+ LoaderThreadPoolSizes,+ LoaderThreadPoolTooSmallError,+)from products.warehouse_sources_queue.backend.models import SourceBatchfrom products.warehouse_sources_queue.backend.sdk import HealthState, start_health_server@@ -69,8 +75,17 @@ def build_consumer_config(options: dict) -> ConsumerConfig:return ConsumerConfig(**kwargs)+def build_thread_pool_sizes(options: dict, config: ConsumerConfig) -> LoaderThreadPoolSizes:+ """Size the thread pools from the consumer's concurrency. Fail startup if an override is too small."""+ try:+ return LoaderThreadPoolSizes.for_concurrency(config.max_concurrency, options.get("nested_thread_pool_size"))+ except LoaderThreadPoolTooSmallError as e:+ raise CommandError(f"--nested-thread-pool-size: {e}") from e++async def _run_consumer(config: ConsumerConfig,+ pool_sizes: LoaderThreadPoolSizes,health_reporter,claim_sync_types: list[str] | None,claim_exclude_sync_types: list[str] | None,@@ -83,16 +98,22 @@ async def _run_consumer(set in `BatchConsumer._process_single` carry the keys `LogMessagesRenderer` needs (`workflow_type`,`workflow_id`, `workflow_run_id`, `team_id`, plus the event-level `log_source_id` override)."""- configure_logger(loop=asyncio.get_running_loop())- consumer = BatchConsumer(- config=config,- process_batch=process_batch,- process_batches=process_batches,- health_reporter=health_reporter,- claim_sync_types=claim_sync_types,- claim_exclude_sync_types=claim_exclude_sync_types,- )- await consumer.run()+ loop = asyncio.get_running_loop()+ pools = LoaderThreadPools(pool_sizes)+ pools.install(loop)+ try:+ configure_logger(loop=loop)+ consumer = BatchConsumer(+ config=config,+ process_batch=partial(process_batch, executor=pools.group_executor),+ process_batches=partial(process_batches, executor=pools.group_executor),+ health_reporter=health_reporter,+ claim_sync_types=claim_sync_types,+ claim_exclude_sync_types=claim_exclude_sync_types,+ )+ await consumer.run()+ finally:+ pools.shutdown()class Command(BaseCommand):@@ -105,6 +126,15 @@ class Command(BaseCommand):default=16,help="Maximum number of (team_id, schema_id) groups processed concurrently (default: 16)",)+ parser.add_argument(+ "--nested-thread-pool-size",+ type=int,+ default=None,+ help=(+ "Threads in the event loop's default executor, which runs the jobs that a load waits for. "+ "Default: sized from --max-concurrency. Startup fails if the value is below that size"+ ),+ )parser.add_argument("--poll-interval",type=float,@@ -246,6 +276,7 @@ class Command(BaseCommand):health_timeout = options["health_timeout"]config = build_consumer_config(options)+ pool_sizes = build_thread_pool_sizes(options, config)# Size deltalite's per-upsert memory slices against this loader's real concurrency (its own# max_concurrency), since it is a Kafka consumer, not a Temporal worker, so the governor's@@ -267,6 +298,8 @@ class Command(BaseCommand):logger.info("warehouse_sources_load_starting",max_concurrency=config.max_concurrency,+ group_thread_pool_size=pool_sizes.group_threads,+ nested_thread_pool_size=pool_sizes.nested_threads,poll_interval=config.poll_interval_seconds,poll_limit=config.poll_limit,max_attempts=config.max_attempts,@@ -285,4 +318,6 @@ class Command(BaseCommand):health_state = HealthState(timeout_seconds=health_timeout)start_health_server(port=health_port, health_state=health_state)- asyncio.run(_run_consumer(config, health_state.report_healthy, claim_sync_types, claim_exclude_sync_types))+ asyncio.run(+ _run_consumer(config, pool_sizes, health_state.report_healthy, claim_sync_types, claim_exclude_sync_types)+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.pyindex 90ddc14c1adf..2afcd8d17936 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py@@ -14,6 +14,7 @@ only needs to raise on failure.from __future__ import annotationsfrom collections.abc import Callable+from concurrent.futures import ThreadPoolExecutorfrom asgiref.sync import sync_to_async@@ -24,20 +25,35 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelinefrom products.warehouse_sources_queue.backend.core.jobs_db import PendingBatch-async def process_batch(batch: PendingBatch, verify_ownership: Callable[[], None] | None = None) -> None:- """Load a single batch into Delta Lake, reusing the existing processor."""+async def process_batch(+ batch: PendingBatch,+ verify_ownership: Callable[[], None] | None = None,+ *,+ executor: ThreadPoolExecutor | None = None,+) -> None:+ """Load a single batch into Delta Lake, reusing the existing processor.++ `executor` is the pool that holds the thread for the full load. The consumer passes a dedicated+ pool, because the load waits for nested jobs on the loop's default executor. A load that runs+ on the default executor can hold the thread that its own nested job needs. See `thread_pools`.+ """# thread_sensitive=False: the default single-thread executor would cap the pod's# real parallelism at 1; process_message is self-contained, so cross-thread is safe.# `latest_attempt` counts attempts already recorded, so the delivery starting now is the next# one — same arithmetic the consumer uses when it stamps the status row.- await sync_to_async(process_message, thread_sensitive=False)(+ await sync_to_async(process_message, thread_sensitive=False, executor=executor)(batch.to_export_signal(), verify_ownership=verify_ownership, attempt=batch.latest_attempt + 1)-async def process_batches(batches: list[PendingBatch], verify_ownership: Callable[[], None] | None = None) -> None:+async def process_batches(+ batches: list[PendingBatch],+ verify_ownership: Callable[[], None] | None = None,+ *,+ executor: ThreadPoolExecutor | None = None,+) -> None:"""Load consecutive batches of one run into Delta Lake as a single write."""- await sync_to_async(process_messages, thread_sensitive=False)(+ await sync_to_async(process_messages, thread_sensitive=False, executor=executor)([batch.to_export_signal() for batch in batches],verify_ownership=verify_ownership,attempt=max(batch.latest_attempt for batch in batches) + 1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_thread_pools.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_thread_pools.pynew file mode 100644index 000000000000..4b9ed59a5de2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_thread_pools.py@@ -0,0 +1,132 @@+import asyncio+import threading+from typing import Any++import pytest+from unittest.mock import patch++from asgiref.sync import async_to_sync+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import (+ process_batch,+ process_batches,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.thread_pools import (+ GROUP_THREAD_NAME_PREFIX,+ NESTED_THREAD_NAME_PREFIX,+ LoaderThreadPools,+ LoaderThreadPoolSizes,+ LoaderThreadPoolTooSmallError,+)+from products.warehouse_sources_queue.backend.core.jobs_db import PendingBatch++_LOAD_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load"+_TIMEOUT_SECONDS = 10.0+++def _make_batch(batch_index: int) -> PendingBatch:+ return PendingBatch(+ id=f"00000000-0000-0000-0000-{batch_index:012d}",+ team_id=1,+ schema_id=f"schema-{batch_index}",+ source_id="source-1",+ job_id="job-1",+ run_uuid="run-1",+ batch_index=batch_index,+ s3_path="s3://bucket/path",+ row_count=100,+ byte_size=1024,+ is_final_batch=False,+ total_batches=None,+ total_rows=None,+ sync_type="full_refresh",+ cumulative_row_count=0,+ resource_name="test_resource",+ is_resume=False,+ is_first_ever_sync=False,+ metadata={},+ latest_attempt=0,+ )+++class TestLoaderThreadPools:+ @parameterized.expand(+ [+ ("single", "process_message", 2),+ ("single_many_groups", "process_message", 16),+ ("coalesced_set", "process_messages", 2),+ ]+ )+ def test_full_concurrency_finishes_when_the_nested_pool_is_no_larger_than_the_group_count(+ self, _name: str, patched: str, groups: int+ ):+ # The nested pool has one thread for each group, the smallest size at which a shared pool+ # deadlocks: every group holds a thread before any group submits its nested job.+ all_groups_hold_a_thread = threading.Barrier(groups)+ threads: list[tuple[str, str]] = []++ async def nested() -> str:+ return await asyncio.to_thread(lambda: threading.current_thread().name)++ def load(*args: Any, **kwargs: Any) -> None:+ all_groups_hold_a_thread.wait(timeout=_TIMEOUT_SECONDS)+ threads.append((threading.current_thread().name, async_to_sync(nested)()))++ async def run() -> None:+ pools = LoaderThreadPools(+ LoaderThreadPoolSizes(max_concurrency=groups, group_threads=groups, nested_threads=groups)+ )+ pools.install(asyncio.get_running_loop())+ try:+ if patched == "process_message":+ loads = [process_batch(_make_batch(i), executor=pools.group_executor) for i in range(groups)]+ else:+ loads = [process_batches([_make_batch(i)], executor=pools.group_executor) for i in range(groups)]+ await asyncio.wait_for(asyncio.gather(*loads), timeout=_TIMEOUT_SECONDS)+ finally:+ # Cancelling the queued jobs releases the group threads if the pools deadlock, so a+ # failure ends the test instead of hanging the process at interpreter exit.+ all_groups_hold_a_thread.abort()+ pools.shutdown()++ with patch(f"{_LOAD_MODULE}.{patched}", side_effect=load):+ asyncio.run(run())++ assert len(threads) == groups+ assert all(group.startswith(GROUP_THREAD_NAME_PREFIX) for group, _ in threads)+ assert all(nested_thread.startswith(NESTED_THREAD_NAME_PREFIX) for _, nested_thread in threads)+++class TestLoaderThreadPoolSizes:+ @parameterized.expand(+ [+ ("default_at_8", 8, None, 40),+ ("default_at_16", 16, None, 72),+ ("override_at_the_minimum", 16, 72, 72),+ ("override_above_the_minimum", 16, 200, 200),+ ]+ )+ def test_sizes_follow_max_concurrency(+ self, _name: str, max_concurrency: int, override: int | None, expected_nested: int+ ):+ sizes = LoaderThreadPoolSizes.for_concurrency(max_concurrency, override)++ assert sizes.group_threads == max_concurrency+ assert sizes.nested_threads == expected_nested++ @parameterized.expand(+ [+ ("one_below_the_minimum", 16, 71),+ ("cpu_based_default_on_a_small_node", 16, 12),+ ("zero", 1, 0),+ ]+ )+ def test_a_nested_pool_below_the_need_is_rejected(self, _name: str, max_concurrency: int, override: int):+ with pytest.raises(LoaderThreadPoolTooSmallError, match=f"max_concurrency={max_concurrency}"):+ LoaderThreadPoolSizes.for_concurrency(max_concurrency, override)++ @parameterized.expand([(0,), (-1,)])+ def test_non_positive_concurrency_is_rejected(self, max_concurrency: int):+ with pytest.raises(ValueError, match="max_concurrency must be at least 1"):+ LoaderThreadPoolSizes.for_concurrency(max_concurrency)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/thread_pools.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/thread_pools.pynew file mode 100644index 000000000000..a64c04628812--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/thread_pools.py@@ -0,0 +1,80 @@+"""Thread pools for the load consumer process.++One group holds one thread for the full load. The load code calls `async_to_sync` from that+thread, and asgiref runs the coroutine on the consumer's event loop. Each `asyncio.to_thread` or+`sync_to_async(thread_sensitive=False)` call in that coroutine then submits a nested job to the+loop's default executor, and the group thread waits for it.++If the groups and their nested jobs share one pool, the pool deadlocks when the groups hold every+thread: each group waits for a nested job that has no thread to run on. The groups therefore get a+dedicated pool, and the default executor serves only the nested jobs. Both sizes come from the+consumer's concurrency, because the default size of `min(32, os.cpu_count() + 4)` changes with the+node type.+"""++from __future__ import annotations++import asyncio+from concurrent.futures import ThreadPoolExecutor++from posthog.dataclasses import frozen++# The number of nested jobs that one group can have on the default executor at the same time.+# A nested job can itself call `async_to_sync` and wait for a job of its own, so the default+# executor must have more than one thread for each group.+NESTED_JOBS_PER_GROUP = 4+# Threads for the default-executor work that does not belong to a group, such as the log producer.+NESTED_POOL_HEADROOM = 8++GROUP_THREAD_NAME_PREFIX = "warehouse-load-group"+NESTED_THREAD_NAME_PREFIX = "warehouse-load-nested"+++class LoaderThreadPoolTooSmallError(ValueError):+ pass+++@frozen+class LoaderThreadPoolSizes:+ max_concurrency: int+ group_threads: int+ nested_threads: int++ @staticmethod+ def required_nested_threads(max_concurrency: int) -> int:+ return max_concurrency * NESTED_JOBS_PER_GROUP + NESTED_POOL_HEADROOM++ @classmethod+ def for_concurrency(cls, max_concurrency: int, nested_threads: int | None = None) -> LoaderThreadPoolSizes:+ """Size both pools for `max_concurrency` groups. Raise if `nested_threads` is below the need."""+ if max_concurrency < 1:+ raise ValueError(f"max_concurrency must be at least 1, got {max_concurrency}")+ required = cls.required_nested_threads(max_concurrency)+ if nested_threads is None:+ nested_threads = required+ if nested_threads < required:+ raise LoaderThreadPoolTooSmallError(+ f"The nested thread pool has {nested_threads} threads, but max_concurrency={max_concurrency} "+ f"needs at least {required} ({NESTED_JOBS_PER_GROUP} for each group plus {NESTED_POOL_HEADROOM}). "+ "Increase the pool or decrease max_concurrency."+ )+ return cls(max_concurrency=max_concurrency, group_threads=max_concurrency, nested_threads=nested_threads)+++class LoaderThreadPools:+ def __init__(self, sizes: LoaderThreadPoolSizes) -> None:+ self.sizes = sizes+ self.group_executor = ThreadPoolExecutor(+ max_workers=sizes.group_threads, thread_name_prefix=GROUP_THREAD_NAME_PREFIX+ )+ self.nested_executor = ThreadPoolExecutor(+ max_workers=sizes.nested_threads, thread_name_prefix=NESTED_THREAD_NAME_PREFIX+ )++ def install(self, loop: asyncio.AbstractEventLoop) -> None:+ """Make the nested pool the default executor of `loop`."""+ loop.set_default_executor(self.nested_executor)++ def shutdown(self) -> None:+ self.group_executor.shutdown(wait=False, cancel_futures=True)+ self.nested_executor.shutdown(wait=False, cancel_futures=True)diff --git a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.pyindex b75d26a7f5d9..c1d7f880f5d0 100644--- a/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py+++ b/products/warehouse_sources/backend/tests/management/test_run_warehouse_sources_load.py@@ -7,6 +7,7 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.management.commands.run_warehouse_sources_load import (Command,build_consumer_config,+ build_thread_pool_sizes,parse_sync_types,)@@ -59,6 +60,30 @@ class TestBuildConsumerConfig:assert config.lease_ttl_seconds == 900+class TestBuildThreadPoolSizes:+ @parameterized.expand(+ [+ ([], 16, 72),+ (["--max-concurrency", "8"], 8, 40),+ (["--max-concurrency", "8", "--nested-thread-pool-size", "64"], 8, 64),+ ]+ )+ def test_pool_sizes_follow_the_flags(self, argv: list[str], expected_group: int, expected_nested: int):+ options = _parse_options(argv)++ sizes = build_thread_pool_sizes(options, build_consumer_config(options))++ assert (sizes.group_threads, sizes.nested_threads) == (expected_group, expected_nested)++ def test_undersized_nested_pool_fails_startup(self):+ # A pool below the need can deadlock the loader with no error and no log, so the pod+ # must crash at startup instead.+ options = _parse_options(["--max-concurrency", "16", "--nested-thread-pool-size", "12"])++ with pytest.raises(CommandError, match="--nested-thread-pool-size"):+ build_thread_pool_sizes(options, build_consumer_config(options))++class TestParseSyncTypes:@parameterized.expand([