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.

chore(ws): use postgres as queue for warehouse sources load process (#56006)

estefaniac309be022c2b
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index d4042a93d96e..15f5372879bd 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -506,9 +506,9 @@ procs:
warehouse-sources-load:
shell: |-
bin/wait-for-docker && \
- python manage.py run_warehouse_sources_load --health-port 8090 --batch-size 100 --consumer-group warehouse-sources-load-dev
+ python manage.py run_warehouse_sources_load
autostart: false
- ready_pattern: 'health_server_started'
+ ready_pattern: 'batch_consumer_started'
groups:
layer: Tools
tech: Python
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c9eaef117385..4acf956d79ab 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3287,6 +3287,8 @@ importers:
specifier: 18.3.1
version: 18.3.1
+ products/warehouse_sources_queue: {}
+
products/web_analytics:
dependencies:
'@posthog/icons':
diff --git a/posthog/management/commands/run_warehouse_sources_load.py b/posthog/management/commands/run_warehouse_sources_load.py
index 538df149227a..7f4436eb92cf 100644
--- a/posthog/management/commands/run_warehouse_sources_load.py
+++ b/posthog/management/commands/run_warehouse_sources_load.py
@@ -1,52 +1,50 @@
+import asyncio
+
from django.core.management.base import BaseCommand
import structlog
-from posthog.kafka_client.topics import KAFKA_WAREHOUSE_SOURCES_JOBS, KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ
-from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka import KafkaConsumerService
-from posthog.temporal.data_imports.pipelines.pipeline_v3.load import (
- ConsumerConfig,
- HealthState,
- process_message,
- start_health_server,
-)
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+from posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState, start_health_server
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import BatchConsumer, ConsumerConfig
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.load import process_batch
logger = structlog.get_logger(__name__)
class Command(BaseCommand):
- help = "Run the warehouse sources load Kafka consumer service"
+ help = "Run the warehouse sources batch consumer"
def add_arguments(self, parser):
parser.add_argument(
- "--health-port",
+ "--max-concurrency",
type=int,
- default=8080,
- help="Port for the health check HTTP server (default: 8080)",
+ default=16,
+ help="Maximum number of (team_id, schema_id) groups processed concurrently (default: 16)",
)
parser.add_argument(
- "--batch-size",
- type=int,
- default=1000,
- help="Maximum number of messages to process per batch (default: 1000)",
+ "--poll-interval",
+ type=float,
+ default=2.0,
+ help="Seconds between poll cycles when idle (default: 2.0)",
)
parser.add_argument(
- "--batch-timeout",
- type=float,
- default=5.0,
- help="Timeout in seconds for polling a batch (default: 5.0)",
+ "--poll-limit",
+ type=int,
+ default=50,
+ help="Maximum batches fetched per poll cycle (default: 50)",
)
parser.add_argument(
- "--input-topic",
- type=str,
- default=KAFKA_WAREHOUSE_SOURCES_JOBS,
- help="Kafka topic to consume messages from",
+ "--max-attempts",
+ type=int,
+ default=3,
+ help="Maximum processing attempts per batch before failing the run (default: 3)",
)
parser.add_argument(
- "--consumer-group",
- type=str,
- required=True,
- help="Kafka consumer group ID",
+ "--health-port",
+ type=int,
+ default=8080,
+ help="Port for the health check HTTP server (default: 8080)",
)
parser.add_argument(
"--health-timeout",
@@ -54,63 +52,34 @@ class Command(BaseCommand):
default=60.0,
help="Health check timeout in seconds (default: 60.0)",
)
- parser.add_argument(
- "--dlq-topic",
- type=str,
- default=KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ,
- help="Kafka topic for dead-letter queue messages",
- )
- parser.add_argument(
- "--max-poll-interval-ms",
- type=int,
- default=1_080_000,
- help=(
- "Maximum time between consume() calls before librdkafka evicts this consumer "
- "from the group (default: 1080000 = 18 min). Post-load processing on final "
- "batches can exceed the librdkafka default of 5 min."
- ),
- )
def handle(self, *args, **options):
health_port = options["health_port"]
- batch_size = options["batch_size"]
- batch_timeout = options["batch_timeout"]
- input_topic = options["input_topic"]
- consumer_group = options["consumer_group"]
health_timeout = options["health_timeout"]
- dlq_topic = options["dlq_topic"]
- max_poll_interval_ms = options["max_poll_interval_ms"]
+
+ config = ConsumerConfig(
+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,
+ max_concurrency=options["max_concurrency"],
+ poll_interval_seconds=options["poll_interval"],
+ poll_limit=options["poll_limit"],
+ max_attempts=options["max_attempts"],
+ health_port=health_port,
+ health_timeout_seconds=health_timeout,
+ )
logger.info(
"warehouse_sources_load_starting",
+ max_concurrency=config.max_concurrency,
+ poll_interval=config.poll_interval_seconds,
+ poll_limit=config.poll_limit,
+ max_attempts=config.max_attempts,
health_port=health_port,
- batch_size=batch_size,
- batch_timeout=batch_timeout,
- input_topic=input_topic,
- consumer_group=consumer_group,
- health_timeout=health_timeout,
- dlq_topic=dlq_topic,
- max_poll_interval_ms=max_poll_interval_ms,
)
health_state = HealthState(timeout_seconds=health_timeout)
-
start_health_server(port=health_port, health_state=health_state)
- config = ConsumerConfig(
- input_topic=input_topic,
- consumer_group=consumer_group,
- dlq_topic=dlq_topic,
- batch_size=batch_size,
- batch_timeout_seconds=batch_timeout,
- health_port=health_port,
- health_timeout_seconds=health_timeout,
- max_poll_interval_ms=max_poll_interval_ms,
+ consumer = BatchConsumer(
+ config=config, process_batch=process_batch, health_reporter=health_state.report_healthy
)
-
- consumer = KafkaConsumerService(
- config=config,
- process_message=process_message,
- )
-
- consumer.run(health_reporter=health_state.report_healthy)
+ asyncio.run(consumer.run())
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 0e406d4cd2c3..1c72ec95ed2a 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -178,6 +178,7 @@ if persons_db_writer_url:
product_routes = load_product_db_routes(Path(__file__).resolve().parents[2])
configured_product_databases: set[str] = set()
+PRODUCT_DB_WRITER_URLS: dict[str, str] = {}
for route in product_routes:
if route.database in configured_product_databases:
@@ -198,6 +199,7 @@ for route in product_routes:
if not writer_url:
continue
+ PRODUCT_DB_WRITER_URLS[db] = writer_url
DATABASES[writer_alias] = dict(dj_database_url.parse(writer_url, conn_max_age=0))
DATABASES[writer_alias].setdefault("OPTIONS", {})["connect_timeout"] = 3
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.py
index 7b9d4379fff5..e45024542f01 100644
--- a/posthog/settings/data_warehouse.py
+++ b/posthog/settings/data_warehouse.py
@@ -2,6 +2,7 @@ import os
from posthog.settings import TEST
from posthog.settings.base_variables import DEBUG
+from posthog.settings.data_stores import DATABASE_URL, PRODUCT_DB_WRITER_URLS
from posthog.settings.utils import get_from_env, str_to_bool
DATAWAREHOUSE_LOCAL_BUCKET_REGION = os.getenv("DATAWAREHOUSE_LOCAL_BUCKET_REGION", "us-east-1")
@@ -39,6 +40,10 @@ CLICKHOUSE_HOGQL_RDSPROXY_READ_DATABASE: str | None = os.getenv("CLICKHOUSE_HOGQ
CLICKHOUSE_HOGQL_RDSPROXY_READ_USER: str | None = os.getenv("CLICKHOUSE_HOGQL_RDSPROXY_READ_USER")
CLICKHOUSE_HOGQL_RDSPROXY_READ_PASSWORD: str | None = os.getenv("CLICKHOUSE_HOGQL_RDSPROXY_READ_PASSWORD")
+WAREHOUSE_SOURCES_DATABASE_URL: str = (
+ os.getenv("WAREHOUSE_SOURCES_DATABASE_URL") or PRODUCT_DB_WRITER_URLS.get("warehouse_sources_queue") or DATABASE_URL
+)
+
# Warehouse-pipeline and cyclotron Kafka config live in `posthog/settings/kafka.py`
# (profiles `warehouse_sources` and `cyclotron`) — read from `settings.KAFKA_PROFILES[...]`
# or via the back-compat top-level names that settings/kafka.py exposes.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 3fe51071d31d..a566a38b5e6b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -71,6 +71,7 @@ PRODUCTS_APPS = [
"products.legal_documents.backend.apps.LegalDocumentsConfig",
"products.query_performance_ai.backend.apps.QueryPerformanceAiConfig",
"products.access_control.backend.apps.AccessControlConfig",
+ "products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",
]
INSTALLED_APPS = [
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index f90824adef92..59018eec9585 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -8,6 +8,7 @@ from structlog.types import FilteringBoundLogger
from temporalio import activity
from posthog.models import DataWarehouseTable
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
from posthog.temporal.common.shutdown import ShutdownMonitor
from posthog.temporal.data_imports.pipelines.common.extract import (
cdp_producer_clear_chunks,
@@ -35,12 +36,15 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
normalize_table_column_names,
)
from posthog.temporal.data_imports.pipelines.pipeline_sync import set_initial_sync_complete
-from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka import KafkaBatchProducer, SyncTypeLiteral
from posthog.temporal.data_imports.pipelines.pipeline_v3.metrics import (
get_batches_produced_metric,
get_pipeline_run_duration_metric,
get_rows_extracted_metric,
)
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import (
+ PostgresProducer,
+ SyncTypeLiteral,
+)
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult, S3BatchWriter
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3.writer import ParquetCompression
from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -70,7 +74,7 @@ class PipelineV3(Generic[ResumableData]):
_batcher: Batcher
_load_id: int
_s3_batch_writer: S3BatchWriter
- _kafka_producer: KafkaBatchProducer
+ _pg_producer: PostgresProducer
_accumulated_pa_schema: pa.Schema | None
_batch_results: list[BatchWriteResult]
@@ -127,7 +131,8 @@ class PipelineV3(Generic[ResumableData]):
is_resume = resumable_source_manager is not None and resumable_source_manager.can_resume()
- self._kafka_producer = KafkaBatchProducer(
+ self._pg_producer = PostgresProducer(
+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,
team_id=self._job.team_id,
job_id=str(self._job.id),
schema_id=str(self._schema.id),
@@ -172,7 +177,7 @@ class PipelineV3(Generic[ResumableData]):
team_id_str = str(self._job.team_id)
schema_id_str = str(self._schema.id)
source_type = self._source.source_type if self._source else "unknown"
- sync_type = self._kafka_producer.sync_type
+ sync_type = self._pg_producer.sync_type
start_time = time.perf_counter()
status = "success"
@@ -203,7 +208,7 @@ class PipelineV3(Generic[ResumableData]):
is_fresh_sync = self._delta_table_helper.is_first_sync or self._schema.table is None
if is_fresh_sync:
- self._kafka_producer.is_first_ever_sync = True
+ self._pg_producer.is_first_ever_sync = True
async for item in async_iterate(self._resource.items()):
py_table = None
@@ -282,7 +287,8 @@ class PipelineV3(Generic[ResumableData]):
self._logger.debug("V3 Pipeline: Cleaning up resources")
del self._resource
del self._s3_batch_writer
- del self._kafka_producer
+ self._pg_producer.close()
+ del self._pg_producer
cleanup_memory(pa_memory_pool, py_table if "py_table" in locals() else None)
@@ -303,8 +309,7 @@ class PipelineV3(Generic[ResumableData]):
batch_result = await asyncio.to_thread(self._s3_batch_writer.write_batch, pa_table, batch_index)
self._batch_results.append(batch_result)
- self._kafka_producer.send_batch_notification(batch_result, is_final_batch=False, cumulative_row_count=row_count)
- self._kafka_producer.flush()
+ self._pg_producer.send_batch_notification(batch_result, is_final_batch=False, cumulative_row_count=row_count)
self._internal_schema.add_pyarrow_table(pa_table)
@@ -351,7 +356,8 @@ class PipelineV3(Generic[ResumableData]):
schema_path = await asyncio.to_thread(self._s3_batch_writer.write_schema)
final_batch = self._batch_results[-1]
- self._kafka_producer.send_batch_notification(
+
+ self._pg_producer.send_batch_notification(
final_batch,
is_final_batch=True,
total_batches=total_batches,
@@ -361,8 +367,6 @@ class PipelineV3(Generic[ResumableData]):
cumulative_row_count=row_count,
)
- self._kafka_producer.flush()
-
await finalize_desc_sort_incremental_value(
self._resource, self._schema, self._last_incremental_field_value, self._logger, log_prefix="V3 Pipeline: "
)
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/20260423 - PostgresArchitecture.png b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/20260423 - PostgresArchitecture.png
new file mode 100644
index 000000000000..95bd2281b281
Binary files /dev/null and b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/20260423 - PostgresArchitecture.png differ
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md
new file mode 100644
index 000000000000..f5b75821256e
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/README.md
@@ -0,0 +1,172 @@
+# Postgres queue for warehouse batch loading
+
+## Problem statement
+
+The Kafka-based consumer for warehouse sources load worked but was fragile. Because a single load could run long, we had to keep pushing max.poll.interval.ms higher (along with session timeouts and max.poll.records) just to stop the broker from evicting consumers mid-batch, every increase was a bandaid, not a fix. On top of that, most of the real logic lived outside the message: retry state in Redis, DLQ routing through a second producer, schema-level locks and progress tracking in yet another store. The message itself was barely more than a pointer; Kafka was carrying the notification while everything that actually mattered happened elsewhere. Every configuration knob we added was compensating for a mismatch between what Kafka gives you and what we actually need.
+
+## RudderStack's approach
+
+RudderStack has been running warehouse loading on Postgres queues for 6+ years, handling 100K events/second at peak.
+Their design uses two tables per queue (a jobs table and an append-only status table) which avoids UPDATE contention and keeps the write path insert-only.
+They partition jobs into datasets of ~100K rows each, use COPY for bulk inserts, and run a compaction process to consolidate completed datasets.
+
+You can find more on:
+
+- [Why RudderStack Used Postgres Over Kafka](https://www.rudderstack.com/blog/why-rudderstack-used-postgres-over-apache-kafka-for-streaming-engine/)
+- [Kafka vs PostgreSQL: Implementing Our Queueing System](https://www.rudderstack.com/blog/kafka-vs-postgresql-implementing-our-queueing-system-using-postgresql/)
+- [Scaling Postgres Queues to 100K Events](https://www.rudderstack.com/blog/scaling-postgres-queue/)
+
+## Our solution
+
+We took RudderStack's two-table model (jobs + append-only status) but kept things simpler (for now, at least)
+
+### What we use
+
+- **Two tables**: `sourcebatch` (the jobs) and `sourcebatchstatus` (append-only status log). A `DISTINCT ON` view (`v_latest_source_batch_status`) gives us the latest status per batch.
+- **Advisory locks** for cross-pod coordination: `pg_try_advisory_lock(namespace, hashtext(team_id:schema_id))` ensures no two pods process the same (team_id, schema_id) simultaneously. Session-level locks held for the duration of group processing, released explicitly after.
+- **Async consumer** (`consumer.py`): single asyncio process that polls, groups batches by (team_id, schema_id), processes groups concurrently via `asyncio.gather`, batches within a group sequentially.
+- **Recovery sweep**: periodic check (every 30s) for batches stuck in `executing` whose advisory lock is not held, those were owned by a crashed pod. Uses a separate connection so it doesn't interfere with the main lock session.
+- **Sync producer** (`producer.py`): runs inside Temporal activities, plain `psycopg.Connection` with autocommit. Each `send_batch_notification` is a single INSERT.
+- **New DB**: we created a new DB to store these two new tables
+
+- **Daily range partitioning** on `created_at`: both tables use `PARTITION BY RANGE (created_at)` with daily partitions. Composite PK `(id, created_at)` is required by Postgres for partitioned tables. A DEFAULT partition catches rows that miss a partition. A Temporal scheduled workflow (`warehouse-sources-queue-partition-management`) runs every 6 hours to create the next 7 days of partitions and drop partitions older than 7 days. `DROP TABLE partition` is O(1) metadata-only — no vacuum, no dead tuples.
+- **MATERIALIZED CTE for advisory locks**: `pg_try_advisory_lock` in a WHERE clause with LIMIT can acquire phantom locks on rows later discarded. All consumer queries use a MATERIALIZED CTE to fully resolve candidates before probing locks.
+- **Partition pruning bounds**: all consumer queries include `created_at > now() - interval '14 days'` (2x the 7-day retention) so the planner can skip dropped partitions.
+
+### What we left out
+
+- **COPY bulk inserts**: the producer inserts one row per batch. At our volume, row-level INSERT is fine. (We can always move to bulk insert if needed)
+- **Compaction**: RudderStack runs a background process to merge/drop completed datasets, it stores tables up to 100k rows and then they roll to the next one. We don't need it at the moment, but if we end up implementing rolling datasets, we will implement this compaction too.
+- **Caching layers**: RudderStack uses "no jobs" caches and active pipeline caches to reduce query load. Our poll query is cheap enough with proper indexing.
+- **Recursive CTE loose index scans**: their trick for finding distinct pipeline IDs efficiently. Our `get_unprocessed_and_lock` query is simple enough without it.
+- **Active Partitions**: RudderStack designs a partition and then it assigns each partition to one processor instance, this is similar to how Kafka partitions work. We don't need this, this will be an overkill as we don't have any specifics for a partition.
+
+### Architecture
+
+![Postgres queue architecture](./20260423%20-%20PostgresArchitecture.png)
+
+## Things to look out for during roll out
+
+- **Partition health**: monitor that the `warehouse-sources-queue-partition-management` Temporal schedule is running. Alert on rows landing in DEFAULT partitions (means partition creation failed).
+- **DB Load**: we will keep an eye on the load and the locks to make sure the tables can hold the full load of warehouse sources
+
+## Extra. Paths (CLAUDE GENERATED)
+
+All state transitions are **inserts** into `sourcebatch`; rows in `sourcebatch` are never updated.
+The latest state per batch comes from the view `v_latest_source_batch_status` (`DISTINCT ON (batch_id) ... ORDER BY batch_id ASC, id DESC`).
+The consumer uses an **autocommit** connection, a **session-level** `pg_try_advisory_lock(ns, hashtext("team_id:schema_id"))`, and polls every ~2s for up to `poll_limit` pending batches via `get_unprocessed_and_lock`.
+
+### Happy path
+
+```text
+t=0 Producer (Temporal activity, autocommit):
+ INSERT batch 1 (run=R, team=T, schema=S, batch_index=1)
+ INSERT batch 2 (run=R, team=T, schema=S, batch_index=2)
+ No status rows yet -> the view reports these as unprocessed.
+
+t=1 Consumer A poll tick (get_unprocessed_and_lock):
+ SELECT ... FROM batch b
+ LEFT JOIN v_last_external_data_job_batch_status s ON b.id = s.batch_id
+ WHERE (s.batch_id IS NULL OR s.job_state = 'waiting_retry')
+ AND b.run_uuid NOT IN (<runs with any failed batch>)
+ AND pg_try_advisory_lock(ns, hashtext(b.team_id || ':' || b.schema_id))
+ ORDER BY b.id ASC LIMIT N;
+ -> returns batches 1 and 2; advisory lock for (T,S) is held on this session.
+
+t=2 _group_by_key groups results by (team_id, schema_id):
+ groups[(T,S)] = [batch 1, batch 2]
+ asyncio.gather runs each group via _process_group; batches within
+ a group are awaited sequentially.
+
+t=3 _process_single(batch 1):
+ INSERT status(batch=1, job_state='executing', attempt=1) -- pre-increment
+ await process_batch(batch 1) -- loads parquet into Delta Lake
+ INSERT status(batch=1, job_state='succeeded', attempt=1)
+
+t=4 _process_single(batch 2): same sequence, attempt=1 -> succeeded.
+
+t=5 End of _process_group (finally):
+ SELECT pg_advisory_unlock(ns, hashtext('T:S'))
+ (Also released at shutdown via pg_advisory_unlock_all.)
+
+t=6 Producer inserted batches 3, 4 in the meantime.
+ They are picked up on a later poll tick -- by this pod or another.
+ The advisory lock arbitrates which pod drains the group at any
+ given moment; there is no inner loop that picks up new work
+ mid-group.
+```
+
+### Transient failure + retry
+
+```text
+tX _process_single(batch K):
+ INSERT status(K, 'executing', attempt=1)
+ await process_batch(K) -- raises (e.g. S3 read timeout)
+ Caught in _process_single:
+ if attempt >= max_attempts (3) -> _fail_run
+ else -> INSERT status(K, 'waiting_retry', attempt=1, error_response={...})
+
+tX+1 Next poll: batch K matches (s.job_state = 'waiting_retry'), lock still
+ acquirable -> returned again. _process_single runs with
+ attempt = latest_attempt + 1 = 2.
+```
+
+### Max retries exceeded
+
+```text
+ _process_single on the final attempt raises -> _fail_run(batch, reason):
+ fail_run(conn, run_uuid) issues a single INSERT ... SELECT that
+ appends a 'failed' status for every batch in the run whose current
+ state is NULL / waiting / waiting_retry / executing.
+ _update_job_status_to_failed marks the ExternalDataJob as FAILED
+ via the Django ORM (sync_to_async).
+ Subsequent polls skip the whole run via the
+ NOT IN (<runs with any failed batch>) filter.
+```
+
+### OOM / pod crash mid-batch (recovery sweep)
+
+```text
+t=0 _process_single(batch K):
+ INSERT status(K, 'executing', attempt=k) -- commits (autocommit)
+ load starts
+
+t=1 OS OOM-killer SIGKILLs the pod.
+ Postgres detects the connection drop and auto-releases the
+ session-level advisory lock. Latest state of K stays 'executing'
+ in the view -- that row is durable.
+
+t=2 Every 30s, _recovery_loop on some consumer runs _recovery_sweep
+ against its dedicated _recovery_conn:
+ SELECT b.*, COALESCE(s.attempt, 0) FROM batch b
+ JOIN v_last_external_data_job_batch_status s ON ...
+ WHERE s.job_state = 'executing'
+ AND pg_try_advisory_lock(ns, hashtext(b.team_id || ':' || b.schema_id))
+ ORDER BY b.id ASC;
+ Only orphans pass the filter -- if another pod is still processing
+ (T,S), pg_try_advisory_lock returns false. Each returned row's
+ probe lock is immediately released with pg_advisory_unlock.
+
+t=3 For every orphan:
+ if latest_attempt >= max_attempts -> _fail_run
+ (reason: "max retries exceeded (likely OOM)")
+ else -> INSERT status(K, 'waiting_retry', attempt=latest_attempt)
+ No +1: the 'executing' insert at t=0 already consumed an attempt.
+
+t=4 On the next main poll, batch K is picked up via the
+ 'waiting_retry' branch and retried (attempt becomes
+ latest_attempt + 1 on re-execute).
+```
+
+### Graceful shutdown (SIGTERM / SIGINT)
+
+```text
+ Signal handler sets self._shutdown.
+ Main loop checks _shutdown.is_set() and exits after the current
+ asyncio.gather completes. Inside _process_group, the per-batch
+ loop also checks _shutdown and breaks early, leaving remaining
+ batches in the group for the next consumer (their state is
+ still 'waiting' -- no 'executing' row was written).
+ _close cancels the recovery task, runs pg_advisory_unlock_all
+ on the main connection, and closes both connections.
+```
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/__init__.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
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
new file mode 100644
index 000000000000..376abd7c6413
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -0,0 +1,357 @@
+"""
+Postgres-backed batch consumer for warehouse source loading.
+
+Replaces KafkaConsumerService with a single asyncio process that polls the
+batch queue, groups work by (team_id, schema_id), processes groups concurrently
+(batches within a group run sequentially), and uses advisory locks for
+cross-pod coordination.
+"""
+
+from __future__ import annotations
+
+import time
+import signal
+import asyncio
+from collections import defaultdict
+from collections.abc import Callable, Coroutine
+from dataclasses import dataclass
+from typing import Any
+
+import psycopg
+import structlog
+from asgiref.sync import sync_to_async
+
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import BatchQueue, PendingBatch
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (
+ ACTIVE_GROUPS,
+ BATCH_PROCESSING_DURATION_SECONDS,
+ BATCH_RETRY_TOTAL,
+ BATCHES_PROCESSED_TOTAL,
+ POLL_BATCHES_FETCHED,
+ POLL_DURATION_SECONDS,
+ RECOVERY_SWEEPS_TOTAL,
+ RUNS_FAILED_TOTAL,
+)
+
+from products.warehouse_sources_queue.backend.models import SourceBatchStatus
+
+logger = structlog.get_logger(__name__)
+
+MAX_ATTEMPTS = 3
+POLL_INTERVAL_SECONDS = 2.0
+
+
+RECOVERY_INTERVAL_SECONDS = 30.0
+
+
+@dataclass
+class ConsumerConfig:
+ """Tuning knobs for the batch consumer."""
+
+ database_url: str
+ max_concurrency: int = 16
+ max_attempts: int = MAX_ATTEMPTS
+ poll_interval_seconds: float = POLL_INTERVAL_SECONDS
+ poll_limit: int = 50
+ health_port: int = 8080
+ health_timeout_seconds: float = 60.0
+ recovery_interval_seconds: float = RECOVERY_INTERVAL_SECONDS
+
+
+class BatchConsumer:
+ """
+ Single-process consumer that polls Postgres for pending batches, groups them
+ by (team_id, schema_id), and processes each group concurrently while batches
+ within a group run sequentially. Advisory locks prevent two pods from
+ working on the same (team_id, schema_id) simultaneously.
+ """
+
+ def __init__(
+ self,
+ config: ConsumerConfig,
+ process_batch: ProcessBatchFn,
+ health_reporter: Callable[[], None] | None = None,
+ ) -> None:
+ self._config = config
+ self._process_batch = process_batch
+ self._health_reporter = health_reporter
+ self._semaphore = asyncio.Semaphore(config.max_concurrency)
+ self._shutdown = asyncio.Event()
+ self._conn: psycopg.AsyncConnection[Any] | None = None
+ self._recovery_conn: psycopg.AsyncConnection[Any] | None = None
+ self._recovery_task: asyncio.Task[None] | None = None
+
+ async def run(self) -> None:
+ """Main loop: poll → group → process → unlock → repeat."""
+ self._install_signal_handlers()
+
+ self._conn = await psycopg.AsyncConnection.connect(
+ self._config.database_url,
+ autocommit=True,
+ )
+ self._recovery_conn = await psycopg.AsyncConnection.connect(
+ self._config.database_url,
+ autocommit=True,
+ )
+
+ logger.info(
+ "batch_consumer_started",
+ max_concurrency=self._config.max_concurrency,
+ poll_interval=self._config.poll_interval_seconds,
+ poll_limit=self._config.poll_limit,
+ )
+
+ try:
+ await self._recovery_sweep()
+ self._recovery_task = asyncio.create_task(self._recovery_loop())
+
+ while not self._shutdown.is_set():
+ if self._health_reporter:
+ self._health_reporter()
+
+ poll_start = time.monotonic()
+ batches = await BatchQueue.get_unprocessed_and_lock(
+ self._conn,
+ limit=self._config.poll_limit,
+ )
+ POLL_DURATION_SECONDS.observe(time.monotonic() - poll_start)
+ POLL_BATCHES_FETCHED.observe(len(batches))
+
+ if not batches:
+ try:
+ await asyncio.wait_for(
+ self._shutdown.wait(),
+ timeout=self._config.poll_interval_seconds,
+ )
+ except TimeoutError:
+ pass
+ continue
+
+ groups = _group_by_key(batches)
+
+ logger.debug(
+ "poll_returned",
+ batch_count=len(batches),
+ group_count=len(groups),
+ )
+
+ ACTIVE_GROUPS.inc(len(groups))
+ try:
+ await asyncio.gather(
+ *[self._process_group(key, group_batches) for key, group_batches in groups.items()]
+ )
+ finally:
+ ACTIVE_GROUPS.dec(len(groups))
+
+ finally:
+ await self._close()
+
+ async def _process_group(
+ self,
+ key: tuple[int, str],
+ batches: list[PendingBatch],
+ ) -> None:
+ """Process all batches for a (team_id, schema_id) sequentially, then unlock."""
+ team_id, schema_id = key
+ await self._semaphore.acquire()
+ try:
+ for batch in batches:
+ if self._shutdown.is_set():
+ logger.info(
+ "shutdown_mid_group",
+ team_id=team_id,
+ schema_id=schema_id,
+ remaining=len(batches) - batches.index(batch),
+ )
+ break
+ await self._process_single(batch)
+ finally:
+ self._semaphore.release()
+ assert self._conn is not None
+ await BatchQueue.unlock_for_batches(self._conn, batches=batches)
+
+ async def _process_single(self, batch: PendingBatch) -> None:
+ """Increment attempt, check max retries, then process the batch."""
+ assert self._conn is not None
+
+ team_id = str(batch.team_id)
+ schema_id = batch.schema_id
+ attempt = batch.latest_attempt + 1
+
+ # Check before we even try — if already at max, fail the whole run.
+ if attempt > self._config.max_attempts:
+ logger.error(
+ "batch_max_retries_exceeded",
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ attempt=attempt,
+ )
+ await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")
+ return
+
+ # Pre-increment: if we OOM here, recovery sees attempt=N+1
+ # and knows this attempt was consumed.
+ await BatchQueue.update_status(
+ self._conn,
+ batch_id=batch.id,
+ job_state=SourceBatchStatus.State.EXECUTING,
+ attempt=attempt,
+ )
+
+ try:
+ start = time.monotonic()
+ await self._process_batch(batch)
+ BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).observe(
+ time.monotonic() - start
+ )
+
+ await BatchQueue.update_status(
+ self._conn,
+ batch_id=batch.id,
+ job_state=SourceBatchStatus.State.SUCCEEDED,
+ attempt=attempt,
+ )
+ BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="success").inc()
+ except Exception as e:
+ BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="error").inc()
+ BATCH_RETRY_TOTAL.labels(attempt=str(attempt), error_type=type(e).__name__).inc()
+
+ if attempt >= self._config.max_attempts:
+ logger.exception(
+ "batch_failed_no_retries_left",
+ batch_id=batch.id,
+ run_uuid=batch.run_uuid,
+ attempt=attempt,
+ )
+ await self._fail_run(batch, reason=f"max retries exceeded: {e}")
+ else:
+ logger.warning(
+ "batch_failed_will_retry",
+ batch_id=batch.id,
+ attempt=attempt,
+ error=str(e),
+ )
+ await BatchQueue.update_status(
+ self._conn,
+ batch_id=batch.id,
+ job_state=SourceBatchStatus.State.WAITING_RETRY,
+ attempt=attempt,
+ error_response={"error": str(e)[:1000]},
+ )
+
+ async def _fail_run(
+ self,
+ batch: PendingBatch,
+ reason: str,
+ conn: psycopg.AsyncConnection[Any] | None = None,
+ ) -> None:
+ """Fail all pending batches in this run and mark the ExternalDataJob as failed."""
+ conn = conn or self._conn
+ assert conn is not None
+
+ await BatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)
+ RUNS_FAILED_TOTAL.inc()
+
+ await sync_to_async(_update_job_status_to_failed)(
+ job_id=batch.job_id,
+ team_id=batch.team_id,
+ error=reason,
+ )
+
+ async def _recovery_loop(self) -> None:
+ """Run recovery sweeps periodically until shutdown."""
+ while not self._shutdown.is_set():
+ try:
+ await asyncio.wait_for(
+ self._shutdown.wait(),
+ timeout=self._config.recovery_interval_seconds,
+ )
+ except TimeoutError:
+ pass
+
+ if self._shutdown.is_set():
+ break
+
+ try:
+ await self._recovery_sweep()
+ except Exception:
+ logger.exception("recovery_sweep_error")
+
+ async def _recovery_sweep(self) -> None:
+ """Recover batches left in 'executing' by a crashed pod."""
+ conn = self._recovery_conn or self._conn
+ assert conn is not None
+
+ stale = await BatchQueue.get_stale_executing(conn)
+ if not stale:
+ RECOVERY_SWEEPS_TOTAL.labels(outcome="clean").inc()
+ return
+
+ RECOVERY_SWEEPS_TOTAL.labels(outcome="orphans_found").inc()
+ logger.info("recovery_sweep_found_stale_batches", count=len(stale))
+
+ for batch in stale:
+ # latest_attempt was already incremented before the crash
+ # (pre-increment in _process_single), so no +1 needed here.
+ if batch.latest_attempt >= self._config.max_attempts:
+ await self._fail_run(batch, reason="max retries exceeded (likely OOM)", conn=conn)
+ else:
+ await BatchQueue.update_status(
+ conn,
+ batch_id=batch.id,
+ job_state=SourceBatchStatus.State.WAITING_RETRY,
+ attempt=batch.latest_attempt,
+ )
+
+ def _install_signal_handlers(self) -> None:
+ """Wire SIGTERM/SIGINT to trigger graceful shutdown."""
+ loop = asyncio.get_running_loop()
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ loop.add_signal_handler(sig, self._shutdown.set)
+
+ async def _close(self) -> None:
+ """Cancel the recovery task, release all advisory locks, and close both connections."""
+ if self._recovery_task is not None:
+ self._recovery_task.cancel()
+ try:
+ await self._recovery_task
+ except asyncio.CancelledError:
+ pass
+
+ if self._recovery_conn is not None and not self._recovery_conn.closed:
+ await self._recovery_conn.close()
+
+ if self._conn is not None and not self._conn.closed:
+ await self._conn.execute("SELECT pg_advisory_unlock_all()")
+ await self._conn.close()
+
+ logger.info("batch_consumer_stopped")
+
+
+ProcessBatchFn = Callable[[PendingBatch], Coroutine[Any, Any, None]]
+
+
+def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> None:
+ """Sync helper to mark the ExternalDataJob and its schema as failed via Django ORM."""
+ from products.data_warehouse.backend.external_data_source.jobs import update_external_job_status
+ from products.data_warehouse.backend.models.external_data_job import ExternalDataJob
+
+ existing = ExternalDataJob.objects.filter(id=job_id, team_id=team_id, status=ExternalDataJob.Status.FAILED).first()
+ if existing is not None:
+ return
+
+ update_external_job_status(
+ job_id=job_id,
+ team_id=team_id,
+ status=ExternalDataJob.Status.FAILED,
+ logger=structlog.get_logger(),
+ latest_error=error,
+ )
+
+
+def _group_by_key(batches: list[PendingBatch]) -> dict[tuple[int, str], list[PendingBatch]]:
+ """Group batches by (team_id, schema_id), preserving insertion order."""
+ groups: dict[tuple[int, str], list[PendingBatch]] = defaultdict(list)
+ for batch in batches:
+ groups[(batch.team_id, batch.schema_id)].append(batch)
+ return groups
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
new file mode 100644
index 000000000000..654f13a892a3
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -0,0 +1,330 @@
+"""
+Postgres-based job queue for warehouse source batch processing.
+
+Replaces the Kafka topic `warehouse_sources_jobs` with direct Postgres inserts
+and advisory-lock-based coordination. All SQL is isolated here so that the
+producer (Temporal activity) and consumer share a single interface to the queue.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+import psycopg
+from psycopg.rows import dict_row
+
+BATCH_TABLE = "sourcebatch"
+STATUS_TABLE = "sourcebatchstatus"
+STATUS_VIEW = "v_latest_source_batch_status"
+
+# Namespace for advisory locks to avoid collisions with other PostHog subsystems.
+ADVISORY_LOCK_NAMESPACE = 0x57485300 # "WHS\0" in hex
+
+# Partition pruning hint: only scan partitions within this window.
+# Set to 2x the retention period so the planner can skip dropped
+# partitions. Not a correctness filter — older partitions are already
+# gone by the time this matters.
+PARTITION_PRUNING_INTERVAL = "14 days"
+
+
+@dataclass(frozen=True, slots=True)
+class PendingBatch:
+ """A batch row fetched from the queue, ready to be processed by the consumer."""
+
+ id: str
+ team_id: int
+ schema_id: str
+ source_id: str
+ job_id: str
+ run_uuid: str
+ batch_index: int
+ s3_path: str
+ row_count: int
+ byte_size: int
+ is_final_batch: bool
+ total_batches: int | None
+ total_rows: int | None
+ sync_type: str
+ cumulative_row_count: int
+ resource_name: str
+ is_resume: bool
+ is_first_ever_sync: bool
+ metadata: dict[str, Any]
+ latest_attempt: int
+ created_at: datetime | None = None
+
+ def to_export_signal(self) -> dict[str, Any]:
+ """Temporary bridge: convert a PendingBatch into an ExportSignalMessage dict
+ so we can reuse the existing process_message() for local testing. The final
+ solution will operate on PendingBatch directly without this conversion."""
+ return {
+ "team_id": self.team_id,
+ "job_id": self.job_id,
+ "schema_id": self.schema_id,
+ "source_id": self.source_id,
+ "resource_name": self.resource_name,
+ "run_uuid": self.run_uuid,
+ "batch_index": self.batch_index,
+ "s3_path": self.s3_path,
+ "row_count": self.row_count,
+ "byte_size": self.byte_size,
+ "is_final_batch": self.is_final_batch,
+ "total_batches": self.total_batches,
+ "total_rows": self.total_rows,
+ "sync_type": self.sync_type,
+ "cumulative_row_count": self.cumulative_row_count,
+ "is_resume": self.is_resume,
+ "is_first_ever_sync": self.is_first_ever_sync,
+ "timestamp_ns": self.metadata.get("timestamp_ns", time.time_ns()),
+ "data_folder": self.metadata.get("data_folder"),
+ "schema_path": self.metadata.get("schema_path"),
+ "primary_keys": self.metadata.get("primary_keys"),
+ "partition_count": self.metadata.get("partition_count"),
+ "partition_size": self.metadata.get("partition_size"),
+ "partition_keys": self.metadata.get("partition_keys"),
+ "partition_format": self.metadata.get("partition_format"),
+ "partition_mode": self.metadata.get("partition_mode"),
+ "cdc_write_mode": self.metadata.get("cdc_write_mode"),
+ "cdc_table_mode": self.metadata.get("cdc_table_mode"),
+ }
+
+
+class BatchQueue:
+ """
+ Async interface to the Postgres batch queue tables. Each method runs
+ its own query against the provided connection — callers manage connections
+ and transactions.
+ """
+
+ # -- writes (producer side) ------------------------------------------------
+
+ @staticmethod
+ async def insert(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int,
+ schema_id: str,
+ source_id: str,
+ job_id: str,
+ run_uuid: str,
+ batch_index: int,
+ s3_path: str,
+ row_count: int,
+ byte_size: int,
+ is_final_batch: bool,
+ total_batches: int | None,
+ total_rows: int | None,
+ sync_type: str,
+ cumulative_row_count: int,
+ resource_name: str,
+ is_resume: bool,
+ is_first_ever_sync: bool,
+ metadata: dict[str, Any],
+ ) -> str:
+ """Insert a batch row into the queue. Returns the new batch id."""
+ row = await conn.execute(
+ f"""
+ INSERT INTO {BATCH_TABLE} (
+ id, team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, created_at
+ ) VALUES (
+ gen_random_uuid(),
+ %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,
+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,
+ %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,
+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, now()
+ )
+ RETURNING id
+ """,
+ {
+ "team_id": team_id,
+ "schema_id": schema_id,
+ "source_id": source_id,
+ "job_id": job_id,
+ "run_uuid": run_uuid,
+ "batch_index": batch_index,
+ "s3_path": s3_path,
+ "row_count": row_count,
+ "byte_size": byte_size,
+ "is_final_batch": is_final_batch,
+ "total_batches": total_batches,
+ "total_rows": total_rows,
+ "sync_type": sync_type,
+ "cumulative_row_count": cumulative_row_count,
+ "resource_name": resource_name,
+ "is_resume": is_resume,
+ "is_first_ever_sync": is_first_ever_sync,
+ "metadata": json.dumps(metadata),
+ },
+ )
+ batch_id: str = str((await row.fetchone())[0]) # type: ignore[index]
+ return batch_id
+
+ # -- reads (consumer side) -------------------------------------------------
+
+ @staticmethod
+ async def get_unprocessed_and_lock(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ limit: int = 50,
+ ) -> list[PendingBatch]:
+ """Fetch unprocessed batches whose (team_id, schema_id) advisory lock is acquirable.
+
+ Uses a MATERIALIZED CTE so that candidate selection (with LIMIT) is
+ fully resolved before any advisory lock is acquired. Without this,
+ Postgres is free to evaluate pg_try_advisory_lock on rows that are
+ later discarded by other predicates or by LIMIT, creating phantom
+ locks that unlock_for_batches never releases.
+ """
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(
+ f"""
+ WITH candidates AS MATERIALIZED (
+ SELECT
+ b.id, b.team_id, b.schema_id, b.source_id, b.job_id,
+ b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,
+ b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,
+ b.cumulative_row_count, b.resource_name, b.is_resume,
+ b.is_first_ever_sync, b.metadata,
+ COALESCE(s.attempt, 0) AS latest_attempt,
+ b.created_at
+ FROM {BATCH_TABLE} b
+ LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND (s.batch_id IS NULL OR s.job_state = 'waiting_retry')
+ AND b.run_uuid NOT IN (
+ SELECT DISTINCT b2.run_uuid
+ FROM {BATCH_TABLE} b2
+ JOIN {STATUS_VIEW} s2 ON b2.id = s2.batch_id
+ WHERE b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND s2.job_state = 'failed'
+ )
+ ORDER BY b.created_at ASC, b.batch_index ASC
+ LIMIT %(limit)s
+ )
+ SELECT c.*
+ FROM candidates c
+ 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},
+ )
+ rows = await cur.fetchall()
+ return [PendingBatch(**row) for row in rows]
+
+ @staticmethod
+ async def update_status(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ batch_id: str,
+ job_state: str,
+ attempt: int = 0,
+ error_response: dict[str, Any] | None = None,
+ ) -> None:
+ """Append a status row for a batch (executing, succeeded, waiting_retry, failed)."""
+ await conn.execute(
+ f"""
+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
+ VALUES (%(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now())
+ """,
+ {
+ "batch_id": batch_id,
+ "job_state": job_state,
+ "attempt": attempt,
+ "error_response": json.dumps(error_response) if error_response else None,
+ },
+ )
+
+ @staticmethod
+ async def get_stale_executing(
+ conn: psycopg.AsyncConnection[Any],
+ ) -> list[PendingBatch]:
+ """Find batches stuck in 'executing' whose advisory lock is not held (previous pod crashed).
+
+ Uses a MATERIALIZED CTE for the same reason as get_unprocessed_and_lock:
+ candidate rows are fully resolved before any advisory lock is probed.
+ """
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(
+ f"""
+ WITH candidates AS MATERIALIZED (
+ SELECT
+ b.id, b.team_id, b.schema_id, b.source_id, b.job_id,
+ b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,
+ b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,
+ b.cumulative_row_count, b.resource_name, b.is_resume,
+ b.is_first_ever_sync, b.metadata,
+ COALESCE(s.attempt, 0) AS latest_attempt,
+ b.created_at
+ FROM {BATCH_TABLE} b
+ JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND s.job_state = 'executing'
+ ORDER BY b.created_at ASC, b.batch_index ASC
+ )
+ SELECT c.*
+ FROM candidates c
+ 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
+ """,
+ )
+ rows = await cur.fetchall()
+
+ result = [PendingBatch(**row) for row in rows]
+
+ # Release the locks immediately — we only needed them to detect orphans.
+ await BatchQueue.unlock_for_batches(conn, batches=result)
+
+ return result
+
+ @staticmethod
+ async def fail_run(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ run_uuid: str,
+ reason: str,
+ ) -> int:
+ """Mark every pending batch in a run as failed. Returns the count of batches failed."""
+ cursor = await conn.execute(
+ f"""
+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
+ SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
+ FROM {BATCH_TABLE} b
+ LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.run_uuid = %(run_uuid)s
+ AND (s.batch_id IS NULL OR s.job_state IN ('waiting', 'waiting_retry', 'executing'))
+ """,
+ {
+ "run_uuid": run_uuid,
+ "error_response": json.dumps({"error": reason}),
+ },
+ )
+ return cursor.rowcount or 0
+
+ @staticmethod
+ async def unlock_for_batches(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ batches: list[PendingBatch],
+ ) -> None:
+ """Release advisory locks once per returned batch row.
+
+ The MATERIALIZED CTE in get_unprocessed_and_lock ensures locks are
+ only acquired on rows that actually appear in the result set, so
+ one unlock per row balances the depth exactly.
+ """
+ for batch in batches:
+ await conn.execute(
+ "SELECT pg_advisory_unlock(%(ns)s, hashtext(%(key)s))",
+ {"ns": ADVISORY_LOCK_NAMESPACE, "key": f"{batch.team_id}:{batch.schema_id}"},
+ )
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
new file mode 100644
index 000000000000..3e0e571bd425
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/load.py
@@ -0,0 +1,24 @@
+"""
+Adapter that connects the BatchConsumer to the existing Delta Lake loading logic.
+
+Converts a PendingBatch into an ExportSignalMessage dict and delegates to
+process_message(). This exists because ProcessBatchFn expects an async callable
+that takes a PendingBatch, but the existing processor works with ExportSignalMessage
+dicts. Once process_message is refactored to accept PendingBatch directly, this
+adapter and to_export_signal() can be removed.
+
+The BatchConsumer handles retries and status updates around this function — it
+only needs to raise on failure.
+"""
+
+from __future__ import annotations
+
+from asgiref.sync import sync_to_async
+
+from posthog.temporal.data_imports.pipelines.pipeline_v3.load.processor import process_message
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch
+
+
+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())
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
new file mode 100644
index 000000000000..7f5f83884f5d
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
@@ -0,0 +1,49 @@
+from prometheus_client import Counter, Gauge, Histogram
+
+BATCHES_PROCESSED_TOTAL = Counter(
+ "warehouse_pg_consumer_batches_processed_total",
+ "Total batches processed by the Postgres consumer",
+ labelnames=["team_id", "schema_id", "status"],
+)
+
+BATCH_PROCESSING_DURATION_SECONDS = Histogram(
+ "warehouse_pg_consumer_batch_processing_duration_seconds",
+ "Duration of individual batch processing",
+ labelnames=["team_id", "schema_id"],
+ buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
+)
+
+BATCH_RETRY_TOTAL = Counter(
+ "warehouse_pg_consumer_batch_retry_total",
+ "Total batch retry attempts",
+ labelnames=["attempt", "error_type"],
+)
+
+RUNS_FAILED_TOTAL = Counter(
+ "warehouse_pg_consumer_runs_failed_total",
+ "Total runs fully failed via fail_run()",
+)
+
+POLL_DURATION_SECONDS = Histogram(
+ "warehouse_pg_consumer_poll_duration_seconds",
+ "Duration of Postgres poll queries",
+ buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),
+)
+
+POLL_BATCHES_FETCHED = Histogram(
+ "warehouse_pg_consumer_poll_batches_fetched",
+ "Number of batches returned per poll cycle",
+ buckets=(0, 1, 5, 10, 25, 50, 100, 250, 500),
+)
+
+ACTIVE_GROUPS = Gauge(
+ "warehouse_pg_consumer_active_groups",
+ "Number of (team_id, schema_id) groups currently being processed",
+ multiprocess_mode="livesum",
+)
+
+RECOVERY_SWEEPS_TOTAL = Counter(
+ "warehouse_pg_consumer_recovery_sweeps_total",
+ "Total recovery sweeps executed",
+ labelnames=["outcome"],
+)
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
new file mode 100644
index 000000000000..0549fccaaaf9
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -0,0 +1,171 @@
+"""
+Postgres-backed batch producer for warehouse source loading.
+
+Drop-in replacement for KafkaBatchProducer: each send_batch_notification
+inserts a row into the Postgres batch queue. flush() is a no-op because
+inserts are durable on commit — no async delivery pipeline to drain.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any, Optional
+
+import psycopg
+import structlog
+from structlog.types import FilteringBoundLogger
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat, PartitionMode
+from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import BATCH_TABLE
+from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
+
+logger = structlog.get_logger(__name__)
+
+
+class PostgresProducer:
+ """Writes batch rows directly into the Postgres queue on each send call."""
+
+ def __init__(
+ self,
+ database_url: str,
+ team_id: int,
+ job_id: str,
+ schema_id: str,
+ source_id: str,
+ resource_name: str,
+ sync_type: SyncTypeLiteral,
+ run_uuid: str,
+ logger: FilteringBoundLogger,
+ primary_keys: list[str] | None = None,
+ is_resume: bool = False,
+ partition_count: int | None = None,
+ partition_size: int | None = None,
+ partition_keys: list[str] | None = None,
+ partition_format: PartitionFormat | None = None,
+ partition_mode: PartitionMode | None = None,
+ is_first_ever_sync: bool = False,
+ cdc_write_mode: str | None = None,
+ cdc_table_mode: str | None = None,
+ ) -> None:
+ self._team_id = team_id
+ self._job_id = job_id
+ self._schema_id = schema_id
+ self._source_id = source_id
+ self._resource_name = resource_name
+ self._sync_type = sync_type
+ self._run_uuid = run_uuid
+ self._primary_keys = primary_keys
+ self._is_resume = is_resume
+ self._logger = logger
+ self._partition_count = partition_count
+ self._partition_size = partition_size
+ self._partition_keys = partition_keys
+ self._partition_format = partition_format
+ self._partition_mode = partition_mode
+ self._is_first_ever_sync = is_first_ever_sync
+ self._cdc_write_mode = cdc_write_mode
+ self._cdc_table_mode = cdc_table_mode
+
+ self._conn = psycopg.Connection.connect(database_url, autocommit=True)
+ self._batches_sent = 0
+
+ @property
+ def sync_type(self) -> SyncTypeLiteral:
+ return self._sync_type
+
+ @property
+ def is_first_ever_sync(self) -> bool:
+ return self._is_first_ever_sync
+
+ @is_first_ever_sync.setter
+ def is_first_ever_sync(self, value: bool) -> None:
+ self._is_first_ever_sync = value
+
+ def send_batch_notification(
+ self,
+ batch_result: BatchWriteResult,
+ is_final_batch: bool = False,
+ total_batches: Optional[int] = None,
+ total_rows: Optional[int] = None,
+ data_folder: Optional[str] = None,
+ schema_path: Optional[str] = None,
+ cumulative_row_count: int = 0,
+ ) -> None:
+ """Insert a batch row into the Postgres queue."""
+ metadata: dict[str, Any] = {}
+ if data_folder is not None:
+ metadata["data_folder"] = data_folder
+ if schema_path is not None:
+ metadata["schema_path"] = schema_path
+ if self._primary_keys is not None:
+ metadata["primary_keys"] = self._primary_keys
+ if self._partition_count is not None:
+ metadata["partition_count"] = self._partition_count
+ if self._partition_size is not None:
+ metadata["partition_size"] = self._partition_size
+ if self._partition_keys is not None:
+ metadata["partition_keys"] = self._partition_keys
+ if self._partition_format is not None:
+ metadata["partition_format"] = self._partition_format
+ if self._partition_mode is not None:
+ metadata["partition_mode"] = self._partition_mode
+ if self._cdc_write_mode is not None:
+ metadata["cdc_write_mode"] = self._cdc_write_mode
+ if self._cdc_table_mode is not None:
+ metadata["cdc_table_mode"] = self._cdc_table_mode
+ metadata["timestamp_ns"] = batch_result.timestamp_ns
+
+ self._conn.execute(
+ f"""
+ INSERT INTO {BATCH_TABLE} (
+ team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata, created_at
+ ) VALUES (
+ %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,
+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,
+ %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,
+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, now()
+ )
+ """,
+ {
+ "team_id": self._team_id,
+ "schema_id": self._schema_id,
+ "source_id": self._source_id,
+ "job_id": self._job_id,
+ "run_uuid": self._run_uuid,
+ "batch_index": batch_result.batch_index,
+ "s3_path": batch_result.s3_path,
+ "row_count": batch_result.row_count,
+ "byte_size": batch_result.byte_size,
+ "is_final_batch": is_final_batch,
+ "total_batches": total_batches,
+ "total_rows": total_rows,
+ "sync_type": self._sync_type,
+ "cumulative_row_count": cumulative_row_count,
+ "resource_name": self._resource_name,
+ "is_resume": self._is_resume,
+ "is_first_ever_sync": self._is_first_ever_sync,
+ "metadata": json.dumps(metadata),
+ },
+ )
+
+ self._batches_sent += 1
+ self._logger.debug(
+ "batch_inserted_to_postgres_queue",
+ batch_index=batch_result.batch_index,
+ is_final_batch=is_final_batch,
+ )
+
+ def flush(self, timeout: Optional[float] = None) -> int:
+ """No-op — inserts are durable on commit. Returns count of batches sent since last flush."""
+ count = self._batches_sent
+ self._batches_sent = 0
+ return count
+
+ def close(self) -> None:
+ """Close the Postgres connection."""
+ if not self._conn.closed:
+ self._conn.close()
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
new file mode 100644
index 000000000000..f779f41342f1
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -0,0 +1,274 @@
+from typing import Any
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (
+ BatchConsumer,
+ ConsumerConfig,
+ _group_by_key,
+)
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch
+
+from products.warehouse_sources_queue.backend.models import SourceBatchStatus
+
+
+def _make_batch(**overrides: Any) -> PendingBatch:
+ defaults: dict[str, Any] = {
+ "id": "00000000-0000-0000-0000-000000000001",
+ "team_id": 1,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "job_id": "job-1",
+ "run_uuid": "run-1",
+ "batch_index": 0,
+ "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,
+ }
+ defaults.update(overrides)
+ return PendingBatch(**defaults)
+
+
+def _make_consumer(max_attempts: int = 3, **kwargs) -> BatchConsumer:
+ config = ConsumerConfig(
+ database_url="postgres://unused:unused@localhost/unused",
+ max_attempts=max_attempts,
+ **kwargs,
+ )
+ mock_process = AsyncMock()
+ consumer = BatchConsumer(config=config, process_batch=mock_process)
+ consumer._conn = AsyncMock()
+ consumer._recovery_conn = AsyncMock()
+ return consumer
+
+
+class TestProcessSingle:
+ @pytest.mark.asyncio
+ async def test_success_updates_status_to_executing_then_succeeded(self):
+ consumer = _make_consumer()
+ batch = _make_batch(latest_attempt=0)
+ states: list[str] = []
+
+ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):
+ states.append(job_state)
+
+ consumer._process_batch = AsyncMock()
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ side_effect=track_status,
+ ):
+ await consumer._process_single(batch)
+
+ assert states == [SourceBatchStatus.State.EXECUTING, SourceBatchStatus.State.SUCCEEDED]
+
+ @pytest.mark.asyncio
+ async def test_error_sets_waiting_retry(self):
+ consumer = _make_consumer(max_attempts=3)
+ batch = _make_batch(latest_attempt=0)
+ states: list[str] = []
+
+ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):
+ states.append(job_state)
+
+ consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))
+ with patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ side_effect=track_status,
+ ):
+ await consumer._process_single(batch)
+
+ assert states == [SourceBatchStatus.State.EXECUTING, SourceBatchStatus.State.WAITING_RETRY]
+
+ @pytest.mark.asyncio
+ async def test_max_attempts_exceeded_fails_run(self):
+ consumer = _make_consumer(max_attempts=3)
+ batch = _make_batch(latest_attempt=3)
+
+ with patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail:
+ await consumer._process_single(batch)
+
+ mock_fail.assert_called_once()
+ assert "max retries exceeded" in mock_fail.call_args[1]["reason"]
+
+ @pytest.mark.asyncio
+ async def test_error_at_max_attempts_fails_run(self):
+ consumer = _make_consumer(max_attempts=2)
+ batch = _make_batch(latest_attempt=1)
+ consumer._process_batch = AsyncMock(side_effect=RuntimeError("crash"))
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ ):
+ await consumer._process_single(batch)
+
+ mock_fail.assert_called_once()
+
+
+class TestProcessGroup:
+ @pytest.mark.asyncio
+ async def test_processes_batches_in_order(self):
+ consumer = _make_consumer()
+ order: list[int] = []
+
+ async def track_batch(batch):
+ order.append(batch.batch_index)
+
+ consumer._process_batch = track_batch
+
+ batches = [_make_batch(batch_index=i, id=f"00000000-0000-0000-0000-{i + 1:012d}") for i in range(3)]
+
+ 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,
+ ) as mock_unlock,
+ ):
+ await consumer._process_group((1, "schema-1"), batches)
+
+ assert order == [0, 1, 2]
+ mock_unlock.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_unlocks_even_on_error(self):
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock(side_effect=RuntimeError("crash"))
+
+ batches = [_make_batch()]
+
+ 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,
+ ) as mock_unlock,
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock),
+ ):
+ await consumer._process_group((1, "schema-1"), batches)
+
+ mock_unlock.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_stops_on_shutdown(self):
+ consumer = _make_consumer()
+ processed: list[int] = []
+
+ async def track_and_shutdown(batch):
+ processed.append(batch.batch_index)
+ if batch.batch_index == 0:
+ consumer._shutdown.set()
+
+ consumer._process_batch = track_and_shutdown
+
+ batches = [_make_batch(batch_index=i, id=f"00000000-0000-0000-0000-{i + 1:012d}") for i in range(3)]
+
+ 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((1, "schema-1"), batches)
+
+ assert processed == [0]
+
+
+class TestRecoverySweep:
+ @pytest.mark.asyncio
+ async def test_retries_stale_below_max(self):
+ consumer = _make_consumer(max_attempts=3)
+ stale_batch = _make_batch(latest_attempt=1)
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[stale_batch],
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ) as mock_status,
+ ):
+ await consumer._recovery_sweep()
+
+ mock_status.assert_called_once_with(
+ consumer._recovery_conn,
+ batch_id=stale_batch.id,
+ job_state=SourceBatchStatus.State.WAITING_RETRY,
+ attempt=1,
+ )
+
+ @pytest.mark.asyncio
+ async def test_fails_exhausted_stale_batch(self):
+ consumer = _make_consumer(max_attempts=3)
+ stale_batch = _make_batch(latest_attempt=3)
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[stale_batch],
+ ),
+ patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,
+ ):
+ await consumer._recovery_sweep()
+
+ mock_fail.assert_called_once()
+ assert "max retries exceeded" in mock_fail.call_args[1]["reason"]
+
+
+class TestGroupByKey:
+ def test_groups_by_team_and_schema(self):
+ batches = [
+ _make_batch(id="00000000-0000-0000-0000-000000000001", team_id=1, schema_id="a", batch_index=0),
+ _make_batch(id="00000000-0000-0000-0000-000000000002", team_id=1, schema_id="b", batch_index=0),
+ _make_batch(id="00000000-0000-0000-0000-000000000003", team_id=1, schema_id="a", batch_index=1),
+ _make_batch(id="00000000-0000-0000-0000-000000000004", team_id=2, schema_id="a", batch_index=0),
+ ]
+
+ groups = _group_by_key(batches)
+
+ assert len(groups) == 3
+ assert len(groups[(1, "a")]) == 2
+ assert len(groups[(1, "b")]) == 1
+ assert len(groups[(2, "a")]) == 1
+
+ def test_preserves_insertion_order(self):
+ batches = [
+ _make_batch(id="00000000-0000-0000-0000-000000000001", team_id=1, schema_id="a", batch_index=0),
+ _make_batch(id="00000000-0000-0000-0000-000000000002", team_id=1, schema_id="a", batch_index=1),
+ _make_batch(id="00000000-0000-0000-0000-000000000003", team_id=1, schema_id="a", batch_index=2),
+ ]
+
+ groups = _group_by_key(batches)
+
+ assert [b.batch_index for b in groups[(1, "a")]] == [0, 1, 2]
+
+ def test_empty_input(self):
+ assert _group_by_key([]) == {}
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
new file mode 100644
index 000000000000..63270c4f2bb7
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -0,0 +1,343 @@
+from typing import Any
+
+import pytest
+
+import psycopg
+
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BATCH_TABLE,
+ STATUS_TABLE,
+ STATUS_VIEW,
+ BatchQueue,
+ PendingBatch,
+)
+
+
+def _get_test_database_url() -> str:
+ from django.db import connection
+
+ s = connection.settings_dict
+ host = s.get("HOST", "localhost") or "localhost"
+ port = s.get("PORT", "5432") or "5432"
+ return f"postgres://{s['USER']}:{s['PASSWORD']}@{host}:{port}/{s['NAME']}"
+
+
+def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {BATCH_TABLE} (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ source_id VARCHAR(200) NOT NULL,
+ job_id VARCHAR(200) NOT NULL,
+ run_uuid VARCHAR(200) NOT NULL,
+ batch_index INT NOT NULL,
+ s3_path TEXT NOT NULL,
+ row_count INT NOT NULL,
+ byte_size BIGINT NOT NULL,
+ is_final_batch BOOLEAN NOT NULL,
+ total_batches INT,
+ total_rows BIGINT,
+ sync_type VARCHAR(32) NOT NULL,
+ cumulative_row_count BIGINT NOT NULL DEFAULT 0,
+ resource_name VARCHAR(400) NOT NULL,
+ is_resume BOOLEAN NOT NULL DEFAULT FALSE,
+ is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,
+ metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ """)
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,
+ job_state VARCHAR(32) NOT NULL,
+ attempt SMALLINT NOT NULL DEFAULT 0,
+ exec_time TIMESTAMPTZ,
+ error_response JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ """)
+ conn.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")
+ conn.execute(f"""
+ CREATE VIEW {STATUS_VIEW} AS
+ SELECT DISTINCT ON (batch_id) *
+ FROM {STATUS_TABLE}
+ ORDER BY batch_id ASC, created_at DESC, id DESC
+ """)
+
+
+def _truncate_tables(conn: psycopg.Connection[Any]) -> None:
+ conn.execute(f"TRUNCATE {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE")
+
+
+_BATCH_DEFAULTS: dict[str, Any] = {
+ "team_id": 1,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "job_id": "job-1",
+ "run_uuid": "run-1",
+ "batch_index": 0,
+ "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": {},
+}
+
+
+async def _insert_batch(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:
+ params = {**_BATCH_DEFAULTS, **overrides}
+ return await BatchQueue.insert(conn, **params)
+
+
[email protected](scope="session")
+def _db_url() -> str:
+ return _get_test_database_url()
+
+
[email protected](scope="session", autouse=True)
+def _create_tables(_db_url: str) -> None:
+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:
+ _ensure_tables(conn)
+
+
[email protected](autouse=True)
+def _clean_tables(_db_url: str) -> None:
+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:
+ _truncate_tables(conn)
+ conn.execute("SELECT pg_advisory_unlock_all()")
+
+
+async def conn(_db_url: str):
+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:
+ yield c
+
+
+async def conn_b(_db_url: str):
+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:
+ yield c
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueInsert:
+ @pytest.mark.asyncio
+ async def test_insert_returns_uuid(self, conn):
+ batch_id = await _insert_batch(conn)
+
+ assert len(batch_id) == 36
+ assert batch_id.count("-") == 4
+
+ @pytest.mark.asyncio
+ async def test_insert_unique_ids(self, conn):
+ id1 = await _insert_batch(conn, batch_index=0)
+ id2 = await _insert_batch(conn, batch_index=1)
+
+ assert id1 != id2
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueGetUnprocessed:
+ @pytest.mark.asyncio
+ async def test_returns_new_batches(self, conn):
+ await _insert_batch(conn, batch_index=0)
+ await _insert_batch(conn, batch_index=1)
+ await _insert_batch(conn, batch_index=2)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+
+ assert len(batches) == 3
+ assert sorted(b.batch_index for b in batches) == [0, 1, 2]
+
+ @pytest.mark.asyncio
+ async def test_skips_succeeded_batches(self, conn):
+ bid = await _insert_batch(conn)
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+
+ assert len(batches) == 0
+
+ @pytest.mark.asyncio
+ async def test_returns_waiting_retry_batches(self, conn):
+ bid = await _insert_batch(conn)
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="waiting_retry", attempt=1)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+
+ assert len(batches) == 1
+ assert batches[0].latest_attempt == 1
+
+ @pytest.mark.asyncio
+ async def test_skips_entire_failed_run(self, conn):
+ await _insert_batch(conn, batch_index=0, run_uuid="run-fail")
+ bid2 = await _insert_batch(conn, batch_index=1, run_uuid="run-fail")
+ await BatchQueue.update_status(conn, batch_id=bid2, job_state="failed", attempt=1)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+
+ assert len(batches) == 0
+
+ @pytest.mark.asyncio
+ async def test_respects_limit(self, conn):
+ for i in range(10):
+ await _insert_batch(conn, batch_index=i)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn, limit=3)
+
+ assert len(batches) == 3
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueUpdateStatus:
+ @pytest.mark.asyncio
+ async def test_appends_multiple_statuses(self, conn):
+ bid = await _insert_batch(conn)
+
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)
+
+ row = await conn.execute(f"SELECT count(*) FROM {STATUS_TABLE} WHERE batch_id = %s", [bid])
+ count = (await row.fetchone())[0]
+ assert count == 2
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueFailRun:
+ @pytest.mark.asyncio
+ async def test_fails_only_pending_batches(self, conn):
+ bid1 = await _insert_batch(conn, batch_index=0, run_uuid="run-x")
+ await _insert_batch(conn, batch_index=1, run_uuid="run-x")
+ await _insert_batch(conn, batch_index=2, run_uuid="run-x")
+ await BatchQueue.update_status(conn, batch_id=bid1, job_state="succeeded", attempt=1)
+
+ count = await BatchQueue.fail_run(conn, run_uuid="run-x", reason="test failure")
+
+ assert count == 2
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ assert len(batches) == 0
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueAdvisoryLocks:
+ @pytest.mark.asyncio
+ async def test_unlock_for_batches_releases_locks(self, conn, conn_b):
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=1)
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=2)
+
+ batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ assert len(batches) == 3
+
+ batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
+ assert len(batches_b) == 0, "conn_b should not acquire lock held by conn"
+
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
+ batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
+ assert len(batches_b) == 3, "conn_b should acquire lock after conn released it"
+
+ await BatchQueue.unlock_for_batches(conn_b, batches=batches_b)
+
+ @pytest.mark.asyncio
+ async def test_different_keys_lock_independently(self, conn, conn_b):
+ await _insert_batch(conn, team_id=1, schema_id="s1")
+ await _insert_batch(conn, team_id=2, schema_id="s2")
+
+ batches_a = await BatchQueue.get_unprocessed_and_lock(conn)
+ assert len(batches_a) == 2
+
+ await BatchQueue.unlock_for_batches(conn, batches=[b for b in batches_a if b.schema_id == "s1"])
+
+ batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
+ assert len(batches_b) == 1
+ assert batches_b[0].schema_id == "s1"
+
+ await BatchQueue.unlock_for_batches(conn, batches=[b for b in batches_a if b.schema_id == "s2"])
+ await BatchQueue.unlock_for_batches(conn_b, batches=batches_b)
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueStaleExecuting:
+ @pytest.mark.asyncio
+ async def test_finds_orphaned_executing_batches(self, conn, conn_b, _db_url):
+ bid = await _insert_batch(conn)
+
+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as orphan_conn:
+ await BatchQueue.get_unprocessed_and_lock(orphan_conn)
+ await BatchQueue.update_status(orphan_conn, batch_id=bid, job_state="executing", attempt=1)
+ # orphan_conn is now closed — advisory lock released
+
+ stale = await BatchQueue.get_stale_executing(conn)
+ assert len(stale) == 1
+ assert str(stale[0].id) == bid
+ assert stale[0].latest_attempt == 1
+
+ @pytest.mark.asyncio
+ async def test_does_not_find_actively_held_batches(self, conn, conn_b):
+ bid = await _insert_batch(conn)
+
+ await BatchQueue.get_unprocessed_and_lock(conn)
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
+
+ stale = await BatchQueue.get_stale_executing(conn_b)
+ assert len(stale) == 0
+
+ await conn.execute("SELECT pg_advisory_unlock_all()")
+
+
+class TestPendingBatchToExportSignal:
+ def test_maps_all_fields(self):
+ batch = PendingBatch(
+ id="00000000-0000-0000-0000-000000000001",
+ team_id=42,
+ schema_id="schema-1",
+ source_id="source-1",
+ job_id="job-1",
+ run_uuid="run-1",
+ batch_index=3,
+ s3_path="s3://bucket/data.parquet",
+ row_count=500,
+ byte_size=2048,
+ is_final_batch=True,
+ total_batches=4,
+ total_rows=2000,
+ sync_type="incremental",
+ cumulative_row_count=1500,
+ resource_name="users",
+ is_resume=True,
+ is_first_ever_sync=False,
+ metadata={
+ "timestamp_ns": 123456789,
+ "data_folder": "/tmp/data",
+ "primary_keys": ["id"],
+ "cdc_write_mode": "upsert",
+ },
+ latest_attempt=2,
+ )
+
+ signal = batch.to_export_signal()
+
+ assert signal["team_id"] == 42
+ assert signal["job_id"] == "job-1"
+ assert signal["schema_id"] == "schema-1"
+ assert signal["batch_index"] == 3
+ assert signal["is_final_batch"] is True
+ assert signal["total_batches"] == 4
+ assert signal["sync_type"] == "incremental"
+ assert signal["cumulative_row_count"] == 1500
+ assert signal["is_resume"] is True
+ assert signal["timestamp_ns"] == 123456789
+ assert signal["data_folder"] == "/tmp/data"
+ assert signal["primary_keys"] == ["id"]
+ assert signal["cdc_write_mode"] == "upsert"
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
new file mode 100644
index 000000000000..d2e5cecb2362
--- /dev/null
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_producer.py
@@ -0,0 +1,134 @@
+import json
+from typing import Any
+
+from unittest.mock import MagicMock, PropertyMock, patch
+
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer import PostgresProducer
+from posthog.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
+
+
+def _make_producer(**kwargs: Any) -> PostgresProducer:
+ defaults: dict[str, Any] = {
+ "database_url": "postgres://unused:unused@localhost/unused",
+ "team_id": 1,
+ "job_id": "job-1",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "resource_name": "test_resource",
+ "sync_type": "full_refresh",
+ "run_uuid": "run-1",
+ "logger": MagicMock(),
+ }
+ defaults.update(kwargs)
+ with patch("posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.producer.psycopg") as mock_psycopg:
+ mock_conn = MagicMock()
+ mock_psycopg.Connection.connect.return_value = mock_conn
+ producer = PostgresProducer(**defaults)
+ return producer
+
+
+def _make_batch_result(batch_index: int = 0) -> BatchWriteResult:
+ return BatchWriteResult(
+ batch_index=batch_index,
+ s3_path="s3://bucket/path",
+ row_count=100,
+ byte_size=1024,
+ timestamp_ns=123456789,
+ )
+
+
+def _mock_conn(producer: PostgresProducer) -> Any:
+ return producer._conn
+
+
+class TestPostgresProducerSendBatch:
+ def test_inserts_row_on_send(self) -> None:
+ producer = _make_producer()
+ batch_result = _make_batch_result()
+
+ producer.send_batch_notification(batch_result)
+
+ mock = _mock_conn(producer)
+ mock.execute.assert_called_once()
+ sql = mock.execute.call_args[0][0]
+ params = mock.execute.call_args[0][1]
+ assert "INSERT INTO" in sql
+ assert params["team_id"] == 1
+ assert params["s3_path"] == "s3://bucket/path"
+ assert params["row_count"] == 100
+ assert params["batch_index"] == 0
+
+ def test_metadata_includes_optional_fields(self) -> None:
+ producer = _make_producer(
+ primary_keys=["id"],
+ partition_count=4,
+ cdc_write_mode="upsert",
+ cdc_table_mode="merge",
+ )
+ batch_result = _make_batch_result()
+
+ producer.send_batch_notification(batch_result)
+
+ mock = _mock_conn(producer)
+ params = mock.execute.call_args[0][1]
+ metadata = json.loads(params["metadata"])
+ assert metadata["primary_keys"] == ["id"]
+ assert metadata["partition_count"] == 4
+ assert metadata["cdc_write_mode"] == "upsert"
+ assert metadata["cdc_table_mode"] == "merge"
+ assert metadata["timestamp_ns"] == 123456789
+
+
+class TestPostgresProducerFlush:
+ def test_returns_count_and_resets(self) -> None:
+ producer = _make_producer()
+ producer.send_batch_notification(_make_batch_result(0))
+ producer.send_batch_notification(_make_batch_result(1))
+ producer.send_batch_notification(_make_batch_result(2))
+
+ count = producer.flush()
+
+ assert count == 3
+
+ count = producer.flush()
+ assert count == 0
+
+ def test_flush_with_no_batches(self) -> None:
+ producer = _make_producer()
+
+ assert producer.flush() == 0
+
+
+class TestPostgresProducerClose:
+ def test_closes_connection(self) -> None:
+ producer = _make_producer()
+ mock = _mock_conn(producer)
+ type(mock).closed = PropertyMock(return_value=False)
+
+ producer.close()
+
+ mock.close.assert_called_once()
+
+ def test_close_idempotent(self) -> None:
+ producer = _make_producer()
+ mock = _mock_conn(producer)
+ type(mock).closed = PropertyMock(return_value=True)
+
+ producer.close()
+
+ mock.close.assert_not_called()
+
+
+class TestPostgresProducerProperties:
+ def test_sync_type_property(self) -> None:
+ producer = _make_producer(sync_type="incremental")
+
+ assert producer.sync_type == "incremental"
+
+ def test_is_first_ever_sync_property(self) -> None:
+ producer = _make_producer(is_first_ever_sync=True)
+
+ assert producer.is_first_ever_sync is True
+
+ producer.is_first_ever_sync = False
+ assert producer.is_first_ever_sync is False
diff --git a/posthog/temporal/tests/data_imports/conftest.py b/posthog/temporal/tests/data_imports/conftest.py
index ee8efeff04b2..4bc308d5adc9 100644
--- a/posthog/temporal/tests/data_imports/conftest.py
+++ b/posthog/temporal/tests/data_imports/conftest.py
@@ -22,6 +22,11 @@ from posthog.hogql.query import execute_hogql_query
from posthog.temporal.data_imports.external_data_job import ExternalDataJobWorkflow
from posthog.temporal.data_imports.pipelines.pipeline.delta_table_helper import DeltaTableHelper
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BATCH_TABLE,
+ STATUS_TABLE,
+ STATUS_VIEW,
+)
from posthog.temporal.data_imports.settings import ACTIVITIES
from posthog.temporal.utils import ExternalDataWorkflowInputs
@@ -34,6 +39,73 @@ SESSION = aioboto3.Session()
create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)
[email protected](scope="package")
+def _ensure_sourcebatch_tables(django_db_setup, django_db_blocker):
+ """Create sourcebatch/sourcebatchstatus tables in the default test database.
+
+ The v3 pipeline tests patch WAREHOUSE_SOURCES_DATABASE_URL to point at
+ the Django test database, but the product migration only runs on the
+ dedicated warehouse_sources_queue DB. This fixture bridges the gap by
+ creating non-partitioned copies of the tables in the test DB.
+ """
+ with django_db_blocker.unblock():
+ from django.db import connection
+
+ with connection.cursor() as cur:
+ cur.execute(f"""
+ CREATE TABLE IF NOT EXISTS {BATCH_TABLE} (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ source_id VARCHAR(200) NOT NULL,
+ job_id VARCHAR(200) NOT NULL,
+ run_uuid VARCHAR(200) NOT NULL,
+ batch_index INT NOT NULL,
+ s3_path TEXT NOT NULL,
+ row_count INT NOT NULL,
+ byte_size BIGINT NOT NULL,
+ is_final_batch BOOLEAN NOT NULL,
+ total_batches INT,
+ total_rows BIGINT,
+ sync_type VARCHAR(32) NOT NULL,
+ cumulative_row_count BIGINT NOT NULL DEFAULT 0,
+ resource_name VARCHAR(400) NOT NULL,
+ is_resume BOOLEAN NOT NULL DEFAULT FALSE,
+ is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,
+ metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ """)
+ cur.execute(f"""
+ CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,
+ job_state VARCHAR(32) NOT NULL,
+ attempt SMALLINT NOT NULL DEFAULT 0,
+ exec_time TIMESTAMPTZ,
+ error_response JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ """)
+ cur.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")
+ cur.execute(f"""
+ CREATE VIEW {STATUS_VIEW} AS
+ SELECT DISTINCT ON (batch_id) *
+ FROM {STATUS_TABLE}
+ ORDER BY batch_id ASC, created_at DESC, id DESC
+ """)
+
+
+def _clean_sourcebatch_tables(_ensure_sourcebatch_tables):
+ """Truncate sourcebatch tables between tests so v3 runs start clean."""
+ yield
+ from django.db import connection
+
+ with connection.cursor() as cur:
+ cur.execute(f"TRUNCATE {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE")
+
+
@pytest_asyncio.fixture
async def minio_client():
"""Manage an S3 client to interact with a MinIO bucket.
diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.py
index 9aacec921adc..d4d9db49d628 100644
--- a/posthog/temporal/tests/data_imports/test_end_to_end.py
+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py
@@ -1,4 +1,5 @@
import re
+import json
import uuid
import functools
import contextlib
@@ -59,6 +60,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.delta_table_helper import
from posthog.temporal.data_imports.pipelines.pipeline.pipeline import PipelineNonDLT
from posthog.temporal.data_imports.pipelines.pipeline_v3.load.processor import process_message
from posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import BATCH_TABLE, PendingBatch
from posthog.temporal.data_imports.row_tracking import get_rows
from posthog.temporal.data_imports.settings import ACTIVITIES
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
@@ -105,35 +107,77 @@ _current_pipeline_mode = "non_dlt"
@pytest.fixture(params=["non_dlt", "v3"], autouse=True)
-def pipeline_mode(request):
+def pipeline_mode(request, _clean_sourcebatch_tables):
global _current_pipeline_mode
_current_pipeline_mode = request.param
yield request.param
_current_pipeline_mode = "non_dlt"
-class _KafkaMessageCapture:
- def __init__(self):
- self.messages: list[dict] = []
+# TODO: remove _KafkaMessageCapture once Postgres producer is fully validated
+# class _KafkaMessageCapture:
+# ...
+# _kafka_capture = _KafkaMessageCapture()
+
+
+def _get_test_database_url() -> str:
+ """Build a psycopg-compatible DSN from Django's active test database connection."""
+ from django.db import connection
+
+ s = connection.settings_dict
+ host = s.get("HOST", "localhost") or "localhost"
+ port = s.get("PORT", "5432") or "5432"
+ return f"postgres://{s['USER']}:{s['PASSWORD']}@{host}:{port}/{s['NAME']}"
+
+
+class _PostgresQueueReplay:
+ """Reads batch rows written by PostgresProducer during tests and replays them
+ through process_message(), mimicking what the real BatchConsumer does."""
+
+ def __init__(self) -> None:
self._processed_batches: set[tuple[str, int]] = set()
- def _capture_and_ack(self, topic, data, key=None, **kw):
- self.messages.append(data)
- return mock.MagicMock(get=mock.MagicMock(return_value=None))
+ def replay_batches_for_run(self, run_uuid: str) -> None:
+ from django.db import connection as django_conn
+
+ with django_conn.cursor() as cur:
+ cur.execute(
+ f"""
+ SELECT id, team_id, schema_id, source_id, job_id, run_uuid,
+ batch_index, s3_path, row_count, byte_size, is_final_batch,
+ total_batches, total_rows, sync_type, cumulative_row_count,
+ resource_name, is_resume, is_first_ever_sync, metadata
+ FROM {BATCH_TABLE}
+ WHERE run_uuid = %s
+ ORDER BY created_at ASC, batch_index ASC
+ """,
+ [run_uuid],
+ )
+ columns = [col.name for col in cur.description]
+ rows = [dict(zip(columns, row)) for row in cur.fetchall()]
- def get_mock_producer(self):
- producer = mock.MagicMock()
- producer.produce.side_effect = self._capture_and_ack
- producer.flush.return_value = 0
- return producer
+ if not rows:
+ return
- def replay_through_consumer(self):
- for msg in self.messages:
+ for row in rows:
+ if isinstance(row.get("metadata"), str):
+ row["metadata"] = json.loads(row["metadata"])
+ batch = PendingBatch(latest_attempt=0, **row)
try:
- process_message(msg)
+ process_message(batch.to_export_signal())
except Exception:
pass
+ def get_run_uuids_for_job(self, job_id: str) -> list[str]:
+ from django.db import connection as django_conn
+
+ with django_conn.cursor() as cur:
+ cur.execute(
+ f"SELECT DISTINCT run_uuid FROM {BATCH_TABLE} WHERE job_id = %s ORDER BY run_uuid",
+ [job_id],
+ )
+ return [row[0] for row in cur.fetchall()]
+
def mock_idempotency_check(
self,
team_id: int,
@@ -148,12 +192,11 @@ class _KafkaMessageCapture:
self._processed_batches.add(key)
return False
- def clear(self):
- self.messages.clear()
+ def clear(self) -> None:
self._processed_batches.clear()
-_kafka_capture = _KafkaMessageCapture()
+_pg_queue_replay = _PostgresQueueReplay()
@pytest.fixture
@@ -426,17 +469,30 @@ async def _run(
async def _replay_v3_consumer(team_id: int, schema_id, job_id: str | None = None):
- if _current_pipeline_mode != "v3" or not _kafka_capture.messages:
+ if _current_pipeline_mode != "v3":
return
+ if not job_id:
+ job = await sync_to_async(
+ ExternalDataJob.objects.filter(team_id=team_id, schema_id=schema_id).order_by("-created_at").first
+ )()
+ if not job:
+ return
+ job_id = str(job.id)
+ else:
+ job = await sync_to_async(ExternalDataJob.objects.get)(id=job_id)
+
# If the workflow already marked the job as COMPLETED (e.g. worker shutdown scenario),
# the consumer should not replay — the workflow managed the job status itself and
# S3 files may have been cleaned up.
- if job_id:
- job = await sync_to_async(ExternalDataJob.objects.get)(id=job_id)
- if job.status == ExternalDataJob.Status.COMPLETED:
- _kafka_capture.clear()
- return
+ if job.status == ExternalDataJob.Status.COMPLETED:
+ _pg_queue_replay.clear()
+ return
+
+ run_uuids = await sync_to_async(_pg_queue_replay.get_run_uuids_for_job)(job_id)
+ if not run_uuids:
+ _pg_queue_replay.clear()
+ return
with (
override_settings(
@@ -452,21 +508,21 @@ async def _replay_v3_consumer(team_id: int, schema_id, job_id: str | None = None
),
mock.patch(
"posthog.temporal.data_imports.pipelines.pipeline_v3.load.processor.is_batch_already_processed",
- side_effect=_kafka_capture.mock_idempotency_check,
+ side_effect=_pg_queue_replay.mock_idempotency_check,
),
):
- await sync_to_async(_kafka_capture.replay_through_consumer)()
-
- if job_id:
- await sync_to_async(calculate_table_size_activity)(
- CalculateTableSizeActivityInputs(
- team_id=team_id,
- schema_id=str(schema_id),
- job_id=job_id,
- )
+ for run_uuid in run_uuids:
+ await sync_to_async(_pg_queue_replay.replay_batches_for_run)(run_uuid)
+
+ await sync_to_async(calculate_table_size_activity)(
+ CalculateTableSizeActivityInputs(
+ team_id=team_id,
+ schema_id=str(schema_id),
+ job_id=job_id,
)
+ )
- _kafka_capture.clear()
+ _pg_queue_replay.clear()
async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, mock_data_response):
@@ -522,7 +578,7 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, moc
"AWS_S3_ALLOW_UNSAFE_RENAME": "true",
}
- _kafka_capture.clear()
+ _pg_queue_replay.clear()
with (
mock.patch.object(RESTClient, "paginate", mock_paginate),
@@ -552,10 +608,11 @@ async def _execute_run(workflow_id: str, inputs: ExternalDataWorkflowInputs, moc
return_value=True,
)
)
+ # Point the Postgres producer at the Django test database
stack.enter_context(
mock.patch(
- "posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.producer.get_warpstream_kafka_producer",
- return_value=_kafka_capture.get_mock_producer(),
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.pipeline.WAREHOUSE_SOURCES_DATABASE_URL",
+ _get_test_database_url(),
)
)
else:
diff --git a/products/db_routing.yaml b/products/db_routing.yaml
index 0baed8091b1a..baac59dbb2c3 100644
--- a/products/db_routing.yaml
+++ b/products/db_routing.yaml
@@ -1,3 +1,5 @@
routes:
- app_label: visual_review
database: visual_review
+ - app_label: warehouse_sources_queue
+ database: warehouse_sources_queue
diff --git a/products/warehouse_sources_queue/__init__.py b/products/warehouse_sources_queue/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources_queue/backend/__init__.py b/products/warehouse_sources_queue/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources_queue/backend/apps.py b/products/warehouse_sources_queue/backend/apps.py
new file mode 100644
index 000000000000..eae16d6da4c1
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/apps.py
@@ -0,0 +1,9 @@
+"""Django app configuration for warehouse_sources_queue."""
+
+from django.apps import AppConfig
+
+
+class WarehouseSourcesQueueConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.warehouse_sources_queue.backend"
+ label = "warehouse_sources_queue"
diff --git a/products/warehouse_sources_queue/backend/migrations/0001_initial.py b/products/warehouse_sources_queue/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..2c278263898f
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0001_initial.py
@@ -0,0 +1,242 @@
+# Generated by Django 4.2.29 on 2026-04-28
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+from posthog.models.utils import uuid7
+
+# How many daily partitions to pre-create ahead of today.
+PARTITIONS_AHEAD = 7
+
+
+def _create_partitioned_tables(apps, schema_editor):
+ schema_editor.execute("""
+ CREATE TABLE sourcebatch (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ source_id VARCHAR(200) NOT NULL,
+ job_id VARCHAR(200) NOT NULL,
+ run_uuid VARCHAR(200) NOT NULL,
+ batch_index INT NOT NULL,
+ s3_path TEXT NOT NULL,
+ row_count INT NOT NULL,
+ byte_size BIGINT NOT NULL,
+ is_final_batch BOOLEAN NOT NULL,
+ total_batches INT,
+ total_rows BIGINT,
+ sync_type VARCHAR(32) NOT NULL,
+ cumulative_row_count BIGINT NOT NULL DEFAULT 0,
+ resource_name VARCHAR(400) NOT NULL,
+ is_resume BOOLEAN NOT NULL DEFAULT FALSE,
+ is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (id, created_at)
+ ) PARTITION BY RANGE (created_at);
+
+ CREATE INDEX sb_team_schema_idx ON sourcebatch (team_id, schema_id);
+ CREATE INDEX sb_run_uuid_idx ON sourcebatch (run_uuid);
+
+ CREATE TABLE sourcebatch_default PARTITION OF sourcebatch DEFAULT;
+ """)
+
+ schema_editor.execute("""
+ CREATE TABLE sourcebatchstatus (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ batch_id UUID NOT NULL,
+ job_state VARCHAR(32) NOT NULL,
+ attempt SMALLINT NOT NULL DEFAULT 0,
+ exec_time TIMESTAMPTZ,
+ error_response JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (id, created_at)
+ ) PARTITION BY RANGE (created_at);
+
+ CREATE INDEX sbs_batch_id_desc_state_idx
+ ON sourcebatchstatus (batch_id, created_at DESC, id DESC, job_state);
+
+ CREATE TABLE sourcebatchstatus_default PARTITION OF sourcebatchstatus DEFAULT;
+ """)
+
+ # Pre-create daily partitions for today + next N days.
+ schema_editor.execute(f"""
+ DO $$
+ DECLARE
+ d DATE;
+ BEGIN
+ FOR d IN SELECT generate_series(
+ CURRENT_DATE,
+ CURRENT_DATE + {PARTITIONS_AHEAD},
+ '1 day'::interval
+ )::date
+ LOOP
+ EXECUTE format(
+ 'CREATE TABLE IF NOT EXISTS sourcebatch_%%s '
+ 'PARTITION OF sourcebatch '
+ 'FOR VALUES FROM (%%L) TO (%%L)',
+ to_char(d, 'YYYYMMDD'), d, d + 1
+ );
+ EXECUTE format(
+ 'CREATE TABLE IF NOT EXISTS sourcebatchstatus_%%s '
+ 'PARTITION OF sourcebatchstatus '
+ 'FOR VALUES FROM (%%L) TO (%%L)',
+ to_char(d, 'YYYYMMDD'), d, d + 1
+ );
+ END LOOP;
+ END $$;
+ """)
+
+
+def _create_latest_status_view(apps, schema_editor):
+ schema_editor.execute("""
+ CREATE VIEW v_latest_source_batch_status AS
+ SELECT DISTINCT ON (batch_id) *
+ FROM sourcebatchstatus
+ ORDER BY batch_id ASC, created_at DESC, id DESC
+ """)
+
+
+def _drop_all(apps, schema_editor):
+ schema_editor.execute("DROP VIEW IF EXISTS v_latest_source_batch_status")
+ schema_editor.execute("DROP TABLE IF EXISTS sourcebatchstatus CASCADE")
+ schema_editor.execute("DROP TABLE IF EXISTS sourcebatch CASCADE")
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ # Django state: let Django know the models exist so the ORM,
+ # makemigrations, and admin introspection work. The actual DDL
+ # is handled by RunSQL below because Django cannot express
+ # PARTITION BY RANGE.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="SourceBatch",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField()),
+ ("schema_id", models.CharField(max_length=200)),
+ ("source_id", models.CharField(max_length=200)),
+ (
+ "job_id",
+ models.CharField(
+ help_text="FK to ExternalDataJob (UUID as string).",
+ max_length=200,
+ ),
+ ),
+ ("run_uuid", models.CharField(max_length=200)),
+ ("batch_index", models.IntegerField()),
+ ("s3_path", models.TextField()),
+ ("row_count", models.IntegerField()),
+ ("byte_size", models.BigIntegerField()),
+ ("is_final_batch", models.BooleanField()),
+ ("total_batches", models.IntegerField(blank=True, null=True)),
+ ("total_rows", models.BigIntegerField(blank=True, null=True)),
+ (
+ "sync_type",
+ models.CharField(
+ choices=[
+ ("full_refresh", "full_refresh"),
+ ("incremental", "incremental"),
+ ("append", "append"),
+ ("cdc", "cdc"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ("cumulative_row_count", models.BigIntegerField(default=0)),
+ ("resource_name", models.CharField(max_length=400)),
+ ("is_resume", models.BooleanField(default=False)),
+ ("is_first_ever_sync", models.BooleanField(default=False)),
+ (
+ "metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Stores partitioning config, CDC mode, primary keys, schema path, data folder, etc.",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ "db_table": "sourcebatch",
+ "indexes": [
+ models.Index(fields=["team_id", "schema_id"], name="sb_team_schema_idx"),
+ models.Index(fields=["run_uuid"], name="sb_run_uuid_idx"),
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="SourceBatchStatus",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "job_state",
+ models.CharField(
+ choices=[
+ ("waiting", "waiting"),
+ ("executing", "executing"),
+ ("succeeded", "succeeded"),
+ ("waiting_retry", "waiting_retry"),
+ ("failed", "failed"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ("attempt", models.SmallIntegerField(default=0)),
+ ("exec_time", models.DateTimeField(blank=True, null=True)),
+ ("error_response", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "batch",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.DO_NOTHING,
+ db_constraint=False,
+ related_name="statuses",
+ to="warehouse_sources_queue.sourcebatch",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "sourcebatchstatus",
+ "indexes": [
+ models.Index(
+ fields=["batch_id", "-created_at", "-id", "job_state"],
+ name="sbs_batch_id_desc_state_idx",
+ ),
+ ],
+ },
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(
+ _create_partitioned_tables,
+ _drop_all,
+ ),
+ migrations.RunPython(
+ _create_latest_status_view,
+ lambda apps, schema_editor: schema_editor.execute("DROP VIEW IF EXISTS v_latest_source_batch_status"),
+ ),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/__init__.py b/products/warehouse_sources_queue/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
new file mode 100644
index 000000000000..cd5ea0eb6b0d
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -0,0 +1,83 @@
+from django.db import models
+
+from posthog.models.utils import UUIDModel, sane_repr
+
+
+class SourceBatch(UUIDModel):
+ class SyncType(models.TextChoices):
+ FULL_REFRESH = "full_refresh", "full_refresh"
+ INCREMENTAL = "incremental", "incremental"
+ APPEND = "append", "append"
+ CDC = "cdc", "cdc"
+
+ team_id = models.BigIntegerField()
+ schema_id = models.CharField(max_length=200)
+ source_id = models.CharField(max_length=200)
+ job_id = models.CharField(max_length=200, help_text="FK to ExternalDataJob (UUID as string).")
+ run_uuid = models.CharField(max_length=200)
+
+ batch_index = models.IntegerField()
+ s3_path = models.TextField()
+ row_count = models.IntegerField()
+ byte_size = models.BigIntegerField()
+ is_final_batch = models.BooleanField()
+ total_batches = models.IntegerField(null=True, blank=True)
+ total_rows = models.BigIntegerField(null=True, blank=True)
+ sync_type = models.CharField(max_length=32, choices=SyncType.choices)
+ cumulative_row_count = models.BigIntegerField(default=0)
+
+ resource_name = models.CharField(max_length=400)
+ is_resume = models.BooleanField(default=False)
+ is_first_ever_sync = models.BooleanField(default=False)
+
+ metadata = models.JSONField(
+ default=dict,
+ blank=True,
+ help_text="Stores partitioning config, CDC mode, primary keys, schema path, data folder, etc.",
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("id", "team_id", "schema_id", "batch_index")
+
+ class Meta:
+ db_table = "sourcebatch"
+ indexes = [
+ models.Index(fields=["team_id", "schema_id"], name="sb_team_schema_idx"),
+ models.Index(fields=["run_uuid"], name="sb_run_uuid_idx"),
+ ]
+
+
+class SourceBatchStatus(UUIDModel):
+ class State(models.TextChoices):
+ WAITING = "waiting", "waiting"
+ EXECUTING = "executing", "executing"
+ SUCCEEDED = "succeeded", "succeeded"
+ WAITING_RETRY = "waiting_retry", "waiting_retry"
+ FAILED = "failed", "failed"
+
+ # No DB-level FK constraint: sourcebatch is range-partitioned on
+ # created_at, making its PK composite (id, created_at). A real FK
+ # would require batch_created_at here. Referential integrity is
+ # enforced in application code — statuses are only inserted for
+ # known batch IDs.
+ batch = models.ForeignKey(
+ SourceBatch,
+ on_delete=models.DO_NOTHING,
+ db_constraint=False,
+ related_name="statuses",
+ )
+ job_state = models.CharField(max_length=32, choices=State.choices)
+ attempt = models.SmallIntegerField(default=0)
+ exec_time = models.DateTimeField(null=True, blank=True)
+ error_response = models.JSONField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ db_table = "sourcebatchstatus"
+ indexes = [
+ models.Index(
+ fields=["batch_id", "-created_at", "-id", "job_state"],
+ name="sbs_batch_id_desc_state_idx",
+ ),
+ ]
diff --git a/products/warehouse_sources_queue/backend/tests/__init__.py b/products/warehouse_sources_queue/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources_queue/backend/tests/test_models.py b/products/warehouse_sources_queue/backend/tests/test_models.py
new file mode 100644
index 000000000000..0039783664fe
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/tests/test_models.py
@@ -0,0 +1,23 @@
+from products.warehouse_sources_queue.backend.models import SourceBatch, SourceBatchStatus
+
+
+class TestSourceBatchModel:
+ def test_sync_type_choices(self):
+ values = {c.value for c in SourceBatch.SyncType}
+ assert values == {"full_refresh", "incremental", "append", "cdc"}
+
+ def test_db_table(self):
+ assert SourceBatch._meta.db_table == "sourcebatch"
+
+
+class TestSourceBatchStatusModel:
+ def test_state_choices(self):
+ values = {c.value for c in SourceBatchStatus.State}
+ assert values == {"waiting", "executing", "succeeded", "waiting_retry", "failed"}
+
+ def test_db_table(self):
+ assert SourceBatchStatus._meta.db_table == "sourcebatchstatus"
+
+ def test_batch_fk_has_no_db_constraint(self):
+ field = SourceBatchStatus._meta.get_field("batch")
+ assert not field.db_constraint # type: ignore[attr-defined]
diff --git a/products/warehouse_sources_queue/package.json b/products/warehouse_sources_queue/package.json
new file mode 100644
index 000000000000..6ec373d81fe2
--- /dev/null
+++ b/products/warehouse_sources_queue/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-warehouse-sources-queue",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend"
+ }
+}
diff --git a/products/warehouse_sources_queue/product.yaml b/products/warehouse_sources_queue/product.yaml
new file mode 100644
index 000000000000..c40875953f31
--- /dev/null
+++ b/products/warehouse_sources_queue/product.yaml
@@ -0,0 +1,3 @@
+name: Warehouse sources queue
+owners:
+ - team-warehouse-sources
diff --git a/tach.toml b/tach.toml
index fac88f7ab1ac..3b395cd10147 100644
--- a/tach.toml
+++ b/tach.toml
@@ -95,6 +95,7 @@ depends_on = [
"products.tracing",
"products.user_interviews",
"products.visual_review",
+ "products.warehouse_sources_queue",
"products.web_analytics",
"products.workflows",
]
@@ -459,6 +460,13 @@ depends_on = [
]
layer = "modules"
+[[modules]]
+path = "products.warehouse_sources_queue"
+depends_on = [
+ "posthog",
+]
+layer = "modules"
+
[[modules]]
path = "products.web_analytics"
depends_on = [