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(data-warehouse): order lease locks and retry queue db drops (#104472)

Tom Owersb4b9ed7cb485
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
index bea8617d35ad..d6ec4ac504b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py
@@ -8,7 +8,8 @@ from collections import defaultdict
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Protocol
+from functools import partial
+from typing import Any, Protocol, TypeVar
from uuid import uuid4
import psycopg
@@ -26,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
logger = structlog.get_logger(__name__)
+T = TypeVar("T")
+
MAX_ATTEMPTS = 3
POLL_INTERVAL_SECONDS = 2.0
RECOVERY_INTERVAL_SECONDS = 30.0
@@ -57,6 +60,14 @@ POLL_BACKOFF_MAX_DOUBLINGS = 32
# re-creating the over-claim problem.
BATCHES_PER_GROUP_FETCH_FACTOR = 3
+# Attempts one queue-DB operation gets before its error escapes. Three is enough for the
+# faults we see, because a pooler recycle kills one connection and a deadlock rolls back
+# one statement. It also keeps a degraded queue DB from holding a poll or a sweep open for
+# minutes, since the caller's own interval is the retry beyond this.
+QUEUE_RETRY_MAX_ATTEMPTS = 3
+QUEUE_RETRY_BASE_DELAY_SECONDS = 0.25
+QUEUE_RETRY_MAX_DELAY_SECONDS = 2.0
+
# EAI_AGAIN ("Temporary failure in name resolution") means the resolver itself is
# briefly unavailable, not that the queue DB's hostname is invalid — the next
@@ -133,6 +144,77 @@ def _is_transient_connection_error(error: BaseException, conn: psycopg.AsyncConn
return isinstance(error, psycopg.OperationalError) and (conn.closed or conn.broken)
+# How libpq and psycopg word a connection that died under an in-flight query. The queue DB
+# sits behind a pooler, so a pool recycle, a failover, or a server-side backend cull leaves
+# the socket gone mid-statement. Nothing committed, so redialing and re-running is enough.
+_CONNECTION_DROPPED_MARKERS = (
+ "server closed the connection unexpectedly",
+ "consuming input failed",
+ "connection is closed",
+ "connection already closed",
+ "ssl connection has been closed unexpectedly",
+ "connection reset by peer",
+ "server conn crashed",
+)
+
+
+def _is_connection_dropped_error(error: BaseException) -> bool:
+ if not isinstance(error, psycopg.OperationalError):
+ return False
+ message = " ".join(str(arg) for arg in error.args).lower()
+ return any(marker in message for marker in _CONNECTION_DROPPED_MARKERS)
+
+
+# The pooler's `query_wait_timeout`: our query waited longer than the pool allows for a
+# server connection and was cut loose before Postgres ever saw it. Nothing ran, so
+# re-running it once the pool drains is safe. It arrives as ProtocolViolation (SQLSTATE
+# 08P01), which is too broad to accept by class, because a genuine protocol violation is a
+# driver bug that must keep reaching error tracking. Match the message instead, the same
+# way posthog/temporal/common/db_errors.py does for the app DB.
+_POOLER_QUERY_WAIT_TIMEOUT_MARKER = "query_wait_timeout"
+
+
+def _is_pooler_query_wait_timeout_error(error: BaseException) -> bool:
+ if not isinstance(error, psycopg.errors.ProtocolViolation):
+ return False
+ return _POOLER_QUERY_WAIT_TIMEOUT_MARKER in str(error).lower()
+
+
+def _is_transient_queue_db_error(error: BaseException) -> bool:
+ """Whether `error` is the queue DB being briefly unavailable rather than a bug.
+
+ Every shape gathered here clears on its own within seconds and leaves the statement
+ either unrun or rolled back, so redialing and re-running is both safe and sufficient.
+ """
+ return (
+ _is_dns_resolution_transient_error(error)
+ or _is_server_not_ready_error(error)
+ or _is_connect_timeout_error(error)
+ or _is_admin_shutdown_error(error)
+ or _is_connection_dropped_error(error)
+ or _is_pooler_query_wait_timeout_error(error)
+ )
+
+
+def _is_retryable_queue_db_error(error: BaseException) -> bool:
+ """Transient connection failures plus deadlocks: the queue-DB errors a retry resolves.
+
+ A deadlock means Postgres rolled our statement back so the other side could proceed.
+ Every queue statement runs in autocommit, so nothing is half applied and re-running it
+ is safe. Retrying does not paper over a lock-ordering bug either: an error that
+ outlives the budget still reaches error tracking, which is how a remaining bad lock
+ order stays visible.
+ """
+ return isinstance(error, psycopg.errors.DeadlockDetected) or _is_transient_queue_db_error(error)
+
+
+def _queue_retry_delay(attempt: int) -> float:
+ """Jittered exponential backoff between queue-DB attempts, so a fleet-wide blip
+ does not turn into a fleet-wide retry in lockstep."""
+ backoff = min(QUEUE_RETRY_BASE_DELAY_SECONDS * 2 ** (attempt - 1), QUEUE_RETRY_MAX_DELAY_SECONDS)
+ return backoff + random.uniform(0, QUEUE_RETRY_BASE_DELAY_SECONDS)
+
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -385,6 +467,28 @@ class BatchConsumer:
return int((client_timeout_seconds + self._config.statement_timeout_margin_seconds) * 1000)
async def _connect(self, *, statement_timeout_seconds: float | None = None) -> psycopg.AsyncConnection[Any]:
+ """Dial the queue DB, retrying a bounded number of times on a transient refusal.
+
+ A connect timeout, a pooler that is draining, or a queue DB still coming up all
+ clear within seconds, but every caller here turns one into something worse: a
+ crashed startup, a group left undispatched with its lease held for the full TTL,
+ or an error-tracking report for a blip that healed on its own.
+ """
+ for attempt in range(1, QUEUE_RETRY_MAX_ATTEMPTS + 1):
+ try:
+ return await self._connect_once(statement_timeout_seconds=statement_timeout_seconds)
+ except Exception as error:
+ if attempt == QUEUE_RETRY_MAX_ATTEMPTS or not _is_transient_queue_db_error(error):
+ raise
+ logger.warning(
+ self._event("queue_db_connect_retrying"),
+ attempt=attempt,
+ error=str(error),
+ )
+ await self._wait_or_shutdown(_queue_retry_delay(attempt))
+ raise AssertionError("unreachable: the last attempt either returns or re-raises")
+
+ async def _connect_once(self, *, statement_timeout_seconds: float | None = None) -> psycopg.AsyncConnection[Any]:
conn = await psycopg.AsyncConnection.connect(
self._config.database_url,
autocommit=True,
@@ -436,6 +540,83 @@ class BatchConsumer:
self._recovery_conn = await self._connect(statement_timeout_seconds=self._config.sweep_timeout_seconds)
return self._recovery_conn
+ async def _ensure_queue_conn(self, conn_attr: str) -> psycopg.AsyncConnection[Any]:
+ """Return the named long-lived connection, redialing it if it died.
+
+ Named rather than passed so it pairs with ``_drop_conn``, which already addresses
+ these two connections by attribute.
+ """
+ return await (self._ensure_poll_conn() if conn_attr == "_poll_conn" else self._ensure_recovery_conn())
+
+ async def _with_queue_conn(
+ self,
+ conn_attr: str,
+ op_name: str,
+ operation: Callable[[psycopg.AsyncConnection[Any]], Coroutine[Any, Any, T]],
+ should_abort: Callable[[], bool] | None = None,
+ ) -> T:
+ """Run `operation` on the named connection, reconnecting and retrying on a blip.
+
+ Covers the failures a long-lived pooled connection meets in normal operation: the
+ socket dying under an in-flight query, the pooler timing the query out before it
+ reached Postgres, and a deadlock against another pod. Without this a poll or a
+ sweep skips a whole cycle over a fault that a redial fixes in a quarter of a second.
+
+ The Django helper ``retry_on_db_connection_drop`` cannot stand in here: the queue
+ lives in its own database reached over raw psycopg, so ``django.db.OperationalError``
+ (an unrelated class) never matches, and its connection eviction would close app-DB
+ connections rather than this one.
+
+ ``should_abort``, when given, is checked before each retry. The caller's own
+ ``asyncio.timeout`` fires its cancellation exactly once, and psycopg can turn that
+ cancellation into a plain retryable-looking ``OperationalError`` ("consuming input
+ failed: server closed the connection unexpectedly") instead of letting a
+ ``TimeoutError`` propagate. Without this check a retry loop that swallows that error
+ would redial and re-run with no further cancellation coming, burning up to
+ ``QUEUE_RETRY_MAX_ATTEMPTS`` attempts and their backoff past a deadline that already
+ expired. Passing the timeout context's own ``expired`` lets a retry still happen for
+ a genuine transient error while the deadline stands, but stop the moment it is the
+ deadline itself that produced the error.
+ """
+ for attempt in range(1, QUEUE_RETRY_MAX_ATTEMPTS + 1):
+ try:
+ conn = await self._ensure_queue_conn(conn_attr)
+ return await operation(conn)
+ except Exception as error:
+ if (
+ attempt == QUEUE_RETRY_MAX_ATTEMPTS
+ or not _is_retryable_queue_db_error(error)
+ or (should_abort is not None and should_abort())
+ ):
+ raise
+ logger.warning(
+ self._event("queue_db_operation_retrying"),
+ operation=op_name,
+ attempt=attempt,
+ error=str(error),
+ )
+ if not isinstance(error, psycopg.errors.DeadlockDetected):
+ # A deadlock leaves the session usable. Every other shape here means the
+ # socket is gone or the pool refused it, so the next attempt must redial.
+ await self._drop_conn(conn_attr)
+ await self._wait_or_shutdown(_queue_retry_delay(attempt))
+ raise AssertionError("unreachable: the last attempt either returns or re-raises")
+
+ def _report_queue_failure(self, event: str, error: Exception, **context: Any) -> None:
+ """Log a queue-DB failure, reporting it only when it is not a self-healing blip.
+
+ A dropped connection or a pooler wait timeout is expected traffic for a fleet of
+ long-lived pollers: the work is picked up on the next cycle, and reporting each one
+ buries the failures that do need a person. A degraded queue DB still surfaces
+ through the poll-failure liveness trip and the queue-freshness gauge, which measure
+ the outage rather than counting its exceptions.
+ """
+ if _is_transient_queue_db_error(error):
+ logger.warning(event, error=str(error), **context)
+ return
+ logger.exception(event, **context)
+ capture_exception(error)
+
async def _wait_or_shutdown(self, timeout: float) -> None:
try:
await asyncio.wait_for(self._shutdown.wait(), timeout=timeout)
@@ -489,14 +670,12 @@ class BatchConsumer:
elif _is_admin_shutdown_error(e):
logger.warning(self._event("startup_sweep_admin_shutdown"), error=str(e))
else:
- logger.exception(self._event("startup_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("startup_sweep_error"), e)
except Exception as e:
if _is_schema_lag_error(e):
logger.warning(self._event("startup_sweep_schema_lag"), error=str(e))
else:
- logger.exception(self._event("startup_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("startup_sweep_error"), e)
self._recovery_task = asyncio.create_task(self._recovery_loop())
while not self._shutdown.is_set():
@@ -517,9 +696,14 @@ class BatchConsumer:
poll_start = time.monotonic()
poll_timeout_ctx = asyncio.timeout(self._config.poll_timeout_seconds)
try:
- conn = await self._ensure_poll_conn()
async with poll_timeout_ctx:
- batches = await self._fetch_batches(conn, available=available)
+ batches = await self._with_queue_conn(
+ "_poll_conn",
+ "fetch_and_lock",
+ partial(self._fetch_batches, available=available),
+ should_abort=poll_timeout_ctx.expired,
+ )
+ conn = await self._ensure_poll_conn()
except TimeoutError:
await self._handle_poll_timeout(poll_start)
continue
@@ -544,8 +728,7 @@ class BatchConsumer:
elif _is_admin_shutdown_error(e):
logger.warning(self._event("poll_failed_queue_db_admin_shutdown"), error=str(e))
else:
- logger.exception(self._event("poll_failed_queue_db_unreachable"))
- capture_exception(e)
+ self._report_queue_failure(self._event("poll_failed_queue_db_unreachable"), e)
self._note_poll_failure("db_unreachable", duration=time.monotonic() - poll_start)
await self._wait_or_shutdown(self._poll_retry_delay())
continue
@@ -627,8 +810,7 @@ class BatchConsumer:
try:
await self._adapter.unlock(conn, batches=undispatched, owner_token=self._owner_token)
except Exception as e:
- logger.exception(self._event("release_undispatched_failed"))
- capture_exception(e)
+ self._report_queue_failure(self._event("release_undispatched_failed"), e)
def _reap_finished_tasks(self) -> None:
"""Remove completed group tasks from the in-flight registry."""
@@ -642,12 +824,12 @@ class BatchConsumer:
try:
await self._process_group(key, batches)
except Exception as e:
- logger.exception(
+ self._report_queue_failure(
self._event("process_group_unhandled_error"),
+ e,
team_id=key[0],
schema_id=key[1],
)
- capture_exception(e)
async def _process_group(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
team_id, schema_id = key
@@ -772,12 +954,12 @@ class BatchConsumer:
pass
def _log_unlock_failure(self, error: Exception, *, team_id: int, schema_id: str) -> None:
- logger.exception(
+ self._report_queue_failure(
self._event("unlock_for_batches_failed"),
+ error,
team_id=team_id,
external_data_schema_id=schema_id,
)
- capture_exception(error)
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."""
@@ -1170,21 +1352,20 @@ class BatchConsumer:
elif _is_admin_shutdown_error(e):
logger.warning(self._event("recovery_sweep_admin_shutdown"), error=str(e))
else:
- logger.exception(self._event("recovery_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("recovery_sweep_error"), e)
except Exception as e:
if _is_schema_lag_error(e):
logger.warning(self._event("recovery_sweep_schema_lag"), error=str(e))
else:
- logger.exception(self._event("recovery_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("recovery_sweep_error"), e)
now = time.monotonic()
if now - self._last_reconcile_monotonic >= self._config.reconcile_interval_seconds:
self._last_reconcile_monotonic = now
+ reconcile_timeout_ctx = asyncio.timeout(self._config.sweep_timeout_seconds)
try:
- async with asyncio.timeout(self._config.sweep_timeout_seconds):
- await self._reconcile_failed_runs()
+ async with reconcile_timeout_ctx:
+ await self._reconcile_failed_runs(should_abort=reconcile_timeout_ctx.expired)
except TimeoutError:
logger.error( # noqa: TRY400 — designed recovery path, traceback is noise
self._event("reconcile_sweep_timed_out"),
@@ -1201,17 +1382,16 @@ class BatchConsumer:
elif _is_admin_shutdown_error(e):
logger.warning(self._event("reconcile_sweep_admin_shutdown"), error=str(e))
else:
- logger.exception(self._event("reconcile_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("reconcile_sweep_error"), e)
except Exception as e:
- logger.exception(self._event("reconcile_sweep_error"))
- capture_exception(e)
+ self._report_queue_failure(self._event("reconcile_sweep_error"), e)
async def _recovery_sweep_with_timeout(self) -> None:
"""Run the recovery sweep under the sweep timeout; a sweep that never returns must not stall the consumer."""
+ sweep_timeout_ctx = asyncio.timeout(self._config.sweep_timeout_seconds)
try:
- async with asyncio.timeout(self._config.sweep_timeout_seconds):
- await self._recovery_sweep()
+ async with sweep_timeout_ctx:
+ await self._recovery_sweep(should_abort=sweep_timeout_ctx.expired)
except TimeoutError:
logger.error( # noqa: TRY400 — designed recovery path, traceback is noise
self._event("recovery_sweep_timed_out"),
@@ -1219,15 +1399,18 @@ class BatchConsumer:
)
await self._drop_conn("_recovery_conn")
- async def _reconcile_failed_runs(self) -> None:
+ async def _reconcile_failed_runs(self, *, should_abort: Callable[[], bool] | None = None) -> None:
"""Reconcile runs whose queue batch failed but whose terminal-state write never landed."""
- conn = await self._ensure_recovery_conn()
-
- await self._adapter.reconcile_failed_runs(
- conn,
- grace_seconds=self._config.reconcile_grace_seconds,
- lookback_seconds=self._config.reconcile_lookback_seconds,
- limit=self._config.reconcile_limit,
+ await self._with_queue_conn(
+ "_recovery_conn",
+ "reconcile_failed_runs",
+ lambda conn: self._adapter.reconcile_failed_runs(
+ conn,
+ grace_seconds=self._config.reconcile_grace_seconds,
+ lookback_seconds=self._config.reconcile_lookback_seconds,
+ limit=self._config.reconcile_limit,
+ ),
+ should_abort=should_abort,
)
def _note_poll_failure(self, reason: str, *, duration: float) -> None:
@@ -1298,9 +1481,7 @@ class BatchConsumer:
except TimeoutError:
pass
- async def _recovery_sweep(self) -> None:
- conn = await self._ensure_recovery_conn()
-
+ async def _recovery_sweep(self, *, should_abort: Callable[[], bool] | None = None) -> None:
grace_seconds = self._config.recovery_grace_seconds
assert grace_seconds is not None
# keep_locks lets advisory-lock sinks (duckgres) hold their probe locks
@@ -1308,11 +1489,18 @@ class BatchConsumer:
# mid-recovery. The lease sink ignores it: get_stale_executing already
# excludes any group with a live lease, and the finally-unlock below is a
# no-op for leases this pod doesn't own.
- stale = await self._adapter.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=True)
+ stale = await self._with_queue_conn(
+ "_recovery_conn",
+ "get_stale_executing",
+ lambda conn: self._adapter.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=True),
+ should_abort=should_abort,
+ )
if not stale:
self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()
return
+ conn = await self._ensure_recovery_conn()
+
self._metrics.recovery_sweeps_total.labels(outcome="orphans_found").inc()
logger.info(self._event("recovery_sweep_found_stale_batches"), count=len(stale))
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.py
index 5e1606439daf..0962339a91f1 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
@@ -49,6 +49,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
OwnershipLostError,
ProcessBatchFn,
_group_by_key,
+ _is_transient_queue_db_error,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import ExportSignalMessage
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
@@ -178,10 +179,15 @@ def _is_transient_queue_connection_drop(err: Exception, conn: psycopg.AsyncConne
"""Whether `err` is a queue-db connection dying mid-query rather than a real bug.
A network blip, server-side cull, or pgbouncer bounce leaves `conn` closed; the next
- reconcile cycle reconnects and retries, so it isn't worth paging on (mirrors the
- conn.closed check already applied to the stranded-run sweep's own OperationalError).
+ reconcile cycle reconnects and retries, so it isn't worth paging on.
+
+ The engine's classifier reads the error itself, so it also catches the shapes that
+ leave the connection usable, such as pgbouncer cutting the query loose before it
+ reached Postgres. The `conn.closed` arm stays for a drop worded in a way no marker
+ matches, because a closed connection under a psycopg error is a drop however it is
+ phrased.
"""
- return isinstance(err, psycopg.OperationalError) and conn.closed
+ return _is_transient_queue_db_error(err) or (isinstance(err, psycopg.OperationalError) and conn.closed)
class DeltaBatchConsumerAdapter:
@@ -480,7 +486,7 @@ class DeltaBatchConsumerAdapter:
try:
await self._drain_orphaned_batches(conn, limit=limit)
except psycopg.OperationalError as e:
- if conn.closed:
+ if _is_transient_queue_connection_drop(e, conn):
logger.warning("orphaned_batch_drain_closed_connection", error=str(e))
else:
logger.exception("orphaned_batch_drain_failed")
@@ -494,9 +500,9 @@ class DeltaBatchConsumerAdapter:
try:
await self._reconcile_stale_stranded_runs(conn, stale_seconds=TAKEOVER_STALE_THRESHOLD_SECONDS, limit=limit)
except psycopg.OperationalError as e:
- if conn.closed:
- # A transient connection drop (network blip, server-side cull, pgbouncer bounce)
- # leaves the connection closed. The engine reconnects on the next cycle.
+ if _is_transient_queue_connection_drop(e, conn):
+ # A transient connection drop (network blip, server-side cull, pgbouncer bounce).
+ # The engine reconnects on the next cycle.
logger.warning("stranded_run_reconcile_sweep_closed_connection", error=str(e))
else:
logger.exception("stranded_run_reconcile_sweep_failed")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index c17f540519ed..cc2548b0fa9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -29,6 +29,23 @@ STATUS_TABLE = "sourcebatchstatus"
STATUS_VIEW = "v_latest_source_batch_status"
LEASE_TABLE = "sourcegrouplease"
+# Lock order for `sourcegrouplease`: a statement that locks more than one lease row
+# must take those locks in ascending (team_id, schema_id).
+#
+# Four paths write this table concurrently across the fleet: the claim upsert in
+# `get_unprocessed_and_lock`, the heartbeat `renew_lease`, the `unlock_for_batches`
+# delete, and the shutdown `release_all_owned_leases`. Postgres locks rows in whatever
+# order the plan happens to emit them, so two pods whose group sets overlap can lock the
+# same rows in opposite orders and deadlock. That also takes down single-row writers
+# caught in the cycle, because a waiter holds an ExclusiveLock on the tuple it is queued
+# for while it waits. `renew_lease` can therefore be a link in a cycle it did not cause.
+#
+# Single-row statements (`renew_lease`, `delete_expired_lease`,
+# `try_acquire_reconcile_sweep_slot`) satisfy the order for free. Multi-row statements
+# have to force it, either with `ORDER BY team_id, schema_id` on the rows an upsert
+# reads, or with an ordered `FOR UPDATE` sub-select that takes every lock before the
+# delete runs.
+
# Default group-lease validity window, in seconds. The consumer renews the
# lease on its heartbeat (~every grace/3); a group whose owner stops renewing
# becomes reclaimable once this window elapses. Coordinated with the consumer's
@@ -793,7 +810,9 @@ class BatchQueue:
Uses a MATERIALIZED CTE so that candidate selection (with LIMIT) is
fully resolved before the lease claim runs. ``candidate_groups`` is
``SELECT DISTINCT`` because ``INSERT ... ON CONFLICT DO UPDATE`` cannot
- affect the same (team_id, schema_id) row twice in one statement.
+ affect the same (team_id, schema_id) row twice in one statement, and it
+ is ordered and materialized so the upsert takes its lease-row locks in
+ the fleet-wide order (see the lock-order note above).
``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on
``state_changed_at``: a batch is only eligible when
@@ -868,8 +887,9 @@ class BatchQueue:
FROM {BATCH_TABLE} b
JOIN narrow n ON n.id = b.id AND n.created_at = b.created_at
),
- candidate_groups AS (
+ candidate_groups AS MATERIALIZED (
SELECT DISTINCT team_id, schema_id FROM candidates
+ ORDER BY team_id, schema_id
),
claimed AS (
INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)
@@ -1026,7 +1046,11 @@ class BatchQueue:
The ``expires_at > now()`` predicate makes a lapsed lease unrenewable, so an owner
whose lease expired (e.g. a >TTL queue-DB blip during a long write) can't resurrect
- it and finish over a batch the recovery sweep has already re-queued."""
+ it and finish over a batch the recovery sweep has already re-queued.
+
+ One row per call, so this satisfies the lease lock order (see the note above)
+ without doing anything: it can only ever wait, never hold one lease row while
+ queueing for another."""
async with conn.cursor() as cur:
await cur.execute(
f"""
@@ -1625,8 +1649,13 @@ class BatchQueue:
The ``owner_token`` predicate is load-bearing: if this owner's lease
already expired and another pod reclaimed the group, the delete must be
a no-op rather than removing the new owner's lease.
+
+ The ordered ``FOR UPDATE`` sub-select takes every row lock before the
+ delete runs, so this honors the fleet-wide lease lock order (see the
+ note above). A bare multi-row ``DELETE`` locks in plan order instead,
+ which is what let this statement deadlock against a concurrent claim.
"""
- pairs = list({(b.team_id, b.schema_id) for b in batches})
+ pairs = sorted({(b.team_id, b.schema_id) for b in batches})
if not pairs:
return
team_ids = [team_id for team_id, _ in pairs]
@@ -1634,10 +1663,16 @@ class BatchQueue:
await conn.execute(
f"""
DELETE FROM {LEASE_TABLE}
- WHERE owner_token = %(owner)s
- AND (team_id, schema_id) IN (
- SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])
- )
+ WHERE id IN (
+ SELECT l.id
+ FROM {LEASE_TABLE} l
+ WHERE l.owner_token = %(owner)s
+ AND (l.team_id, l.schema_id) IN (
+ SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])
+ )
+ ORDER BY l.team_id, l.schema_id
+ FOR UPDATE
+ )
""",
{"owner": owner_token, "team_ids": team_ids, "schema_ids": schema_ids},
)
@@ -1648,9 +1683,22 @@ class BatchQueue:
*,
owner_token: str,
) -> None:
- """Delete every group lease held by ``owner_token``. Used for best-effort cleanup on shutdown."""
+ """Delete every group lease held by ``owner_token``. Used for best-effort cleanup on shutdown.
+
+ Ordered ``FOR UPDATE`` for the same reason as :meth:`unlock_for_batches`: a pod
+ shutting down releases many groups at once, against a fleet still claiming them.
+ """
await conn.execute(
- f"DELETE FROM {LEASE_TABLE} WHERE owner_token = %(owner)s",
+ f"""
+ DELETE FROM {LEASE_TABLE}
+ WHERE id IN (
+ SELECT id
+ FROM {LEASE_TABLE}
+ WHERE owner_token = %(owner)s
+ ORDER BY team_id, schema_id
+ FOR UPDATE
+ )
+ """,
{"owner": owner_token},
)
@@ -1860,16 +1908,23 @@ class BatchQueue:
"""
if not pairs:
return 0
+ ordered = sorted(pairs)
cursor = conn.execute(
f"""
DELETE FROM {LEASE_TABLE}
- WHERE (team_id, schema_id) IN (
- SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])
+ WHERE id IN (
+ SELECT l.id
+ FROM {LEASE_TABLE} l
+ WHERE (l.team_id, l.schema_id) IN (
+ SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])
+ )
+ ORDER BY l.team_id, l.schema_id
+ FOR UPDATE
)
""",
{
- "team_ids": [team_id for team_id, _ in pairs],
- "schema_ids": [schema_id for _, schema_id in pairs],
+ "team_ids": [team_id for team_id, _ in ordered],
+ "schema_ids": [schema_id for _, schema_id in ordered],
},
)
return cursor.rowcount or 0
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.py
index a522a4f0c1d5..8b1c16540e1a 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
@@ -20,12 +20,15 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
batch_consumer as batch_consumer_module,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
+ QUEUE_RETRY_MAX_ATTEMPTS,
OwnershipLostError,
_is_admin_shutdown_error,
_is_connect_timeout_error,
_is_dns_resolution_transient_error,
+ _is_retryable_queue_db_error,
_is_schema_lag_error,
_is_server_not_ready_error,
+ _is_transient_queue_db_error,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue import (
@@ -666,6 +669,9 @@ class TestDnsResolutionTransientErrorClassification:
side_effect=raise_dns_error,
),
patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ # The bounded retry redials before its last attempt; without this the fake
+ # database_url would be dialled for real.
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
):
loop_task = asyncio.create_task(consumer._recovery_loop())
@@ -739,7 +745,7 @@ class TestConnectTimeoutErrorClassification:
second_reconcile_started = asyncio.Event()
call_count = 0
- async def flaky_reconcile() -> None:
+ async def flaky_reconcile(**kwargs: Any) -> None:
nonlocal call_count
call_count += 1
if call_count == 1:
@@ -823,6 +829,9 @@ class TestConnectTimeoutErrorClassification:
side_effect=raise_connect_timeout,
),
patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ # The bounded retry redials before its last attempt; without this the fake
+ # database_url would be dialled for real.
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
):
loop_task = asyncio.create_task(consumer._recovery_loop())
@@ -867,7 +876,7 @@ class TestAdminShutdownErrorClassification:
second_reconcile_started = asyncio.Event()
call_count = 0
- async def flaky_reconcile() -> None:
+ async def flaky_reconcile(**kwargs: Any) -> None:
nonlocal call_count
call_count += 1
if call_count == 1:
@@ -952,6 +961,9 @@ class TestAdminShutdownErrorClassification:
side_effect=raise_admin_shutdown,
),
patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ # The bounded retry redials before its last attempt; without this the fake
+ # database_url would be dialled for real.
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
):
loop_task = asyncio.create_task(consumer._recovery_loop())
@@ -1300,7 +1312,7 @@ class TestQueueOperationTimeouts:
second_reconcile_started = asyncio.Event()
call_count = 0
- async def flaky_reconcile() -> None:
+ async def flaky_reconcile(**kwargs: Any) -> None:
nonlocal call_count
call_count += 1
if call_count == 1:
@@ -2443,15 +2455,30 @@ class TestReconcileFailedRuns:
mock_capture.assert_not_called()
@pytest.mark.parametrize(
- "conn_closed,expect_capture",
- [(True, False), (False, True)],
- ids=["closed_conn_suppresses_capture", "open_conn_still_captured"],
+ "error,conn_closed,expect_capture",
+ [
+ (psycopg.OperationalError("the connection is closed"), True, False),
+ (
+ psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"),
+ False,
+ False,
+ ),
+ (psycopg.errors.ProtocolViolation("query_wait_timeout"), False, False),
+ (psycopg.OperationalError("relation permission denied"), False, True),
+ ],
+ ids=[
+ "closed_conn_suppresses_capture",
+ "dropped_conn_suppresses_capture",
+ "pooler_wait_timeout_suppresses_capture",
+ "real_failure_still_captured",
+ ],
)
@pytest.mark.asyncio
- async def test_stranded_sweep_closed_connection_not_captured(self, conn_closed, expect_capture):
- # A psycopg.OperationalError from a closed connection is a transient network
- # drop — the engine reconnects on the next cycle. Only a real unexpected error
- # (conn still open) should reach error tracking.
+ async def test_stranded_sweep_connection_drop_not_captured(self, error, conn_closed, expect_capture):
+ # A queue-db connection dying under the sweep is a transient drop, because the
+ # engine reconnects on the next cycle. The drop is recognized from the error itself, so a
+ # pooler that cut the query loose without closing our connection counts too. Only a
+ # real unexpected error should reach error tracking.
consumer = _make_consumer()
# consumer._recovery_conn starts healthy so _ensure_recovery_conn returns it
# without reconnecting. The side-effect below simulates the connection closing
@@ -2460,7 +2487,7 @@ class TestReconcileFailedRuns:
async def raise_with_maybe_closed_conn(*args: object, **kwargs: object) -> None:
if conn_closed:
cast(Any, consumer._recovery_conn).closed = True
- raise psycopg.OperationalError("the connection is closed")
+ raise error
with (
patch(
@@ -2495,16 +2522,29 @@ class TestReconcileFailedRuns:
assert mock_capture.called is expect_capture
@pytest.mark.parametrize(
- "conn_closed,expect_capture",
- [(True, False), (False, True)],
- ids=["closed_conn_suppresses_capture", "open_conn_still_captured"],
+ "error,conn_closed,expect_capture",
+ [
+ (psycopg.OperationalError("the connection is closed"), True, False),
+ (
+ psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"),
+ False,
+ False,
+ ),
+ (psycopg.errors.ProtocolViolation("query_wait_timeout"), False, False),
+ (psycopg.OperationalError("relation permission denied"), False, True),
+ ],
+ ids=[
+ "closed_conn_suppresses_capture",
+ "dropped_conn_suppresses_capture",
+ "pooler_wait_timeout_suppresses_capture",
+ "real_failure_still_captured",
+ ],
)
@pytest.mark.asyncio
- async def test_straggler_sweep_closed_connection_not_captured(self, conn_closed, expect_capture):
+ async def test_straggler_sweep_connection_drop_not_captured(self, error, conn_closed, expect_capture):
# Reproduces the reported issue: BatchQueue.fail_run for a straggler batch raised
- # psycopg.OperationalError("consuming input failed: server closed the connection
- # unexpectedly") because the queue-db connection died mid-query. That's the same
- # transient network drop already handled for the stranded-run sweep above; the
+ # an OperationalError because the queue-db connection died mid-query. That's the
+ # same transient drop already handled for the stranded-run sweep above; the
# straggler sweep must treat it the same way instead of always capturing it.
consumer = _make_consumer()
ref = _make_failed_run_ref()
@@ -2512,7 +2552,7 @@ class TestReconcileFailedRuns:
async def raise_with_maybe_closed_conn(*args: object, **kwargs: object) -> None:
if conn_closed:
cast(Any, consumer._recovery_conn).closed = True
- raise psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly")
+ raise error
with (
patch(
@@ -2680,6 +2720,227 @@ class TestConnectionRecovery:
assert mock_get_stale.call_args[0][0] is fresh
+class TestQueueDbRetry:
+ @pytest.mark.parametrize(
+ "error,transient,retryable",
+ [
+ (psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"), True, True),
+ (psycopg.OperationalError("the connection is closed"), True, True),
+ (psycopg.errors.ConnectionTimeout("connection timeout expired"), True, True),
+ (psycopg.errors.AdminShutdown("terminating connection due to administrator command"), True, True),
+ (psycopg.errors.ProtocolViolation("query_wait_timeout"), True, True),
+ (psycopg.errors.DeadlockDetected("deadlock detected"), False, True),
+ (psycopg.errors.ProtocolViolation("invalid message length"), False, False),
+ (psycopg.OperationalError("relation permission denied"), False, False),
+ (psycopg.errors.UndefinedColumn("column does not exist"), False, False),
+ ],
+ )
+ def test_classifies_queue_db_errors(self, error, transient, retryable) -> None:
+ assert _is_transient_queue_db_error(error) is transient
+ assert _is_retryable_queue_db_error(error) is retryable
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly"),
+ psycopg.errors.ConnectionTimeout("connection timeout expired"),
+ psycopg.errors.ProtocolViolation("query_wait_timeout"),
+ ],
+ ids=["dropped_connection", "connect_timeout", "pooler_wait_timeout"],
+ )
+ @pytest.mark.asyncio
+ async def test_transient_failure_redials_and_succeeds(self, error) -> None:
+ consumer = _make_consumer()
+ dead = consumer._recovery_conn
+ fresh = _make_healthy_conn()
+ seen: list[Any] = []
+
+ async def fail_once(conn: Any) -> str:
+ seen.append(conn)
+ if len(seen) == 1:
+ raise error
+ return "swept"
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ assert await consumer._with_queue_conn("_recovery_conn", "sweep", fail_once) == "swept"
+
+ assert seen == [dead, fresh]
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_deadlock_retries_on_the_same_connection(self) -> None:
+ # Postgres rolled the statement back but left the session usable, so redialing
+ # would throw away a healthy connection for nothing.
+ consumer = _make_consumer()
+ original = consumer._poll_conn
+ seen: list[Any] = []
+
+ async def fail_once(conn: Any) -> str:
+ seen.append(conn)
+ if len(seen) == 1:
+ raise psycopg.errors.DeadlockDetected("deadlock detected")
+ return "claimed"
+
+ with patch.object(consumer, "_connect", new_callable=AsyncMock) as mock_connect:
+ assert await consumer._with_queue_conn("_poll_conn", "fetch_and_lock", fail_once) == "claimed"
+
+ assert seen == [original, original]
+ mock_connect.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_deadlock_outliving_the_budget_still_raises(self) -> None:
+ # The budget must not hide a lock-ordering bug: a deadlock on every attempt has to
+ # escape so the caller reports it.
+ consumer = _make_consumer()
+ attempts = 0
+
+ async def always_deadlock(conn: Any) -> None:
+ nonlocal attempts
+ attempts += 1
+ raise psycopg.errors.DeadlockDetected("deadlock detected")
+
+ with (
+ patch(f"{batch_consumer_module.__name__}._queue_retry_delay", return_value=0),
+ pytest.raises(psycopg.errors.DeadlockDetected),
+ ):
+ await consumer._with_queue_conn("_poll_conn", "fetch_and_lock", always_deadlock)
+
+ assert attempts == QUEUE_RETRY_MAX_ATTEMPTS
+
+ @pytest.mark.asyncio
+ async def test_non_retryable_error_is_not_retried(self) -> None:
+ consumer = _make_consumer()
+ attempts = 0
+
+ async def always_fail(conn: Any) -> None:
+ nonlocal attempts
+ attempts += 1
+ raise psycopg.errors.UndefinedColumn("column b.destination_ids does not exist")
+
+ with pytest.raises(psycopg.errors.UndefinedColumn):
+ await consumer._with_queue_conn("_recovery_conn", "sweep", always_fail)
+
+ assert attempts == 1
+
+ @pytest.mark.asyncio
+ async def test_should_abort_stops_retrying_a_retryable_error(self) -> None:
+ # A caller's own asyncio.timeout cancels its task exactly once, and psycopg can
+ # turn that cancellation into a plain retryable-looking OperationalError. Without
+ # should_abort the retry loop would redial and re-run with no further cancellation
+ # coming, burning attempts and backoff past a deadline that already expired.
+ consumer = _make_consumer()
+ attempts = 0
+
+ async def always_transient(conn: Any) -> None:
+ nonlocal attempts
+ attempts += 1
+ raise psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly")
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ pytest.raises(psycopg.OperationalError),
+ ):
+ await consumer._with_queue_conn("_poll_conn", "fetch_and_lock", always_transient, should_abort=lambda: True)
+
+ # Raises on the very first attempt instead of exhausting QUEUE_RETRY_MAX_ATTEMPTS.
+ assert attempts == 1
+
+ @pytest.mark.asyncio
+ async def test_connect_retries_a_transient_refusal(self) -> None:
+ consumer = _make_consumer()
+ fresh = _make_healthy_conn()
+ attempts = 0
+
+ async def flaky_dial(**kwargs: Any) -> Any:
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")
+ return fresh
+
+ with patch.object(consumer, "_connect_once", side_effect=flaky_dial):
+ assert await consumer._connect() is fresh
+
+ assert attempts == 2
+
+ @pytest.mark.asyncio
+ async def test_connect_does_not_retry_a_real_failure(self) -> None:
+ consumer = _make_consumer()
+ attempts = 0
+
+ async def always_fail(**kwargs: Any) -> Any:
+ nonlocal attempts
+ attempts += 1
+ raise psycopg.OperationalError("password authentication failed")
+
+ with patch.object(consumer, "_connect_once", side_effect=always_fail), pytest.raises(psycopg.OperationalError):
+ await consumer._connect()
+
+ assert attempts == 1
+
+ @pytest.mark.asyncio
+ async def test_recovery_sweep_survives_a_dropped_connection(self) -> None:
+ # Reproduces the reported issue end to end: get_stale_executing lost its connection
+ # mid-query. Before the retry the whole sweep was skipped and the drop was reported;
+ # now the sweep redials and completes.
+ consumer = _make_consumer()
+ calls = 0
+
+ async def fail_once(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise psycopg.OperationalError("consuming input failed: server closed the connection unexpectedly")
+ return []
+
+ with (
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_stale_executing",
+ side_effect=fail_once,
+ ),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ await consumer._recovery_sweep()
+
+ assert calls == 2
+ mock_capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_poll_retries_a_claim_deadlock(self) -> None:
+ # The claim upsert is the deadlock-prone statement; one rollback must not cost the
+ # pod a whole poll cycle.
+ consumer = _make_consumer()
+ calls = 0
+
+ async def fail_once(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise psycopg.errors.DeadlockDetected("deadlock detected")
+ return []
+
+ with (
+ patch(
+ f"{consumer_module.__name__}.BatchQueue.get_unprocessed_and_lock",
+ side_effect=fail_once,
+ ),
+ patch(f"{batch_consumer_module.__name__}.capture_exception") as mock_capture,
+ ):
+ batches = await consumer._with_queue_conn(
+ "_poll_conn",
+ "fetch_and_lock",
+ lambda conn: consumer._fetch_batches(conn, available=1),
+ )
+
+ assert batches == []
+ assert calls == 2
+ mock_capture.assert_not_called()
+
+
class TestPerGroupConnectionIsolation:
@pytest.mark.asyncio
async def test_each_group_gets_distinct_connection(self):
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.py
index 541d734c47f1..a7692e1ba839 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
@@ -1,6 +1,7 @@
import re
import time
import asyncio
+from collections.abc import Coroutine
from datetime import timedelta
from typing import Any
from uuid import uuid4
@@ -606,6 +607,80 @@ class TestBatchQueueLeaseRenewal:
assert renewed is (not deleted), "delete must fence the old owner without touching live leases"
[email protected]_db(transaction=True)
+class TestLeaseLockOrder:
+ # Every multi-row lease statement must lock rows in ascending (team_id, schema_id).
+ # Pods claim and release overlapping group sets constantly, so two statements that
+ # disagree on the order deadlock as soon as their sets cross. Blocking one row in the
+ # middle of the set and asking which of the others are already locked pins the order
+ # without needing a deadlock to actually happen.
+
+ GROUPS = [(team_id, f"schema-{team_id}") for team_id in range(1, 6)]
+ BLOCKED_INDEX = 2 # the middle group, so both an earlier and a later row are observable
+
+ async def _await_lock_wait(self, probe: psycopg.AsyncConnection[Any], backend_pid: int) -> None:
+ deadline = time.monotonic() + 10.0
+ while time.monotonic() < deadline:
+ row = await (
+ await probe.execute("SELECT wait_event_type FROM pg_stat_activity WHERE pid = %s", (backend_pid,))
+ ).fetchone()
+ if row is not None and row[0] == "Lock":
+ return
+ await asyncio.sleep(0.02)
+ raise AssertionError("the statement under test never blocked on the group we locked")
+
+ async def _is_locked(self, probe: psycopg.AsyncConnection[Any], team_id: int, schema_id: str) -> bool:
+ try:
+ await probe.execute(
+ f"SELECT 1 FROM {LEASE_TABLE} WHERE team_id = %s AND schema_id = %s FOR UPDATE NOWAIT",
+ (team_id, schema_id),
+ )
+ except psycopg.errors.LockNotAvailable:
+ return True
+ return False
+
+ @pytest.mark.parametrize("statement", ["claim", "unlock"])
+ @pytest.mark.asyncio
+ async def test_multi_group_statements_lock_in_ascending_key_order(self, conn, conn_b, _db_url, statement):
+ 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)
+ assert len(batches) == len(self.GROUPS)
+
+ run: Coroutine[Any, Any, object]
+ if statement == "claim":
+ # Re-claiming has to lock the existing rows, so expire them rather than delete.
+ await conn.execute(f"UPDATE {LEASE_TABLE} SET expires_at = now() - interval '1 second'")
+ run = _claim(conn_b, owner=OWNER_A, limit=50)
+ else:
+ run = BatchQueue.unlock_for_batches(conn_b, batches=batches, owner_token=OWNER_A)
+
+ blocked_team_id, blocked_schema_id = self.GROUPS[self.BLOCKED_INDEX]
+ blocker = await psycopg.AsyncConnection.connect(_db_url)
+ probe = await psycopg.AsyncConnection.connect(_db_url, autocommit=True)
+ 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),
+ )
+
+ task = asyncio.create_task(run)
+ await self._await_lock_wait(probe, conn_b.info.backend_pid)
+
+ locked = [await self._is_locked(probe, team_id, schema_id) for team_id, schema_id in self.GROUPS]
+ await blocker.rollback()
+ await asyncio.wait_for(task, timeout=10.0)
+ finally:
+ await blocker.close()
+ await probe.close()
+
+ # Everything below the blocked group is already locked; nothing above it has been
+ # 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.django_db(transaction=True)
class TestVerifyGroupLeaseSync:
# Must agree with the async verify_advisory_lock predicate: a divergence