: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): skip locked leases when releasing undispatched groups (#115867)
posthog[bot]ec68fc55962a
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 8c735f3cc857..a0bec5eb2831 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@@ -289,8 +289,9 @@ class DeltaBatchConsumerAdapter:*,batches: list[PendingBatch],owner_token: str,+ skip_locked: bool = False,) -> None:- await BatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner_token)+ await BatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner_token, skip_locked=skip_locked)async def release_all_owned(self,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 c15844a82923..4d9b522e61cc 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@@ -663,7 +663,7 @@ class TestRecoverySweep:expected_state_changed_at=stale_batch.state_changed_at,)mock_unlock.assert_called_once_with(- consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token+ consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token, skip_locked=False)@pytest.mark.asyncio@@ -743,7 +743,7 @@ class TestRecoverySweep:await consumer._recovery_sweep()mock_unlock.assert_called_once_with(- consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token+ consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token, skip_locked=False)@@ -4124,6 +4124,7 @@ class TestDispatchGroups:assert (1, "schema-2") not in consumer._in_flightreleased = mock_unlock.call_args.kwargs["batches"]assert {b.id for b in released} == {dropped_1.id, dropped_2.id}+ assert mock_unlock.call_args.kwargs["skip_locked"] is Truetask = consumer._in_flight.pop((1, "schema-1"))task.cancel()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 889991e96ab9..f5165f726eca 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@@ -648,6 +648,34 @@ class TestLeaseLockOrder:# touched. Plan order would leave an arbitrary subset locked instead.assert locked == [index <= self.BLOCKED_INDEX for index in range(len(self.GROUPS))]+ @pytest.mark.asyncio+ async def test_skip_locked_unlock_releases_free_groups_without_waiting(self, conn, conn_b, _db_url):+ for team_id, schema_id in self.GROUPS:+ await _insert_batch(+ conn, team_id=team_id, schema_id=schema_id, job_id=f"job-{team_id}", run_uuid=f"run-{team_id}"+ )+ batches = await _claim(conn, owner=OWNER_A, limit=50)++ blocked_team_id, blocked_schema_id = self.GROUPS[self.BLOCKED_INDEX]+ blocker = await psycopg.AsyncConnection.connect(_db_url)+ try:+ await blocker.execute(+ f"SELECT 1 FROM {LEASE_TABLE} WHERE team_id = %s AND schema_id = %s FOR UPDATE",+ (blocked_team_id, blocked_schema_id),+ )+ await asyncio.wait_for(+ BatchQueue.unlock_for_batches(conn_b, batches=batches, owner_token=OWNER_A, skip_locked=True),+ timeout=10.0,+ )+ finally:+ await blocker.rollback()+ await blocker.close()++ remaining = [+ await _lease_count(conn, team_id=team_id, schema_id=schema_id) for team_id, schema_id in self.GROUPS+ ]+ assert remaining == [int(index == self.BLOCKED_INDEX) for index in range(len(self.GROUPS))]+@pytest.mark.django_db(transaction=True)class TestVerifyGroupLeaseSync:diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.pyindex d89abf302e07..278792ea5990 100644--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py@@ -354,6 +354,7 @@ class BatchConsumerAdapter(Protocol):*,batches: list[PendingBatch],owner_token: str,+ skip_locked: bool = False,) -> None: ...async def release_all_owned(@@ -917,7 +918,9 @@ class BatchConsumer:batch_count=len(undispatched),)try:- await self._adapter.unlock(conn, batches=undispatched, owner_token=self._owner_token)+ # Best effort: a lease row locked elsewhere expires after its TTL, so waiting on it+ # only risks the poll connection's statement timeout.+ await self._adapter.unlock(conn, batches=undispatched, owner_token=self._owner_token, skip_locked=True)except Exception as e:self._report_queue_failure(self._event("release_undispatched_failed"), e)diff --git a/products/warehouse_sources_queue/backend/core/generic_jobs.py b/products/warehouse_sources_queue/backend/core/generic_jobs.pyindex 7ba392df62f9..9319d3122b15 100644--- a/products/warehouse_sources_queue/backend/core/generic_jobs.py+++ b/products/warehouse_sources_queue/backend/core/generic_jobs.py@@ -626,16 +626,36 @@ class JobsTable:lane: str,group_keys: list[str],owner_token: str,+ skip_locked: bool = False,) -> None:- """Hand groups back when their work finishes (drop this owner's leases)."""+ """Hand groups back when their work finishes (drop this owner's leases).++ ``skip_locked`` leaves a lease row that another statement holds in place+ (it expires after its TTL) instead of waiting on it.+ """if not group_keys:return+ params = {"lane": lane, "group_keys": group_keys, "owner": owner_token}+ if skip_locked:+ await conn.execute(+ f"""+ DELETE FROM {JOB_LEASE_TABLE}+ WHERE id IN (+ SELECT id FROM {JOB_LEASE_TABLE}+ WHERE lane = %(lane)s AND group_key = ANY(%(group_keys)s) AND owner_token = %(owner)s+ ORDER BY group_key+ FOR UPDATE SKIP LOCKED+ )+ """,+ params,+ )+ returnawait conn.execute(f"""DELETE FROM {JOB_LEASE_TABLE}WHERE lane = %(lane)s AND group_key = ANY(%(group_keys)s) AND owner_token = %(owner)s""",- {"lane": lane, "group_keys": group_keys, "owner": owner_token},+ params,)@staticmethoddiff --git a/products/warehouse_sources_queue/backend/core/jobs_db.py b/products/warehouse_sources_queue/backend/core/jobs_db.pyindex b2ebae424685..a8a06b1582ad 100644--- a/products/warehouse_sources_queue/backend/core/jobs_db.py+++ b/products/warehouse_sources_queue/backend/core/jobs_db.py@@ -2388,6 +2388,7 @@ class BatchQueue:*,batches: list[PendingBatch],owner_token: str,+ skip_locked: bool = False,) -> None:"""Release the group leases for ``batches``' (team_id, schema_id) groups held by ``owner_token``.@@ -2399,6 +2400,10 @@ class BatchQueue:delete runs, so this honors the fleet-wide lease lock order (see thenote above). A bare multi-row ``DELETE`` locks in plan order instead,which is what let this statement deadlock against a concurrent claim.++ ``skip_locked`` makes the release best effort: a lease row that another+ statement holds stays in place and expires after its TTL, so the delete+ never waits into the connection's statement timeout."""pairs = sorted({(b.team_id, b.schema_id) for b in batches})if not pairs:@@ -2416,7 +2421,7 @@ class BatchQueue:SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[]))ORDER BY l.team_id, l.schema_id- FOR UPDATE+ FOR UPDATE {"SKIP LOCKED" if skip_locked else ""})""",{"owner": owner_token, "team_ids": team_ids, "schema_ids": schema_ids},diff --git a/products/warehouse_sources_queue/backend/sdk/jobs.py b/products/warehouse_sources_queue/backend/sdk/jobs.pyindex 2a9fffaf5021..84e7806ea1b0 100644--- a/products/warehouse_sources_queue/backend/sdk/jobs.py+++ b/products/warehouse_sources_queue/backend/sdk/jobs.py@@ -157,12 +157,14 @@ class GenericJobAdapter:*,batches: list[Job],owner_token: str,+ skip_locked: bool = False,) -> None:await JobsTable.unlock_groups(conn,lane=self._lane,group_keys=sorted({job.group_key for job in batches}),owner_token=owner_token,+ skip_locked=skip_locked,)async def release_all_owned(