Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ws): make pipeline v3 lock release and consumer connections self-healing (#62873)

estefaniac0d3a2c6a627
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index f1ab3303a502..3c417e54d9d3 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -1,6 +1,8 @@
from collections.abc import Callable
from typing import Any, Literal
+from django.db import close_old_connections
+
import s3fs
import pyarrow as pa
import deltalake as deltalake
@@ -321,6 +323,9 @@ def _mark_job_failed(export_signal: ExportSignalMessage, error: Exception) -> No
def process_message(message: Any, progress_callback: Callable[[], None] | None = None) -> None:
export_signal = ExportSignalMessage.from_dict(message)
+ # Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.
+ close_old_connections()
+
# Clear cached S3FileSystem instances to avoid reusing sessions bound to a
# previously closed event loop (async_to_sync creates/destroys loops).
s3fs.S3FileSystem.clear_instance_cache()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 3aaff4f8e7c6..a4d309439153 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -17,11 +17,14 @@ from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any
+from django.db import close_old_connections
+
import psycopg
import structlog
from asgiref.sync import sync_to_async
from posthog.exceptions_capture import capture_exception
+from posthog.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
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,
@@ -32,6 +35,7 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics
POLL_DURATION_SECONDS,
RECOVERY_SWEEPS_TOTAL,
RUNS_FAILED_TOTAL,
+ RUNS_RECONCILED_TOTAL,
)
from posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock import release_v3_pipeline_lock
@@ -48,6 +52,11 @@ RECOVERY_INTERVAL_SECONDS = 30.0
RETRY_BACKOFF_BASE_SECONDS = 15
HEARTBEAT_INTERVAL_SECONDS = 5.0
+# Reconcile sweep: catch runs whose queue batch failed but whose ExternalDataJob was left non-terminal.
+RECONCILE_INTERVAL_SECONDS = 300.0
+RECONCILE_GRACE_SECONDS = 120 # don't race a _fail_run that is still in flight
+RECONCILE_LOOKBACK_SECONDS = 6 * 60 * 60 # keep the queue scan cheap
+
@dataclass
class ConsumerConfig:
@@ -64,6 +73,10 @@ class ConsumerConfig:
recovery_interval_seconds: float = RECOVERY_INTERVAL_SECONDS
retry_backoff_base_seconds: int = RETRY_BACKOFF_BASE_SECONDS
recovery_grace_seconds: int | None = None
+ reconcile_interval_seconds: float = RECONCILE_INTERVAL_SECONDS
+ reconcile_grace_seconds: int = RECONCILE_GRACE_SECONDS
+ reconcile_lookback_seconds: int = RECONCILE_LOOKBACK_SECONDS
+ reconcile_limit: int = 100
def __post_init__(self) -> None:
if self.recovery_grace_seconds is None:
@@ -91,21 +104,53 @@ class BatchConsumer:
self._shutdown = asyncio.Event()
self._conn: psycopg.AsyncConnection[Any] | None = None
self._recovery_conn: psycopg.AsyncConnection[Any] | None = None
+ # Serialize reconnects: concurrent groups all hit _ensure_*_conn on a bounce; without a lock each would dial its own connection and orphan all but the last.
+ self._main_conn_lock = asyncio.Lock()
+ self._recovery_conn_lock = asyncio.Lock()
self._recovery_task: asyncio.Task[None] | None = None
self._heartbeat_task: asyncio.Task[None] | None = None
+ # Monotonic stamp of the last reconcile sweep; runs inside the recovery loop so both share one connection.
+ self._last_reconcile_monotonic = 0.0
+
+ async def _connect(self) -> psycopg.AsyncConnection[Any]:
+ return await psycopg.AsyncConnection.connect(
+ self._config.database_url,
+ autocommit=True,
+ )
+
+ async def _ensure_main_conn(self) -> psycopg.AsyncConnection[Any]:
+ """Return the main queue connection, reconnecting if a failover/pgbouncer bounce dropped it."""
+ if self._conn is not None and not self._conn.closed and not self._conn.broken:
+ return self._conn
+ async with self._main_conn_lock:
+ # Re-check under the lock: another coroutine may have already reconnected while we waited.
+ if self._conn is None or self._conn.closed or self._conn.broken:
+ logger.warning("queue_db_main_connection_reconnecting")
+ self._conn = await self._connect()
+ return self._conn
+
+ async def _ensure_recovery_conn(self) -> psycopg.AsyncConnection[Any]:
+ """Return the recovery/reconcile connection, reconnecting so a dropped one can't disable the sweeps forever."""
+ if self._recovery_conn is not None and not self._recovery_conn.closed and not self._recovery_conn.broken:
+ return self._recovery_conn
+ async with self._recovery_conn_lock:
+ if self._recovery_conn is None or self._recovery_conn.closed or self._recovery_conn.broken:
+ logger.warning("queue_db_recovery_connection_reconnecting")
+ self._recovery_conn = await self._connect()
+ return self._recovery_conn
+
+ async def _wait_or_shutdown(self, timeout: float) -> None:
+ try:
+ await asyncio.wait_for(self._shutdown.wait(), timeout=timeout)
+ except TimeoutError:
+ pass
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,
- )
+ self._conn = await self._connect()
+ self._recovery_conn = await self._connect()
logger.info(
"batch_consumer_started",
@@ -124,22 +169,24 @@ class BatchConsumer:
self._health_reporter()
poll_start = time.monotonic()
- batches = await BatchQueue.get_unprocessed_and_lock(
- self._conn,
- limit=self._config.poll_limit,
- retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
- )
+ try:
+ conn = await self._ensure_main_conn()
+ batches = await BatchQueue.get_unprocessed_and_lock(
+ conn,
+ limit=self._config.poll_limit,
+ retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
+ )
+ except psycopg.OperationalError as e:
+ # Queue DB unreachable — keep the pod alive; the next iteration reconnects.
+ logger.exception("poll_failed_queue_db_unreachable")
+ capture_exception(e)
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
+ continue
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
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
continue
groups = _group_by_key(batches)
@@ -168,6 +215,8 @@ class BatchConsumer:
) -> None:
"""Process all batches for a (team_id, schema_id) sequentially, then unlock."""
team_id, schema_id = key
+ # Unlock on the session that acquired the advisory locks, even if a reconnect swaps self._conn mid-group.
+ lock_conn = self._conn
await self._semaphore.acquire()
try:
for batch in batches:
@@ -181,7 +230,19 @@ class BatchConsumer:
remaining=len(batches) - batches.index(batch),
)
break
- succeeded = await self._process_single(batch)
+ try:
+ succeeded = await self._process_single(batch)
+ except Exception as e:
+ # A queue-DB write failing mid-batch (e.g. stale conn after a bounce) must cost this group, not the pod.
+ logger.exception(
+ "process_single_unhandled_error",
+ team_id=team_id,
+ external_data_schema_id=schema_id,
+ batch_id=batch.id,
+ batch_index=batch.batch_index,
+ )
+ capture_exception(e)
+ succeeded = False
if not succeeded:
# Stop processing sibling batches in this group
logger.info(
@@ -195,8 +256,17 @@ class BatchConsumer:
break
finally:
self._semaphore.release()
- assert self._conn is not None
- await BatchQueue.unlock_for_batches(self._conn, batches=batches)
+ try:
+ assert lock_conn is not None
+ await BatchQueue.unlock_for_batches(lock_conn, batches=batches)
+ except Exception as e:
+ # A dead session already released its locks server-side; don't crash every concurrent group.
+ logger.exception(
+ "unlock_for_batches_failed",
+ team_id=team_id,
+ external_data_schema_id=schema_id,
+ )
+ capture_exception(e)
async def _process_single(self, batch: PendingBatch) -> bool:
"""Increment attempt, check max retries, then process the batch.
@@ -204,8 +274,6 @@ class BatchConsumer:
Binds per-batch contextvars so every downstream log line (including loader calls)
routes to log_entries under the right schema/workflow.
"""
- assert self._conn is not None
-
team_id = str(batch.team_id)
schema_id = batch.schema_id
attempt = batch.latest_attempt + 1
@@ -255,8 +323,6 @@ class BatchConsumer:
structlog.contextvars.unbind_contextvars(*bound_keys)
async def _process_single_inner(self, batch: PendingBatch, attempt: int, team_id: str, schema_id: str) -> bool:
- assert self._conn is not None
-
# Check before we even try — if already at max, fail the whole run.
if attempt > self._config.max_attempts:
logger.error(
@@ -282,7 +348,7 @@ class BatchConsumer:
# Pre-increment: if we OOM here, recovery sees attempt=N+1
# and knows this attempt was consumed.
await BatchQueue.update_status(
- self._conn,
+ await self._ensure_main_conn(),
batch_id=batch.id,
job_state=SourceBatchStatus.State.EXECUTING,
attempt=attempt,
@@ -295,7 +361,7 @@ class BatchConsumer:
BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).observe(duration)
await BatchQueue.update_status(
- self._conn,
+ await self._ensure_main_conn(),
batch_id=batch.id,
job_state=SourceBatchStatus.State.SUCCEEDED,
attempt=attempt,
@@ -322,6 +388,7 @@ class BatchConsumer:
batch_index=batch.batch_index,
attempt=attempt,
)
+ capture_exception(e)
await self._fail_run(batch, reason=f"max retries exceeded: {e}")
else:
logger.warning(
@@ -332,7 +399,7 @@ class BatchConsumer:
error=str(e),
)
await BatchQueue.update_status(
- self._conn,
+ await self._ensure_main_conn(),
batch_id=batch.id,
job_state=SourceBatchStatus.State.WAITING_RETRY,
attempt=attempt,
@@ -346,18 +413,26 @@ class BatchConsumer:
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
+ """Fail all pending batches in this run and mark the ExternalDataJob as failed; each step is isolated so a failure can't crash the consumer."""
+ conn = conn or await self._ensure_main_conn()
- await BatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)
- RUNS_FAILED_TOTAL.inc()
+ try:
+ await BatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)
+ RUNS_FAILED_TOTAL.inc()
+ except Exception as e:
+ logger.exception("fail_run_queue_update_failed", batch_id=batch.id, run_uuid=batch.run_uuid)
+ capture_exception(e)
- await sync_to_async(_update_job_status_to_failed)(
- job_id=batch.job_id,
- team_id=batch.team_id,
- error=reason,
- )
+ try:
+ await sync_to_async(_update_job_status_to_failed)(
+ job_id=batch.job_id,
+ team_id=batch.team_id,
+ error=reason,
+ )
+ except Exception as e:
+ # Leave the job for the reconcile sweep rather than crashing the consumer.
+ logger.exception("fail_run_job_status_update_failed", job_id=batch.job_id, run_uuid=batch.run_uuid)
+ capture_exception(e)
workflow_run_id = batch.metadata.get("workflow_run_id")
if workflow_run_id:
@@ -392,8 +467,69 @@ class BatchConsumer:
try:
await self._recovery_sweep()
- except Exception:
+ except Exception as e:
logger.exception("recovery_sweep_error")
+ capture_exception(e)
+
+ now = time.monotonic()
+ if now - self._last_reconcile_monotonic >= self._config.reconcile_interval_seconds:
+ self._last_reconcile_monotonic = now
+ try:
+ await self._reconcile_failed_runs()
+ except Exception as e:
+ logger.exception("reconcile_sweep_error")
+ capture_exception(e)
+
+ async def _reconcile_failed_runs(self) -> None:
+ """Mark ExternalDataJobs Failed when their run has a failed queue batch but the app-DB write never landed."""
+ conn = await self._ensure_recovery_conn()
+
+ refs = await BatchQueue.get_failed_runs(
+ conn,
+ grace_seconds=self._config.reconcile_grace_seconds,
+ lookback_seconds=self._config.reconcile_lookback_seconds,
+ limit=self._config.reconcile_limit,
+ )
+ for ref in refs:
+ try:
+ reconciled = await sync_to_async(_mark_job_failed_if_not_terminal)(
+ job_id=ref.job_id,
+ team_id=ref.team_id,
+ error=ref.reason or "run failed (reconciled from queue)",
+ )
+ except Exception as e:
+ logger.exception("reconcile_job_status_update_failed", job_id=ref.job_id, run_uuid=ref.run_uuid)
+ capture_exception(e)
+ continue
+
+ if not reconciled:
+ continue # job was already terminal — nothing to reconcile
+
+ RUNS_RECONCILED_TOTAL.inc()
+ logger.warning(
+ "run_reconciled_to_failed",
+ job_id=ref.job_id,
+ run_uuid=ref.run_uuid,
+ team_id=ref.team_id,
+ external_data_schema_id=ref.schema_id,
+ )
+
+ # Release the V3 pipeline lock too, otherwise it blocks the schema's next sync until its TTL expires.
+ if ref.workflow_run_id:
+ try:
+ await sync_to_async(release_v3_pipeline_lock)(
+ team_id=ref.team_id,
+ schema_id=ref.schema_id,
+ token=ref.workflow_run_id,
+ )
+ except Exception as e:
+ logger.error(
+ "failed_to_release_v3_pipeline_lock",
+ job_id=ref.job_id,
+ schema_id=ref.schema_id,
+ exc_info=True,
+ )
+ capture_exception(e)
async def _heartbeat_loop(self) -> None:
"""Report liveness on a fixed cadence, independent of batch processing."""
@@ -410,8 +546,7 @@ class BatchConsumer:
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
+ conn = await self._ensure_recovery_conn()
grace_seconds = self._config.recovery_grace_seconds
assert grace_seconds is not None
@@ -492,7 +627,12 @@ class BatchConsumer:
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()")
+ try:
+ await self._conn.execute("SELECT pg_advisory_unlock_all()")
+ except Exception as e:
+ # A broken session already lost its advisory locks; still close below.
+ logger.exception("advisory_unlock_all_failed_on_shutdown")
+ capture_exception(e)
await self._conn.close()
logger.info("batch_consumer_stopped")
@@ -506,6 +646,9 @@ def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> No
from products.data_warehouse.backend.external_data_source.jobs import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+ # Drop stale app-DB connections so this write reconnects instead of leaving the job stuck in Running.
+ close_old_connections()
+
existing = ExternalDataJob.objects.filter(id=job_id, team_id=team_id, status=ExternalDataJob.Status.FAILED).first()
if existing is not None:
return
@@ -519,6 +662,20 @@ def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> No
)
+def _mark_job_failed_if_not_terminal(*, job_id: str, team_id: int, error: str) -> bool:
+ """Mark a non-terminal ExternalDataJob Failed; returns True if it transitioned (terminal jobs are a no-op)."""
+ from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+
+ close_old_connections()
+
+ job = ExternalDataJob.objects.filter(id=job_id, team_id=team_id).only("status").first()
+ if job is None or job.status in TERMINAL_JOB_STATUSES:
+ return False
+
+ _update_job_status_to_failed(job_id=job_id, team_id=team_id, error=error)
+ return True
+
+
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)
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index 8956b58009d2..02575cfc1834 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -93,6 +93,18 @@ class PendingBatch:
}
+@dataclass(frozen=True, slots=True)
+class FailedRunRef:
+ """Identity of a run with a ``failed`` queue batch, used by the reconcile sweep to fail its ExternalDataJob."""
+
+ run_uuid: str
+ job_id: str
+ team_id: int
+ schema_id: str
+ workflow_run_id: str | None
+ reason: str | None
+
+
class BatchQueue:
"""
Async interface to the Postgres batch queue tables. Each method runs
@@ -372,6 +384,55 @@ class BatchQueue:
)
return cursor.rowcount or 0
+ @staticmethod
+ async def get_failed_runs(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ grace_seconds: int,
+ lookback_seconds: int,
+ limit: int,
+ ) -> list[FailedRunRef]:
+ """Return one ref per run with a ``failed`` batch older than ``grace_seconds``, within ``lookback_seconds``.
+
+ Ordered by latest failure first so fresh failures still land in the window when
+ already-reconciled runs outnumber ``limit`` within the lookback.
+ """
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(
+ f"""
+ SELECT run_uuid, job_id, team_id, schema_id, metadata, error_response
+ FROM (
+ SELECT DISTINCT ON (b.run_uuid)
+ b.run_uuid, b.job_id, b.team_id, b.schema_id, b.metadata, s.error_response,
+ s.created_at AS failed_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 = 'failed'
+ AND s.created_at <= now() - make_interval(secs => %(grace)s)
+ AND s.created_at >= now() - make_interval(secs => %(lookback)s)
+ ORDER BY b.run_uuid, s.created_at DESC
+ ) failed_runs
+ ORDER BY failed_at DESC
+ LIMIT %(limit)s
+ """,
+ {"grace": grace_seconds, "lookback": lookback_seconds, "limit": limit},
+ )
+ rows = await cur.fetchall()
+
+ return [
+ FailedRunRef(
+ run_uuid=row["run_uuid"],
+ job_id=row["job_id"],
+ team_id=row["team_id"],
+ schema_id=row["schema_id"],
+ workflow_run_id=(row["metadata"] or {}).get("workflow_run_id"),
+ reason=(row["error_response"] or {}).get("error"),
+ )
+ for row in rows
+ ]
+
@staticmethod
async def unlock_for_batches(
conn: psycopg.AsyncConnection[Any],
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
index 7f5f83884f5d..3fb562b25bfa 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py
@@ -47,3 +47,9 @@ RECOVERY_SWEEPS_TOTAL = Counter(
"Total recovery sweeps executed",
labelnames=["outcome"],
)
+
+RUNS_RECONCILED_TOTAL = Counter(
+ "warehouse_pg_consumer_runs_reconciled_total",
+ "Runs whose ExternalDataJob was left non-terminal despite a failed queue batch and "
+ "was reconciled to Failed by the reconcile sweep",
+)
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index a04f107a9a1b..b36c0939d29e 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -4,6 +4,7 @@ from typing import Any
import pytest
from unittest.mock import AsyncMock, patch
+import psycopg
import structlog
from posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState
@@ -12,7 +13,7 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer
ConsumerConfig,
_group_by_key,
)
-from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch
+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import FailedRunRef, PendingBatch
from products.warehouse_sources_queue.backend.models import SourceBatchStatus
@@ -44,6 +45,19 @@ def _make_batch(**overrides: Any) -> PendingBatch:
return PendingBatch(**defaults)
+def _make_failed_run_ref(**overrides: Any) -> FailedRunRef:
+ defaults: dict[str, Any] = {
+ "run_uuid": "run-1",
+ "job_id": "job-1",
+ "team_id": 1,
+ "schema_id": "schema-1",
+ "workflow_run_id": "wf-1",
+ "reason": "max retries exceeded: the connection is closed",
+ }
+ defaults.update(overrides)
+ return FailedRunRef(**defaults)
+
+
def _make_consumer(max_attempts: int = 3, **kwargs) -> BatchConsumer:
config = ConsumerConfig(
database_url="postgres://unused:unused@localhost/unused",
@@ -52,11 +66,19 @@ def _make_consumer(max_attempts: int = 3, **kwargs) -> BatchConsumer:
)
mock_process = AsyncMock()
consumer = BatchConsumer(config=config, process_batch=mock_process)
- consumer._conn = AsyncMock()
- consumer._recovery_conn = AsyncMock()
+ consumer._conn = _make_healthy_conn()
+ consumer._recovery_conn = _make_healthy_conn()
return consumer
+def _make_healthy_conn(closed: bool = False, broken: bool = False) -> AsyncMock:
+ # closed/broken must be real booleans, otherwise _ensure_*_conn sees a dead conn and dials the fake database_url.
+ conn = AsyncMock()
+ conn.closed = closed
+ conn.broken = broken
+ return conn
+
+
class TestProcessSingle:
@pytest.mark.asyncio
async def test_success_updates_status_to_executing_then_succeeded(self):
@@ -277,6 +299,238 @@ class TestRecoverySweep:
assert "max retries exceeded" in mock_fail.call_args[1]["reason"]
+class TestFailRun:
+ @pytest.mark.asyncio
+ async def test_does_not_raise_when_job_status_update_fails(self):
+ # A dropped app-DB connection while marking the job Failed must not propagate out of _fail_run.
+ consumer = _make_consumer()
+ batch = _make_batch()
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ ) as mock_fail_run,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
+ side_effect=Exception("the connection is closed"),
+ ),
+ ):
+ await consumer._fail_run(batch, reason="max retries exceeded: the connection is closed")
+
+ mock_fail_run.assert_called_once() # queue batches still marked failed
+
+ @pytest.mark.asyncio
+ async def test_attempts_job_status_update_even_when_queue_update_fails(self):
+ consumer = _make_consumer()
+ batch = _make_batch()
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.fail_run",
+ new_callable=AsyncMock,
+ side_effect=Exception("the connection is closed"),
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
+ ) as mock_status,
+ ):
+ await consumer._fail_run(batch, reason="boom")
+
+ mock_status.assert_called_once()
+
+
+class TestReconcileFailedRuns:
+ @pytest.mark.asyncio
+ async def test_marks_non_terminal_run_failed(self):
+ consumer = _make_consumer()
+ ref = _make_failed_run_ref()
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[ref],
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ return_value=True,
+ ) as mock_mark,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.release_v3_pipeline_lock",
+ ) as mock_release,
+ ):
+ await consumer._reconcile_failed_runs()
+
+ mock_mark.assert_called_once_with(job_id=ref.job_id, team_id=ref.team_id, error=ref.reason)
+ mock_release.assert_called_once_with(team_id=ref.team_id, schema_id=ref.schema_id, token=ref.workflow_run_id)
+
+ @pytest.mark.asyncio
+ async def test_skips_already_terminal_run(self):
+ consumer = _make_consumer()
+ ref = _make_failed_run_ref()
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[ref],
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ return_value=False,
+ ) as mock_mark,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.release_v3_pipeline_lock",
+ ) as mock_release,
+ ):
+ await consumer._reconcile_failed_runs()
+
+ mock_mark.assert_called_once() # no-op for an already-terminal job, no error
+ mock_release.assert_not_called() # don't release the lock for a job we didn't reconcile
+
+ @pytest.mark.asyncio
+ async def test_continues_after_error_on_one_ref(self):
+ consumer = _make_consumer()
+ ref_a = _make_failed_run_ref(run_uuid="run-a", job_id="job-a")
+ ref_b = _make_failed_run_ref(run_uuid="run-b", job_id="job-b")
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_failed_runs",
+ new_callable=AsyncMock,
+ return_value=[ref_a, ref_b],
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ side_effect=[Exception("db down"), True],
+ ) as mock_mark,
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.release_v3_pipeline_lock",
+ ),
+ ):
+ await consumer._reconcile_failed_runs()
+
+ assert mock_mark.call_count == 2 # error on the first ref does not abort the sweep
+
+
+class TestConnectionRecovery:
+ @pytest.mark.parametrize(
+ "closed, broken, expect_reconnect",
+ [
+ (False, False, False),
+ (True, False, True),
+ (False, True, True),
+ ],
+ ids=["healthy", "closed", "broken"],
+ )
+ @pytest.mark.asyncio
+ async def test_ensure_main_conn_reconnects_only_when_dead(self, closed, broken, expect_reconnect):
+ consumer = _make_consumer()
+ original = _make_healthy_conn(closed=closed, broken=broken)
+ consumer._conn = original
+ fresh = _make_healthy_conn()
+
+ with patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh) as mock_connect:
+ conn = await consumer._ensure_main_conn()
+
+ if expect_reconnect:
+ mock_connect.assert_awaited_once()
+ assert conn is fresh
+ else:
+ mock_connect.assert_not_awaited()
+ assert conn is original
+
+ @pytest.mark.asyncio
+ async def test_concurrent_ensure_main_conn_dials_only_once(self):
+ # All concurrent groups hitting a dead conn must share one reconnect, not dial N connections.
+ consumer = _make_consumer()
+ consumer._conn = _make_healthy_conn(closed=True)
+ fresh = _make_healthy_conn()
+
+ async def slow_connect() -> AsyncMock:
+ await asyncio.sleep(0) # yield so the other coroutines reach the check while we're "dialing"
+ return fresh
+
+ with patch.object(consumer, "_connect", side_effect=slow_connect) as mock_connect:
+ conns = await asyncio.gather(*[consumer._ensure_main_conn() for _ in range(5)])
+
+ assert mock_connect.call_count == 1
+ assert all(conn is fresh for conn in conns)
+
+ @pytest.mark.asyncio
+ async def test_ensure_recovery_conn_reconnects_when_dead(self):
+ consumer = _make_consumer()
+ consumer._recovery_conn = _make_healthy_conn(closed=True)
+ fresh = _make_healthy_conn()
+
+ with patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh) as mock_connect:
+ conn = await consumer._ensure_recovery_conn()
+
+ mock_connect.assert_awaited_once()
+ assert conn is fresh
+
+ @pytest.mark.asyncio
+ async def test_process_group_does_not_raise_when_unlock_fails(self):
+ # An unlock failure must not crash the gather() running every concurrent group.
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+
+ 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,
+ side_effect=Exception("the connection is closed"),
+ ),
+ ):
+ await consumer._process_group((1, "schema-1"), [_make_batch()])
+
+ @pytest.mark.asyncio
+ async def test_process_group_does_not_raise_when_process_single_raises(self):
+ # An unguarded queue-DB write blowing up mid-batch must cost the group, not crash the gather()/pod.
+ consumer = _make_consumer()
+
+ with (
+ patch.object(
+ consumer,
+ "_process_single",
+ new_callable=AsyncMock,
+ side_effect=psycopg.OperationalError("the connection is closed"),
+ ) as mock_single,
+ 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"), [_make_batch(), _make_batch(batch_index=1)])
+
+ mock_single.assert_awaited_once() # group halts after the failed batch
+ mock_unlock.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_recovery_sweep_uses_reconnected_conn(self):
+ consumer = _make_consumer()
+ consumer._recovery_conn = _make_healthy_conn(closed=True)
+ fresh = _make_healthy_conn()
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.get_stale_executing",
+ new_callable=AsyncMock,
+ return_value=[],
+ ) as mock_get_stale,
+ ):
+ await consumer._recovery_sweep()
+
+ mock_get_stale.assert_awaited_once()
+ assert mock_get_stale.call_args[0][0] is fresh
+
+
class TestGroupByKey:
def test_groups_by_team_and_schema(self):
batches = [
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
index b3e9c52798d0..148f8da68799 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/sync_lock.py
@@ -76,6 +76,23 @@ def acquire_v3_pipeline_lock(team_id: int, schema_id: str, token: str) -> bool:
return False
+def get_v3_pipeline_lock_holder(team_id: int, schema_id: str) -> str | None:
+ """Return the token currently holding the lock, or None if unheld or Redis is unavailable."""
+ with _get_redis_client() as client:
+ if client is None:
+ return None
+
+ try:
+ holder = client.get(_lock_key(team_id, schema_id))
+ if holder is None:
+ return None
+ return holder.decode() if isinstance(holder, bytes) else str(holder)
+ except Exception as e:
+ logger.warning("v3_pipeline_lock_get_holder_error", error=str(e), team_id=team_id, schema_id=schema_id)
+ capture_exception(e)
+ return None
+
+
def release_v3_pipeline_lock(team_id: int, schema_id: str, token: str) -> bool:
"""Release the lock only if held by this token. Fail-silent on errors."""
with _get_redis_client() as client:
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py
index 211a7403d176..0d30c96b27d6 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/test_sync_lock.py
@@ -5,6 +5,7 @@ from posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
LOCK_TTL_SECONDS,
_lock_key,
acquire_v3_pipeline_lock,
+ get_v3_pipeline_lock_holder,
release_v3_pipeline_lock,
)
@@ -51,6 +52,42 @@ class TestAcquireV3PipelineLock:
assert acquire_v3_pipeline_lock(1, "s-1", "tok-1") is False
+class TestGetV3PipelineLockHolder:
+ @pytest.mark.parametrize(
+ "get_return, expected",
+ [
+ (b"tok-1", "tok-1"),
+ ("tok-1", "tok-1"),
+ (None, None),
+ ],
+ ids=["bytes_token", "str_token", "unheld"],
+ )
+ @patch("posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock._get_redis_client")
+ def test_holder_result(self, mock_ctx: MagicMock, get_return: bytes | str | None, expected: str | None) -> None:
+ mock_redis = MagicMock()
+ mock_redis.get.return_value = get_return
+ mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_redis)
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ assert get_v3_pipeline_lock_holder(1, "s-1") == expected
+
+ @patch("posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock._get_redis_client")
+ def test_returns_none_on_redis_unavailable(self, mock_ctx: MagicMock) -> None:
+ mock_ctx.return_value.__enter__ = MagicMock(return_value=None)
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ assert get_v3_pipeline_lock_holder(1, "s-1") is None
+
+ @patch("posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock._get_redis_client")
+ def test_returns_none_on_get_exception(self, mock_ctx: MagicMock) -> None:
+ mock_redis = MagicMock()
+ mock_redis.get.side_effect = Exception("connection lost")
+ mock_ctx.return_value.__enter__ = MagicMock(return_value=mock_redis)
+ mock_ctx.return_value.__exit__ = MagicMock(return_value=False)
+
+ assert get_v3_pipeline_lock_holder(1, "s-1") is None
+
+
class TestReleaseV3PipelineLock:
@pytest.mark.parametrize(
"eval_return, expected",
diff --git a/posthog/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/posthog/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index 882b29a70e8a..a0bc8bc18a15 100644
--- a/posthog/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/posthog/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -1,5 +1,6 @@
import uuid
import dataclasses
+from typing import Any
from django.db import close_old_connections
@@ -7,12 +8,15 @@ from structlog.contextvars import bind_contextvars
from temporalio import activity
from posthog.temporal.common.logger import get_logger
+from posthog.temporal.data_imports.metrics import TERMINAL_JOB_STATUSES
from posthog.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
acquire_v3_pipeline_lock,
+ get_v3_pipeline_lock_holder,
release_v3_pipeline_lock,
)
from posthog.temporal.data_imports.workflow_activities.create_job_model import is_pipeline_v3_enabled
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
LOGGER = get_logger(__name__)
@@ -74,6 +78,8 @@ def acquire_v3_pipeline_lock_activity(inputs: AcquireV3LockActivityInputs) -> Ac
return AcquireV3LockActivityOutputs(acquired=False, token="")
acquired = acquire_v3_pipeline_lock(inputs.team_id, str(inputs.schema_id), token)
+ if not acquired:
+ acquired = _take_over_lock_if_holder_finished(inputs, token, logger)
logger.info(
"v3_pipeline_lock_acquire_result",
@@ -85,6 +91,37 @@ def acquire_v3_pipeline_lock_activity(inputs: AcquireV3LockActivityInputs) -> Ac
return AcquireV3LockActivityOutputs(acquired=acquired, token=token)
+def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, token: str, logger: Any) -> bool:
+ """Take over the lock when its holder's ExternalDataJob is terminal (run provably over); fail closed otherwise."""
+ holder = get_v3_pipeline_lock_holder(inputs.team_id, str(inputs.schema_id))
+ if holder is None:
+ # Lock vanished between SET NX and GET (released or expired) — just retry.
+ return acquire_v3_pipeline_lock(inputs.team_id, str(inputs.schema_id), token)
+
+ close_old_connections()
+ holder_job = (
+ ExternalDataJob.objects.filter(
+ team_id=inputs.team_id,
+ schema_id=inputs.schema_id,
+ workflow_run_id=holder,
+ )
+ .order_by("-created_at")
+ .only("status")
+ .first()
+ )
+ if holder_job is None or holder_job.status not in TERMINAL_JOB_STATUSES:
+ return False
+
+ logger.warning(
+ "v3_pipeline_lock_taking_over_stale_lock",
+ schema_id=str(inputs.schema_id),
+ holder_token=holder,
+ holder_job_status=holder_job.status,
+ )
+ release_v3_pipeline_lock(inputs.team_id, str(inputs.schema_id), holder)
+ return acquire_v3_pipeline_lock(inputs.team_id, str(inputs.schema_id), token)
+
+
@activity.defn
def release_v3_pipeline_lock_activity(inputs: ReleaseV3LockActivityInputs) -> None:
bind_contextvars(team_id=inputs.team_id)
diff --git a/posthog/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/posthog/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index 289d81d5b9f4..4527e149f786 100644
--- a/posthog/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/posthog/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -79,6 +79,7 @@ class TestAcquireV3PipelineLockActivity:
[True, False],
ids=["lock_free", "lock_held"],
)
+ @patch(f"{MODULE}._take_over_lock_if_holder_finished", return_value=False)
@patch(f"{MODULE}.acquire_v3_pipeline_lock")
@patch(f"{MODULE}.activity")
@patch(f"{MODULE}.bind_contextvars")
@@ -87,6 +88,7 @@ class TestAcquireV3PipelineLockActivity:
_bind: MagicMock,
mock_activity: MagicMock,
mock_acquire: MagicMock,
+ mock_take_over: MagicMock,
lock_acquired: bool,
) -> None:
mock_activity.info.return_value.workflow_run_id = WORKFLOW_RUN_ID
@@ -97,6 +99,27 @@ class TestAcquireV3PipelineLockActivity:
assert result.acquired is lock_acquired
assert result.token == WORKFLOW_RUN_ID
mock_acquire.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), WORKFLOW_RUN_ID)
+ if lock_acquired:
+ mock_take_over.assert_not_called()
+ else:
+ mock_take_over.assert_called_once()
+
+ @patch(f"{MODULE}._take_over_lock_if_holder_finished", return_value=True)
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock", return_value=False)
+ @patch(f"{MODULE}.activity")
+ @patch(f"{MODULE}.bind_contextvars")
+ def test_take_over_result_wins_when_holder_finished(
+ self,
+ _bind: MagicMock,
+ mock_activity: MagicMock,
+ _mock_acquire: MagicMock,
+ _mock_take_over: MagicMock,
+ ) -> None:
+ mock_activity.info.return_value.workflow_run_id = WORKFLOW_RUN_ID
+
+ result = acquire_v3_pipeline_lock_activity(AcquireV3LockActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID))
+
+ assert result.acquired is True
@patch(f"{MODULE}.activity")
@patch(f"{MODULE}.bind_contextvars")
@@ -113,6 +136,80 @@ class TestAcquireV3PipelineLockActivity:
assert result.token == ""
+class TestTakeOverStaleLock:
+ HOLDER_TOKEN = "stale-run-999"
+
+ def _run(self) -> bool:
+ from posthog.temporal.data_imports.workflow_activities.acquire_v3_lock import _take_over_lock_if_holder_finished
+
+ inputs = AcquireV3LockActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID)
+ return _take_over_lock_if_holder_finished(inputs, WORKFLOW_RUN_ID, MagicMock())
+
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock", return_value=True)
+ @patch(f"{MODULE}.get_v3_pipeline_lock_holder", return_value=None)
+ def test_retries_acquire_when_lock_vanished(self, _holder: MagicMock, mock_acquire: MagicMock) -> None:
+ assert self._run() is True
+ mock_acquire.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), WORKFLOW_RUN_ID)
+
+ @pytest.mark.parametrize(
+ "holder_status, expect_taken",
+ [
+ ("Completed", True),
+ ("Failed", True),
+ ("Running", False),
+ ],
+ ids=["holder_completed", "holder_failed", "holder_still_running"],
+ )
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock", return_value=True)
+ @patch(f"{MODULE}.release_v3_pipeline_lock")
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.get_v3_pipeline_lock_holder", return_value=HOLDER_TOKEN)
+ def test_takes_over_only_when_holder_job_terminal(
+ self,
+ _holder: MagicMock,
+ _close: MagicMock,
+ mock_job_model: MagicMock,
+ mock_release: MagicMock,
+ mock_acquire: MagicMock,
+ holder_status: str,
+ expect_taken: bool,
+ ) -> None:
+ holder_job = MagicMock()
+ holder_job.status = holder_status
+ mock_job_model.objects.filter.return_value.order_by.return_value.only.return_value.first.return_value = (
+ holder_job
+ )
+
+ assert self._run() is expect_taken
+ if expect_taken:
+ mock_release.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), self.HOLDER_TOKEN)
+ mock_acquire.assert_called_once_with(TEAM_ID, str(SCHEMA_ID), WORKFLOW_RUN_ID)
+ else:
+ mock_release.assert_not_called()
+ mock_acquire.assert_not_called()
+
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock")
+ @patch(f"{MODULE}.release_v3_pipeline_lock")
+ @patch(f"{MODULE}.ExternalDataJob")
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.get_v3_pipeline_lock_holder", return_value=HOLDER_TOKEN)
+ def test_fails_closed_when_holder_has_no_job_yet(
+ self,
+ _holder: MagicMock,
+ _close: MagicMock,
+ mock_job_model: MagicMock,
+ mock_release: MagicMock,
+ mock_acquire: MagicMock,
+ ) -> None:
+ # The holder may be between lock acquisition and job creation — don't steal.
+ mock_job_model.objects.filter.return_value.order_by.return_value.only.return_value.first.return_value = None
+
+ assert self._run() is False
+ mock_release.assert_not_called()
+ mock_acquire.assert_not_called()
+
+
class TestReleaseV3PipelineLockActivity:
@patch(f"{MODULE}.release_v3_pipeline_lock")
@patch(f"{MODULE}.bind_contextvars")