:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ws): protect against advisory lock zombie consumers (#65122)
estefaniaa6b4a51b7c3c
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex a67d13ebd206..d900e0dd1e61 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -25,6 +25,7 @@ POLL_INTERVAL_SECONDS = 2.0RECOVERY_INTERVAL_SECONDS = 30.0RETRY_BACKOFF_BASE_SECONDS = 15HEARTBEAT_INTERVAL_SECONDS = 5.0+RECOVERY_GRACE_SECONDS = 300# Reconcile sweep: catch runs whose queue batch failed but whose ExternalDataJob was left non-terminal.RECONCILE_INTERVAL_SECONDS = 300.0@@ -32,6 +33,10 @@ RECONCILE_GRACE_SECONDS = 120 # don't race a _fail_run that is still in flightRECONCILE_LOOKBACK_SECONDS = 6 * 60 * 60 # keep the queue scan cheap+class OwnershipLostError(Exception):+ """Raised when the advisory lock for a (team_id, schema_id) group is no longer held."""++@dataclassclass BatchConsumerConfig:"""Tuning knobs for the batch consumer."""@@ -58,7 +63,7 @@ class BatchConsumerConfig:def __post_init__(self) -> None:if self.recovery_grace_seconds is None:- self.recovery_grace_seconds = int(self.recovery_interval_seconds)+ self.recovery_grace_seconds = RECOVERY_GRACE_SECONDSclass BatchConsumerAdapter(Protocol):@@ -109,11 +114,20 @@ class BatchConsumerAdapter(Protocol):reason: str,) -> None: ...+ async def verify_advisory_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> bool: ...+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],*,grace_seconds: int,+ keep_locks: bool = False,) -> list[PendingBatch]: ...async def reconcile_failed_runs(@@ -264,7 +278,7 @@ class BatchConsumer:async def _process_group(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:team_id, schema_id = key- # Unlock on the session that acquired the advisory locks, even if a reconnect swaps self._conn mid-group.+ # Pin the connection that holds the advisory locks so status writes stay on the same session.lock_conn = self._connawait self._semaphore.acquire()try:@@ -278,7 +292,14 @@ class BatchConsumer:)breaktry:- succeeded = await self._process_single(batch)+ succeeded = await self._process_single(batch, lock_conn=lock_conn)+ except OwnershipLostError:+ logger.warning(+ self._event("ownership_lost_abandoning_group"),+ team_id=team_id,+ schema_id=schema_id,+ )+ breakexcept 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(@@ -292,7 +313,7 @@ class BatchConsumer:succeeded = Falseif not succeeded:# Stop processing sibling batches in this run once one fails or- # enters waiting_retry — later batches depend on earlier ones.+ # enters waiting_retry -- later batches depend on earlier ones.logger.info(self._event("group_halted_by_non_success"),team_id=team_id,@@ -315,7 +336,47 @@ class BatchConsumer:)capture_exception(e)- async def _process_single(self, batch: PendingBatch) -> bool:+ async def _get_status_conn(self, lock_conn: psycopg.AsyncConnection[Any] | None) -> psycopg.AsyncConnection[Any]:+ """Return the connection to use for status writes, preferring the lock session."""+ if lock_conn is not None:+ if lock_conn.closed or lock_conn.broken:+ raise OwnershipLostError("lock session is dead")+ return lock_conn+ return await self._ensure_main_conn()++ async def _verify_ownership(self, lock_conn: psycopg.AsyncConnection[Any] | None, batch: PendingBatch) -> None:+ """Raise OwnershipLostError if this session no longer holds the advisory lock."""+ if lock_conn is None:+ return+ try:+ owns = await self._adapter.verify_advisory_lock(lock_conn, team_id=batch.team_id, schema_id=batch.schema_id)+ except Exception as e:+ raise OwnershipLostError("lock verification query failed") from e+ if not owns:+ raise OwnershipLostError(f"advisory lock lost for ({batch.team_id}, {batch.schema_id})")++ async def _batch_heartbeat(+ self,+ lock_conn: psycopg.AsyncConnection[Any],+ batch: PendingBatch,+ attempt: int,+ ) -> None:+ """Re-insert EXECUTING status periodically to prevent premature recovery."""+ interval = max((self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS) / 3, 10.0)+ while True:+ await asyncio.sleep(interval)+ try:+ await self._verify_ownership(lock_conn, batch)+ await self._adapter.update_status(+ lock_conn,+ batch_id=batch.id,+ job_state=self._adapter.executing_state,+ attempt=attempt,+ )+ except Exception:+ return++ async def _process_single(self, batch: PendingBatch, lock_conn: psycopg.AsyncConnection[Any] | None = None) -> bool:"""Bind per-batch log context, then process. Returns True only on success.Binds structlog contextvars so every downstream log line (including loader calls)@@ -325,9 +386,6 @@ class BatchConsumer:schema_id = batch.schema_idattempt = batch.latest_attempt + 1- # Producer (running inside a Temporal activity) stamps workflow ids into batch metadata,- # so no DB round-trip is needed here. Derive workflow_type from the workflow_id prefix so- # non-CDC syncs (regular `external-data-job`) route to the right `log_entries` source too.workflow_id = batch.metadata.get("workflow_id") or ""workflow_run_id = batch.metadata.get("workflow_run_id") or ""workflow_type = "cdc-extraction" if workflow_id.startswith("cdc-extraction-") else "external-data-job"@@ -362,14 +420,20 @@ class BatchConsumer:)self._inflight_started[batch.id] = time.monotonic()try:- return await self._process_single_inner(batch, attempt, team_id, schema_id)+ await self._verify_ownership(lock_conn, batch)+ return await self._process_single_inner(batch, attempt, team_id, schema_id, lock_conn)finally:self._inflight_started.pop(batch.id, None)- # Unbind only the keys we set so ambient context (parent logger, test setup) survives.structlog.contextvars.unbind_contextvars(*bound_keys)- async def _process_single_inner(self, batch: PendingBatch, attempt: int, team_id: str, schema_id: str) -> bool:- # Check before we even try — if already at max, fail the whole run.+ async def _process_single_inner(+ self,+ batch: PendingBatch,+ attempt: int,+ team_id: str,+ schema_id: str,+ lock_conn: psycopg.AsyncConnection[Any] | None = None,+ ) -> bool:if attempt > self._config.max_attempts:logger.error(self._event("batch_max_retries_exceeded"),@@ -380,6 +444,8 @@ class BatchConsumer:await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")return False+ status_conn = await self._get_status_conn(lock_conn)+logger.info(self._event("batch_picked_up"),batch_id=batch.id,@@ -390,19 +456,21 @@ class BatchConsumer:resource_name=batch.resource_name,)- # Pre-increment: if we OOM here, recovery sees attempt=N+1- # and knows this attempt was consumed.+ # Pre-increment: if we OOM here, recovery sees attempt=N+1 and knows this attempt was consumed.await self._adapter.update_status(- await self._ensure_main_conn(),+ status_conn,batch_id=batch.id,job_state=self._adapter.executing_state,attempt=attempt,)+ heartbeat_task: asyncio.Task[None] | None = Nonetry:start = time.monotonic()should_process = await self._adapter.should_process_batch(await self._ensure_main_conn(), batch=batch)if should_process:+ if lock_conn is not None:+ heartbeat_task = asyncio.create_task(self._batch_heartbeat(lock_conn, batch, attempt))await self._process_batch(batch)await self._adapter.after_batch_processed(await self._ensure_main_conn(), batch=batch)@@ -411,8 +479,9 @@ class BatchConsumer:duration)+ await self._verify_ownership(lock_conn, batch)await self._adapter.update_status(- await self._ensure_main_conn(),+ status_conn,batch_id=batch.id,job_state=self._adapter.succeeded_state,attempt=attempt,@@ -427,6 +496,8 @@ class BatchConsumer:duration_seconds=round(duration, 3),)return True+ except OwnershipLostError:+ raiseexcept Exception as err:self._metrics.batches_processed_total.labels(team_id=team_id, schema_id=schema_id, status="error").inc()self._metrics.batch_retry_total.labels(attempt=str(attempt), error_type=type(err).__name__).inc()@@ -448,13 +519,20 @@ class BatchConsumer:error=str(err),)await self._adapter.update_status(- await self._ensure_main_conn(),+ status_conn,batch_id=batch.id,job_state=self._adapter.waiting_retry_state,attempt=attempt,error_response={"error": str(err)[:1000]},)return False+ finally:+ if heartbeat_task is not None:+ heartbeat_task.cancel()+ try:+ await heartbeat_task+ except asyncio.CancelledError:+ passasync def _fail_run(self,@@ -554,7 +632,8 @@ class BatchConsumer:grace_seconds = self._config.recovery_grace_secondsassert grace_seconds is not None- stale = await self._adapter.get_stale_executing(conn, grace_seconds=grace_seconds)+ # Hold probe locks so a concurrent consumer can't pick up these batches mid-recovery.+ stale = await self._adapter.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=True)if not stale:self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()return@@ -573,35 +652,42 @@ class BatchConsumer:"log_source_id","attempt",)- for batch in stale:- # latest_attempt was already incremented before the crash (pre-increment in- # _process_single), so no +1 needed here.- structlog.contextvars.bind_contextvars(- team_id=batch.team_id,- external_data_schema_id=batch.schema_id,- external_data_source_id=batch.source_id,- external_data_job_id=batch.job_id,- run_uuid=batch.run_uuid,- batch_id=batch.id,- resource_name=batch.resource_name,- log_source_id=batch.schema_id,- attempt=batch.latest_attempt,- )+ try:+ for batch in stale:+ structlog.contextvars.bind_contextvars(+ team_id=batch.team_id,+ external_data_schema_id=batch.schema_id,+ external_data_source_id=batch.source_id,+ external_data_job_id=batch.job_id,+ run_uuid=batch.run_uuid,+ batch_id=batch.id,+ resource_name=batch.resource_name,+ log_source_id=batch.schema_id,+ attempt=batch.latest_attempt,+ )+ try:+ if batch.latest_attempt >= self._config.max_attempts:+ logger.warning(+ self._event("batch_recovered_max_retries_exceeded"), attempt=batch.latest_attempt+ )+ await self._fail_run(batch, reason="max retries exceeded (likely OOM)", conn=conn)+ else:+ logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)+ await self._adapter.update_status(+ conn,+ batch_id=batch.id,+ job_state=self._adapter.waiting_retry_state,+ attempt=batch.latest_attempt,+ error_response={"error": "executing timed out - pod restart or OOM"},+ )+ finally:+ structlog.contextvars.unbind_contextvars(*recovery_bound_keys)+ finally:+ # Release probe locks acquired by keep_locks=True.try:- if batch.latest_attempt >= self._config.max_attempts:- logger.warning(self._event("batch_recovered_max_retries_exceeded"), attempt=batch.latest_attempt)- await self._fail_run(batch, reason="max retries exceeded (likely OOM)", conn=conn)- else:- logger.warning(self._event("batch_recovered_for_retry"), attempt=batch.latest_attempt)- await self._adapter.update_status(- conn,- batch_id=batch.id,- job_state=self._adapter.waiting_retry_state,- attempt=batch.latest_attempt,- error_response={"error": "executing timed out — pod restart or OOM"},- )- finally:- structlog.contextvars.unbind_contextvars(*recovery_bound_keys)+ await self._adapter.unlock(conn, batches=stale)+ except Exception:+ logger.exception(self._event("recovery_sweep_unlock_failed"))def _install_signal_handlers(self) -> None:loop = asyncio.get_running_loop()diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pyindex b72154a94171..26cc670787f1 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -160,13 +160,23 @@ class DuckgresBatchConsumerAdapter:)capture_exception(e)+ async def verify_advisory_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> bool:+ return await DuckgresBatchQueue.verify_advisory_lock(conn, team_id=team_id, schema_id=schema_id)+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],*,grace_seconds: int,+ keep_locks: bool = False,) -> list[PendingBatch]:- return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)+ return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=keep_locks)async def reconcile_failed_runs(self,diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pyindex 65c9ddcac31c..10f28fbec683 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -410,12 +410,43 @@ class DuckgresBatchQueue:)return cursor.rowcount or 0+ @staticmethod+ async def verify_advisory_lock(+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> bool:+ """Check if this session still holds the advisory lock for (team_id, schema_id)."""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT EXISTS (+ SELECT 1 FROM pg_locks+ WHERE locktype = 'advisory'+ AND classid = {DUCKGRES_ADVISORY_LOCK_NAMESPACE}+ AND objid = hashtext(%(key)s)+ AND pid = pg_backend_pid()+ AND granted = true+ )+ """,+ {"key": f"{team_id}:{schema_id}"},+ )+ row = await cur.fetchone()+ return bool(row and row[0])+@staticmethodasync def get_stale_executing(conn: psycopg.AsyncConnection[Any],*,grace_seconds: int = 0,+ keep_locks: bool = False,) -> list[PendingBatch]:+ """Find batches stuck in 'executing' whose advisory lock is not held (previous pod crashed).++ When ``keep_locks`` is True the caller is responsible for releasing the+ probe locks after it has finished acting on the returned batches.+ """async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(f"""@@ -443,7 +474,10 @@ class DuckgresBatchQueue:rows = await cur.fetchall()result = [PendingBatch(**row) for row in rows]- await DuckgresBatchQueue.unlock_for_batches(conn, batches=result)++ if not keep_locks:+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=result)+return result@staticmethoddiff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex f4cbe2ebb3ec..785567d1c50f 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -140,13 +140,23 @@ class DeltaBatchConsumerAdapter:)capture_exception(e)+ async def verify_advisory_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> bool:+ return await BatchQueue.verify_advisory_lock(conn, team_id=team_id, schema_id=schema_id)+async def get_stale_executing(self,conn: psycopg.AsyncConnection[Any],*,grace_seconds: int,+ keep_locks: bool = False,) -> list[PendingBatch]:- return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)+ return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=keep_locks)async def reconcile_failed_runs(self,diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex cfc593df5234..f11fdea05d26 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@@ -327,11 +327,37 @@ class BatchQueue:},)+ @staticmethod+ async def verify_advisory_lock(+ conn: psycopg.AsyncConnection[Any],+ *,+ team_id: int,+ schema_id: str,+ ) -> bool:+ """Check if this session still holds the advisory lock for (team_id, schema_id)."""+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT EXISTS (+ SELECT 1 FROM pg_locks+ WHERE locktype = 'advisory'+ AND classid = {ADVISORY_LOCK_NAMESPACE}+ AND objid = hashtext(%(key)s)+ AND pid = pg_backend_pid()+ AND granted = true+ )+ """,+ {"key": f"{team_id}:{schema_id}"},+ )+ row = await cur.fetchone()+ return bool(row and row[0])+@staticmethodasync def get_stale_executing(conn: psycopg.AsyncConnection[Any],*,grace_seconds: int = 0,+ keep_locks: bool = False,) -> list[PendingBatch]:"""Find batches stuck in 'executing' whose advisory lock is not held (previous pod crashed).@@ -340,6 +366,9 @@ class BatchQueue:``grace_seconds`` requires the 'executing' status row to be older thanthis threshold before the batch is considered orphaned.++ When ``keep_locks`` is True the caller is responsible for releasing the+ probe locks after it has finished acting on the returned batches."""async with conn.cursor(row_factory=dict_row) as cur:await cur.execute(@@ -366,8 +395,8 @@ class BatchQueue: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)+ if not keep_locks:+ await BatchQueue.unlock_for_batches(conn, batches=result)return resultdiff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex b36c0939d29e..f80f44fb4f44 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, patchimport psycopgimport structlog+from posthog.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import OwnershipLostErrorfrom posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthStatefrom posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (BatchConsumer,@@ -167,6 +168,11 @@ class TestProcessGroup:"posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",new_callable=AsyncMock,) as mock_unlock,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ return_value=True,+ ),):await consumer._process_group((1, "schema-1"), batches)@@ -189,6 +195,11 @@ class TestProcessGroup:"posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",new_callable=AsyncMock,) as mock_unlock,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ return_value=True,+ ),patch.object(consumer, "_fail_run", new_callable=AsyncMock),):await consumer._process_group((1, "schema-1"), batches)@@ -218,6 +229,11 @@ class TestProcessGroup:"posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",new_callable=AsyncMock,),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ return_value=True,+ ),):await consumer._process_group((1, "schema-1"), batches)@@ -247,6 +263,11 @@ class TestProcessGroup:"posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",new_callable=AsyncMock,),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ return_value=True,+ ),):await consumer._process_group((1, "schema-1"), batches)@@ -269,6 +290,10 @@ class TestRecoverySweep:"posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",new_callable=AsyncMock,) as mock_status,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ) as mock_unlock,):await consumer._recovery_sweep()@@ -277,8 +302,9 @@ class TestRecoverySweep:batch_id=stale_batch.id,job_state=SourceBatchStatus.State.WAITING_RETRY,attempt=1,- error_response={"error": "executing timed out — pod restart or OOM"},+ error_response={"error": "executing timed out - pod restart or OOM"},)+ mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch])@pytest.mark.asyncioasync def test_fails_exhausted_stale_batch(self):@@ -292,11 +318,42 @@ class TestRecoverySweep:return_value=[stale_batch],),patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ) as mock_unlock,):await consumer._recovery_sweep()mock_fail.assert_called_once()assert "max retries exceeded" in mock_fail.call_args[1]["reason"]+ mock_unlock.assert_called_once()++ @pytest.mark.asyncio+ async def test_recovery_sweep_releases_probe_locks_on_error(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,+ side_effect=Exception("db gone"),+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",+ new_callable=AsyncMock,+ ) as mock_unlock,+ pytest.raises(Exception, match="db gone"),+ ):+ await consumer._recovery_sweep()++ mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch])class TestFailRun:@@ -486,12 +543,16 @@ class TestConnectionRecovery:new_callable=AsyncMock,side_effect=Exception("the connection is closed"),),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ return_value=True,+ ),):await consumer._process_group((1, "schema-1"), [_make_batch()])@pytest.mark.asyncioasync 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 (@@ -695,3 +756,77 @@ class TestHeartbeatLoop:# Once the heartbeat stops, liveness correctly goes stale again.await asyncio.sleep(0.2)assert health.is_healthy() is False+++class TestOwnershipVerification:+ @pytest.mark.asyncio+ async def test_ownership_lost_abandons_group(self):+ consumer = _make_consumer()+ processed: list[int] = []++ async def track_and_lose_lock(batch):+ processed.append(batch.batch_index)++ consumer._process_batch = track_and_lose_lock++ 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,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",+ new_callable=AsyncMock,+ side_effect=[True, True, False],+ ),+ ):+ await consumer._process_group((1, "schema-1"), batches)++ # Batch 0 processes (verify returns True before batch 0, True before succeeded write),+ # batch 1 fails on verify (returns False) and the group is abandoned.+ assert len(processed) <= 2+ mock_unlock.assert_called_once()++ @pytest.mark.asyncio+ async def test_dead_lock_conn_raises_ownership_lost(self):+ consumer = _make_consumer()+ batch = _make_batch(latest_attempt=0)++ dead_conn = _make_healthy_conn(closed=True)+ consumer._conn = dead_conn++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",+ new_callable=AsyncMock,+ ),+ pytest.raises(OwnershipLostError),+ ):+ await consumer._process_single(batch, lock_conn=dead_conn)++ @pytest.mark.asyncio+ async def test_process_single_without_lock_conn_skips_verification(self):+ consumer = _make_consumer()+ batch = _make_batch(latest_attempt=0)+ 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.verify_advisory_lock",+ new_callable=AsyncMock,+ ) as mock_verify,+ ):+ result = await consumer._process_single(batch, lock_conn=None)++ assert result is True+ mock_verify.assert_not_called()