: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
revert(ws): replace gather-barrier with in-flight task registry and parallel batch loading (#65721)
estefania25e74862a7d4
diff --git a/posthog/management/commands/run_warehouse_sources_load.py b/posthog/management/commands/run_warehouse_sources_load.pyindex f5cd6bf0e528..8e64738f271a 100644--- a/posthog/management/commands/run_warehouse_sources_load.py+++ b/posthog/management/commands/run_warehouse_sources_load.py@@ -1,5 +1,4 @@import asyncio-from concurrent.futures import ThreadPoolExecutorfrom django.core.management.base import BaseCommand@@ -22,14 +21,8 @@ async def _run_consumer(config: ConsumerConfig, health_reporter) -> None:`merge_temporal_context` no-ops outside an actual workflow/activity, and the per-batch contextvarsset 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."""- loop = asyncio.get_running_loop()- loop.set_default_executor(ThreadPoolExecutor(max_workers=config.max_concurrency))- configure_logger(loop=loop)+ configure_logger(loop=asyncio.get_running_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.pyindex 17a447a7f5db..b40fbcf51a83 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -87,7 +87,6 @@ class BatchConsumerAdapter(Protocol):*,limit: int,retry_backoff_base_seconds: int,- exclude_keys: set[tuple[int, str]] | None = None,) -> list[PendingBatch]: ...async def unlock(@@ -183,9 +182,6 @@ 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(@@ -241,14 +237,6 @@ 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()@@ -256,7 +244,6 @@ 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.@@ -277,50 +264,18 @@ class BatchConsumer:self._event("poll_returned"),batch_count=len(batches),group_count=len(groups),- in_flight=len(self._in_flight),)- 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]}",+ self._metrics.active_groups.inc(len(groups))+ try:+ await asyncio.gather(+ *[self._process_group(key, group_batches) for key, group_batches in groups.items()])- self._in_flight[key] = task+ finally:+ self._metrics.active_groups.dec(len(groups))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.pyindex f1cd0a9042b6..26cc670787f1 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -103,7 +103,6 @@ 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:@@ -116,7 +115,6 @@ 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.pyindex b16a544942cf..10f28fbec683 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,7 +81,6 @@ 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.@@ -95,10 +94,6 @@ class DuckgresBatchQueue:filter, for tests/dev). The sink must never claim batches for orgs withouta 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 runstart time) of the same (team_id, schema_id) still has unapplied,non-failed data batches. Without this, a newer run's batch-0@@ -107,26 +102,6 @@ class DuckgresBatchQueue:Liveness: older runs either complete, fail (max attempts), or aresuperseded 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"""@@ -140,7 +115,7 @@ class DuckgresBatchQueue:LEFT JOIN {DUCKGRES_STATUS_VIEW} dgs ON b.id = dgs.batch_idWHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'- AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s)){exclude_clause}+ AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))AND ds.job_state = 'succeeded'AND (dgs.batch_id IS NULL@@ -210,7 +185,7 @@ class DuckgresBatchQueue:)ORDER BY c.created_at ASC, c.batch_index ASC, c.is_final_batch ASC""",- params,+ {"limit": limit, "backoff": retry_backoff_base_seconds, "team_ids": team_ids},)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.pyindex 962bee128efd..71caca7e6d82 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -1,4 +1,3 @@-import threadingfrom collections.abc import Callablefrom typing import Any, Literal@@ -47,8 +46,6 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTablelogger = 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."""@@ -198,8 +195,7 @@ 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).- with _s3fs_cache_lock:- s3fs.S3FileSystem.clear_instance_cache()+ s3fs.S3FileSystem.clear_instance_cache()async def _run() -> None:job = await ExternalDataJob.objects.prefetch_related("schema", "schema__source", "schema__table").aget(@@ -354,8 +350,7 @@ 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).- with _s3fs_cache_lock:- s3fs.S3FileSystem.clear_instance_cache()+ s3fs.S3FileSystem.clear_instance_cache()try:team_id_str = str(export_signal.team_id)@@ -647,5 +642,3 @@ 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.pyindex eb5672942109..785567d1c50f 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,13 +54,11 @@ 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.pyindex 8d03957423f9..0c0289287716 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,7 +220,6 @@ 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.@@ -249,22 +248,6 @@ class BatchQueue:schema's other queued runs from consuming the ``LIMIT`` window ahead ofthe 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"""@@ -317,7 +300,6 @@ 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 ASCLIMIT %(limit)s)@@ -326,7 +308,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""",- params,+ {"limit": limit, "backoff": retry_backoff_base_seconds},)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.pyindex e2d27f44927f..3e0e571bd425 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_dbasync def process_batch(batch: PendingBatch) -> None:"""Load a single batch into Delta Lake, reusing the existing processor."""- await sync_to_async(process_message, thread_sensitive=False)(batch.to_export_signal())+ await sync_to_async(process_message)(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.pyindex d6702d33bbce..f80f44fb4f44 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,9 +1,8 @@import asyncio-import dataclassesfrom typing import Anyimport pytest-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, patchimport psycopgimport structlog@@ -593,66 +592,6 @@ 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.pyindex f63232932230..588079ed2ab0 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,36 +223,6 @@ 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.asyncioasync def test_in_flight_gating_clears_after_terminal_status(self, conn):# Once the executing batch is superseded by a terminal status, the schema's