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(warehouse): replace gather-barrier with in-flight task registry and parallel batch loading (#65181)

estefania8c1fdaf79bee
diff --git a/posthog/management/commands/run_warehouse_sources_load.py b/posthog/management/commands/run_warehouse_sources_load.py
index 8e64738f271a..f5cd6bf0e528 100644
--- a/posthog/management/commands/run_warehouse_sources_load.py
+++ b/posthog/management/commands/run_warehouse_sources_load.py
@@ -1,4 +1,5 @@
import asyncio
+from concurrent.futures import ThreadPoolExecutor
from django.core.management.base import BaseCommand
@@ -21,8 +22,14 @@ async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:
`merge_temporal_context` no-ops outside an actual workflow/activity, and the per-batch contextvars
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).
+
+ `sync_to_async(thread_sensitive=False)` dispatches batch loading to the default executor.
+ Setting it to a `ThreadPoolExecutor` sized to `max_concurrency` ensures the thread pool
+ matches the async concurrency limit, preventing unbounded thread creation.
"""
- configure_logger(loop=asyncio.get_running_loop())
+ loop = asyncio.get_running_loop()
+ loop.set_default_executor(ThreadPoolExecutor(max_workers=config.max_concurrency))
+ configure_logger(loop=loop)
consumer = BatchConsumer(config=config, process_batch=process_batch, health_reporter=health_reporter)
await consumer.run()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
index b40fbcf51a83..17a447a7f5db 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
@@ -87,6 +87,7 @@ class BatchConsumerAdapter(Protocol):
*,
limit: int,
retry_backoff_base_seconds: int,
+ exclude_keys: set[tuple[int, str]] | None = None,
) -> list[PendingBatch]: ...
async def unlock(
@@ -182,6 +183,9 @@ class BatchConsumer:
# batch_id -> monotonic start, for the stuck-batch watchdog.
self._inflight_started: dict[str, float] = {}
self._last_stuck_log_monotonic = 0.0
+ # In-flight group tasks keyed by (team_id, schema_id). Prevents re-polling
+ # the same key (session advisory locks are re-entrant).
+ self._in_flight: dict[tuple[int, str], asyncio.Task[None]] = {}
async def _connect(self) -> psycopg.AsyncConnection[Any]:
return await psycopg.AsyncConnection.connect(
@@ -237,6 +241,14 @@ class BatchConsumer:
while not self._shutdown.is_set():
self._report_health()
+ self._reap_finished_tasks()
+
+ if len(self._in_flight) >= self._config.max_concurrency:
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
+ continue
+
+ exclude_keys = set(self._in_flight.keys())
+
poll_start = time.monotonic()
try:
conn = await self._ensure_main_conn()
@@ -244,6 +256,7 @@ class BatchConsumer:
conn,
limit=self._config.poll_limit,
retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
+ exclude_keys=exclude_keys,
)
except psycopg.OperationalError as e:
# Queue DB unreachable — keep the pod alive; the next iteration reconnects.
@@ -264,18 +277,50 @@ class BatchConsumer:
self._event("poll_returned"),
batch_count=len(batches),
group_count=len(groups),
+ in_flight=len(self._in_flight),
)
- self._metrics.active_groups.inc(len(groups))
- try:
- await asyncio.gather(
- *[self._process_group(key, group_batches) for key, group_batches in groups.items()]
+ for key, group_batches in groups.items():
+ task = asyncio.create_task(
+ self._process_group_tracked(key, group_batches),
+ name=f"group:{key[0]}:{key[1]}",
)
- finally:
- self._metrics.active_groups.dec(len(groups))
+ self._in_flight[key] = task
finally:
+ if self._in_flight:
+ await asyncio.gather(*self._in_flight.values(), return_exceptions=True)
+ self._in_flight.clear()
await self._close()
+ def _reap_finished_tasks(self) -> None:
+ """Remove completed tasks from the in-flight registry."""
+ done = [k for k, t in self._in_flight.items() if t.done()]
+ for k in done:
+ task = self._in_flight.pop(k)
+ if task.cancelled():
+ logger.error(
+ self._event("group_task_cancelled"),
+ team_id=k[0],
+ schema_id=k[1],
+ )
+ elif task.exception() is not None:
+ exc = task.exception()
+ logger.error(
+ self._event("group_task_failed"),
+ team_id=k[0],
+ schema_id=k[1],
+ error=str(exc),
+ )
+ capture_exception(exc)
+
+ async def _process_group_tracked(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
+ """Wrapper that updates the active-groups gauge and removes self from in-flight on completion."""
+ self._metrics.active_groups.inc()
+ try:
+ await self._process_group(key, batches)
+ finally:
+ self._metrics.active_groups.dec()
+
async def _process_group(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
team_id, schema_id = key
# Pin the connection that holds the advisory locks so status writes stay on the same session.
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
index 26cc670787f1..f1cd0a9042b6 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
@@ -103,6 +103,7 @@ class DuckgresBatchConsumerAdapter:
*,
limit: int,
retry_backoff_base_seconds: int,
+ exclude_keys: set[tuple[int, str]] | None = None,
) -> list[PendingBatch]:
team_ids = await self._enabled_team_ids()
if team_ids is not None and not team_ids:
@@ -115,6 +116,7 @@ class DuckgresBatchConsumerAdapter:
limit=limit,
retry_backoff_base_seconds=retry_backoff_base_seconds,
team_ids=team_ids,
+ exclude_keys=exclude_keys,
)
async def unlock(
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
index 10f28fbec683..b16a544942cf 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
@@ -81,6 +81,7 @@ class DuckgresBatchQueue:
limit: int = 50,
retry_backoff_base_seconds: int = 0,
team_ids: list[int] | None = None,
+ exclude_keys: set[tuple[int, str]] | None = None,
) -> list[PendingBatch]:
"""Fetch Duckgres-eligible batches whose Delta load has succeeded.
@@ -94,6 +95,10 @@ class DuckgresBatchQueue:
filter, for tests/dev). The sink must never claim batches for orgs without
a Duckgres deployment — they would burn retries and fail runs for nothing.
+ ``exclude_keys`` skips ``(team_id, schema_id)`` groups already in flight on
+ this pod, so a poll cannot re-claim batches for a group whose advisory lock
+ the engine is still holding.
+
Cross-run head-of-line: a batch is ineligible while an older run (by run
start time) of the same (team_id, schema_id) still has unapplied,
non-failed data batches. Without this, a newer run's batch-0
@@ -102,6 +107,26 @@ class DuckgresBatchQueue:
Liveness: older runs either complete, fail (max attempts), or are
superseded by ``supersede_replaced_runs`` — all three unblock the gate.
"""
+ exclude_clause = ""
+ params: dict[str, Any] = {
+ "limit": limit,
+ "backoff": retry_backoff_base_seconds,
+ "team_ids": team_ids,
+ }
+ if exclude_keys:
+ value_placeholders = ",".join(
+ f"(%(xk_t_{i})s::bigint, %(xk_s_{i})s::text)" for i in range(len(exclude_keys))
+ )
+ exclude_clause = f"""
+ AND NOT EXISTS (
+ SELECT 1
+ FROM (VALUES {value_placeholders}) AS excl(team_id, schema_id)
+ WHERE excl.team_id = b.team_id AND excl.schema_id = b.schema_id
+ )"""
+ for i, (t, s) in enumerate(exclude_keys):
+ params[f"xk_t_{i}"] = t
+ params[f"xk_s_{i}"] = s
+
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
f"""
@@ -115,7 +140,7 @@ class DuckgresBatchQueue:
LEFT JOIN {DUCKGRES_STATUS_VIEW} dgs ON b.id = dgs.batch_id
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
- AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))
+ AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s)){exclude_clause}
AND ds.job_state = 'succeeded'
AND (
dgs.batch_id IS NULL
@@ -185,7 +210,7 @@ class DuckgresBatchQueue:
)
ORDER BY c.created_at ASC, c.batch_index ASC, c.is_final_batch ASC
""",
- {"limit": limit, "backoff": retry_backoff_base_seconds, "team_ids": team_ids},
+ params,
)
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 71caca7e6d82..962bee128efd 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -1,3 +1,4 @@
+import threading
from collections.abc import Callable
from typing import Any, Literal
@@ -46,6 +47,8 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable
logger = structlog.get_logger(__name__)
+_s3fs_cache_lock = threading.Lock()
+
def _get_write_type(sync_type: SyncTypeLiteral) -> Literal["incremental", "full_refresh", "append"]:
"""Convert sync type to write type for DeltaTableHelper."""
@@ -195,7 +198,8 @@ def _run_post_load_for_already_processed_batch(export_signal: ExportSignalMessag
"""
# Clear cached S3FileSystem instances to avoid reusing sessions bound to a
# previously closed event loop (async_to_sync creates/destroys loops).
- s3fs.S3FileSystem.clear_instance_cache()
+ with _s3fs_cache_lock:
+ s3fs.S3FileSystem.clear_instance_cache()
async def _run() -> None:
job = await ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").aget(
@@ -350,7 +354,8 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
# Clear cached S3FileSystem instances to avoid reusing sessions bound to a
# previously closed event loop (async_to_sync creates/destroys loops).
- s3fs.S3FileSystem.clear_instance_cache()
+ with _s3fs_cache_lock:
+ s3fs.S3FileSystem.clear_instance_cache()
try:
team_id_str = str(export_signal.team_id)
@@ -642,3 +647,5 @@ def process_message(message: Any, progress_callback: Callable[[], None] | None =
},
)
raise
+ finally:
+ close_old_connections()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 785567d1c50f..eb5672942109 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -54,11 +54,13 @@ class DeltaBatchConsumerAdapter:
*,
limit: int,
retry_backoff_base_seconds: int,
+ exclude_keys: set[tuple[int, str]] | None = None,
) -> list[PendingBatch]:
return await BatchQueue.get_unprocessed_and_lock(
conn,
limit=limit,
retry_backoff_base_seconds=retry_backoff_base_seconds,
+ exclude_keys=exclude_keys,
)
async def unlock(
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index 0c0289287716..8d03957423f9 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -220,6 +220,7 @@ class BatchQueue:
*,
limit: int = 50,
retry_backoff_base_seconds: int = 0,
+ exclude_keys: set[tuple[int, str]] | None = None,
) -> list[PendingBatch]:
"""Fetch unprocessed batches whose (team_id, schema_id) advisory lock is acquirable.
@@ -248,6 +249,22 @@ class BatchQueue:
schema's other queued runs from consuming the ``LIMIT`` window ahead of
the advisory-lock filter and starving other schemas' claimable work.
"""
+ exclude_clause = ""
+ params: dict[str, Any] = {"limit": limit, "backoff": retry_backoff_base_seconds}
+ if exclude_keys:
+ value_placeholders = ",".join(
+ f"(%(xk_t_{i})s::bigint, %(xk_s_{i})s::text)" for i in range(len(exclude_keys))
+ )
+ exclude_clause = f"""
+ AND NOT EXISTS (
+ SELECT 1
+ FROM (VALUES {value_placeholders}) AS excl(team_id, schema_id)
+ WHERE excl.team_id = b.team_id AND excl.schema_id = b.schema_id
+ )"""
+ for i, (t, s) in enumerate(exclude_keys):
+ params[f"xk_t_{i}"] = t
+ params[f"xk_s_{i}"] = s
+
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
f"""
@@ -300,6 +317,7 @@ class BatchQueue:
AND b_busy.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
AND s_busy.job_state = 'executing'
)
+ {exclude_clause}
ORDER BY b.created_at ASC, b.batch_index ASC
LIMIT %(limit)s
)
@@ -308,7 +326,7 @@ class BatchQueue:
WHERE pg_try_advisory_lock({ADVISORY_LOCK_NAMESPACE}, hashtext(c.team_id::text || ':' || c.schema_id))
ORDER BY c.created_at ASC, c.batch_index ASC
""",
- {"limit": limit, "backoff": retry_backoff_base_seconds},
+ params,
)
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
index 3e0e571bd425..e2d27f44927f 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
@@ -21,4 +21,4 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db
async def process_batch(batch: PendingBatch) -> None:
"""Load a single batch into Delta Lake, reusing the existing processor."""
- await sync_to_async(process_message)(batch.to_export_signal())
+ await sync_to_async(process_message, thread_sensitive=False)(batch.to_export_signal())
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index f80f44fb4f44..d6702d33bbce 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -1,8 +1,9 @@
import asyncio
+import dataclasses
from typing import Any
import pytest
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import psycopg
import structlog
@@ -592,6 +593,66 @@ class TestConnectionRecovery:
assert mock_get_stale.call_args[0][0] is fresh
+class TestInFlightTaskRegistry:
+ @pytest.mark.asyncio
+ async def test_reap_removes_finished_tasks(self):
+ consumer = _make_consumer()
+
+ done_task = asyncio.create_task(asyncio.sleep(0))
+ await done_task
+ consumer._in_flight[(1, "s1")] = done_task
+
+ running_task = asyncio.create_task(asyncio.sleep(100))
+ consumer._in_flight[(2, "s2")] = running_task
+
+ consumer._reap_finished_tasks()
+
+ assert (1, "s1") not in consumer._in_flight
+ assert (2, "s2") in consumer._in_flight
+ running_task.cancel()
+
+ @pytest.mark.asyncio
+ async def test_reap_logs_failed_tasks(self):
+ consumer = _make_consumer()
+
+ async def fail():
+ raise RuntimeError("boom")
+
+ task = asyncio.create_task(fail())
+ try:
+ await task
+ except RuntimeError:
+ pass
+ consumer._in_flight[(1, "s1")] = task
+
+ consumer._reap_finished_tasks()
+
+ assert (1, "s1") not in consumer._in_flight
+
+ @pytest.mark.asyncio
+ async def test_process_group_tracked_increments_and_decrements_gauge(self):
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+
+ mock_gauge = MagicMock()
+ consumer._metrics = dataclasses.replace(consumer._metrics, active_groups=mock_gauge)
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ),
+ ):
+ await consumer._process_group_tracked((1, "schema-1"), [_make_batch()])
+
+ mock_gauge.inc.assert_called_once()
+ mock_gauge.dec.assert_called_once()
+
+
class TestGroupByKey:
def test_groups_by_team_and_schema(self):
batches = [
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
index 588079ed2ab0..f63232932230 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -223,6 +223,36 @@ class TestBatchQueueGetUnprocessed:
assert [b.schema_id for b in batches] == ["B"]
await BatchQueue.unlock_for_batches(conn, batches=batches)
+ @pytest.mark.asyncio
+ async def test_exclude_keys_filters_matching_schemas(self, conn):
+ await _insert_batch(conn, team_id=1, schema_id="s1", run_uuid="run-1", batch_index=0)
+ await _insert_batch(conn, team_id=2, schema_id="s2", run_uuid="run-2", batch_index=0)
+ await _insert_batch(conn, team_id=3, schema_id="s3", run_uuid="run-3", batch_index=0)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn, exclude_keys={(1, "s1"), (3, "s3")})
+
+ assert [b.schema_id for b in batches] == ["s2"]
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
+ @pytest.mark.asyncio
+ async def test_exclude_keys_empty_set_returns_all(self, conn):
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
+ await _insert_batch(conn, team_id=2, schema_id="s2", batch_index=0)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn, exclude_keys=set())
+
+ assert len(batches) == 2
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
+ @pytest.mark.asyncio
+ async def test_exclude_keys_none_returns_all(self, conn):
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn, exclude_keys=None)
+
+ assert len(batches) == 1
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
@pytest.mark.asyncio
async def test_in_flight_gating_clears_after_terminal_status(self, conn):
# Once the executing batch is superseded by a terminal status, the schema's