: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(data-warehouse): release the queue gauge slot on loader shutdown (#113553)
Tom Owers08c4185b1e36
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.pyindex afef0b6bfbc4..8c735f3cc857 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py@@ -774,6 +774,13 @@ class DeltaBatchConsumerAdapter:async def observe_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> bool:return await self._observe_queue_freshness(conn)+ async def release_queue_gauges_slot(self, conn: psycopg.AsyncConnection[Any]) -> None:+ await BatchQueue.release_queue_gauges_slot(+ conn, owner_token=self._gauge_owner_token, slot_key=self._gauge_slot_key+ )+ self._depth_sample = None+ clear_queue_sample_gauges()+async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> bool:"""Report the age of the oldest batch no consumer has picked up yet, and the queue depth.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.pyindex b1c2fe97bd12..d5a63c3a5629 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py@@ -3930,6 +3930,49 @@ class TestShutdown:mock_release.assert_awaited_once_with(main_conn, owner_token=consumer._owner_token)main_conn.close.assert_awaited_once()+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "error,conn_closed,expected_calls",+ [+ (None, False, 1),+ (psycopg.OperationalError("server closed the connection unexpectedly"), False, 1),+ (TimeoutError(), False, 1),+ (None, True, 0),+ ],+ )+ async def test_close_releases_gauge_slot_once_and_survives_failure(self, error, conn_closed, expected_calls):+ consumer = _make_consumer()+ recovery_conn = _make_healthy_conn(closed=conn_closed)+ consumer._recovery_conn = recovery_conn++ with (+ patch.object(+ consumer._adapter, "release_queue_gauges_slot", new_callable=AsyncMock, side_effect=error+ ) as mock_release,+ patch.object(consumer._adapter, "release_all_owned", new_callable=AsyncMock),+ ):+ await consumer._close()++ assert mock_release.await_count == expected_calls+ if expected_calls:+ mock_release.assert_awaited_once_with(recovery_conn)++ @pytest.mark.asyncio+ async def test_close_does_not_wait_on_a_slow_gauge_slot_release(self):+ consumer = _make_consumer()++ async def hang(conn):+ await asyncio.Event().wait()++ with (+ patch.object(batch_consumer_module, "GAUGE_SLOT_RELEASE_TIMEOUT_SECONDS", 0.01),+ patch.object(consumer._adapter, "release_queue_gauges_slot", side_effect=hang),+ patch.object(consumer._adapter, "release_all_owned", new_callable=AsyncMock) as mock_release_all,+ ):+ await asyncio.wait_for(consumer._close(), timeout=5.0)++ mock_release_all.assert_awaited_once()+@pytest.mark.asyncioasync def test_close_drains_in_flight_tasks(self):consumer = _make_consumer()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.pyindex e15b2bc04092..e29c9bea4c7a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py@@ -159,6 +159,33 @@ class TestQueueGaugesSlot:assert acquired is expected+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "releaser,released,next_pod_acquires",+ [+ # The holder frees the slot, so the next pod samples at once, not after the TTL.+ ("pod-a", True, True),+ # A pod that lost the slot must not delete the new holder's row.+ ("pod-b", False, False),+ ],+ )+ async def test_release_only_frees_the_holders_slot(self, conn, conn_b, releaser, released, next_pod_acquires):+ assert await BatchQueue.try_acquire_queue_gauges_slot(conn, owner_token="pod-a")++ assert await BatchQueue.release_queue_gauges_slot(conn, owner_token=releaser) is released++ assert await BatchQueue.try_acquire_queue_gauges_slot(conn_b, owner_token="pod-c") is next_pod_acquires++ @pytest.mark.asyncio+ async def test_release_leaves_other_fleets_slots(self, conn, conn_b):+ other_key = "__queue-gauges__:only:cdc"+ assert await BatchQueue.try_acquire_queue_gauges_slot(conn, owner_token="pod-a")+ assert await BatchQueue.try_acquire_queue_gauges_slot(conn, owner_token="pod-a", slot_key=other_key)++ await BatchQueue.release_queue_gauges_slot(conn, owner_token="pod-a")++ assert await BatchQueue.try_acquire_queue_gauges_slot(conn_b, owner_token="pod-b", slot_key=other_key) is False+@pytest.mark.asyncioasync def test_gauge_slot_does_not_take_the_sweep_slot(self, conn, conn_b):assert await BatchQueue.try_acquire_queue_gauges_slot(conn, owner_token="pod-a")diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex 3a5aaccb8b65..90d631aa7af9 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -47,6 +47,7 @@ GAUGE_SLOT_WARMUP_SECONDS = RECONCILE_INTERVAL_SECONDSRECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphaned by consumer outagesSHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0+GAUGE_SLOT_RELEASE_TIMEOUT_SECONDS = 3.0# Cap on the jitter window between failed polls — flat retries make the whole# fleet hammer a degraded queue DB in lockstep.@@ -424,6 +425,10 @@ class BatchConsumerAdapter(Protocol):"""Sample the queue-wide gauges if this pod holds the gauge slot; True means it does."""...+ async def release_queue_gauges_slot(self, conn: psycopg.AsyncConnection[Any]) -> None:+ """Free the gauge slot if this pod holds it, so another pod can sample at once. Best-effort on shutdown."""+ ...+async def should_process_batch(self,conn: psycopg.AsyncConnection[Any],@@ -1859,6 +1864,17 @@ class BatchConsumer:except Exception:logger.exception(self._event("recovery_sweep_unlock_failed"))+ async def _release_queue_gauges_slot(self) -> None:+ """Best-effort: a slow or failing queue DB must never delay or fail the shutdown."""+ conn = self._recovery_conn+ if conn is None or conn.closed or conn.broken:+ return+ try:+ async with asyncio.timeout(GAUGE_SLOT_RELEASE_TIMEOUT_SECONDS):+ await self._adapter.release_queue_gauges_slot(conn)+ except Exception as e:+ logger.warning(self._event("release_queue_gauges_slot_failed"), error=str(e) or type(e).__name__)+def _install_signal_handlers(self) -> None:loop = asyncio.get_running_loop()for sig in (signal.SIGTERM, signal.SIGINT):@@ -1875,6 +1891,9 @@ class BatchConsumer:except asyncio.CancelledError:pass+ # Free the gauge slot before the drain: no pod samples while the old holder drains.+ await self._release_queue_gauges_slot()+# Drain in-flight group tasks; each task releases its own lease and closes its connection.if self._in_flight:logger.info(self._event("draining_in_flight_groups"), count=len(self._in_flight))diff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.pyindex de36956ac4c5..17931e645b21 100644--- a/products/warehouse_sources_queue/backend/core/jobs_db.py+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py@@ -1740,6 +1740,29 @@ class BatchQueue:reentrant=True,)+ @staticmethod+ async def release_queue_gauges_slot(+ conn: psycopg.AsyncConnection[Any],+ *,+ owner_token: str,+ slot_key: str = QUEUE_GAUGES_LEASE_SCHEMA_ID_PREFIX,+ ) -> bool:+ """Delete the gauge slot row if ``owner_token`` still holds it; True means a row was deleted.++ One statement, so a pod that lost the slot to another pod cannot delete the+ new holder's row. After the delete, the next acquire inserts a fresh row at once.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ DELETE FROM {LEASE_TABLE}+ WHERE team_id = %(team_id)s AND schema_id = %(schema_id)s AND owner_token = %(owner)s+ RETURNING 1+ """,+ {"team_id": RECONCILE_SWEEP_LEASE_TEAM_ID, "schema_id": slot_key, "owner": owner_token},+ )+ return (await cur.fetchone()) is not None+@staticmethodasync def renew_lease(conn: psycopg.AsyncConnection[Any],diff --git a/products/warehouse_sources_queue/backend/sdk/jobs.py b/products/warehouse_sources_queue/backend/sdk/jobs.pyindex e282d0dcebc3..2a9fffaf5021 100644--- a/products/warehouse_sources_queue/backend/sdk/jobs.py+++ b/products/warehouse_sources_queue/backend/sdk/jobs.py@@ -345,6 +345,9 @@ class GenericJobAdapter:async def observe_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> bool:return False+ async def release_queue_gauges_slot(self, conn: psycopg.AsyncConnection[Any]) -> None:+ return+async def should_process_batch(self,conn: psycopg.AsyncConnection[Any],