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-imports): make group lock lease-based so abandoned groups can't wedge the consumer (#66606)

estefania4e7a8811c84b
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index a9fad5a7223d..06e6b1ff9cbb 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -229,6 +229,7 @@ rules:
|SlackThreadTaskMapping
|SourceBatch
|SourceBatchDuckgresApply
+ |SourceGroupLease
|StreamlitApp
|Subscription
|SubscriptionDelivery
@@ -491,6 +492,7 @@ rules:
|SlackThreadTaskMapping
|SourceBatch
|SourceBatchDuckgresApply
+ |SourceGroupLease
|StreamlitApp
|Subscription
|SubscriptionDelivery
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index 863d2bcc5772..08c38277ac95 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -155,6 +155,7 @@ SignalTeamConfig
SingleSessionSummary
SlackThreadTaskMapping
SourceBatch
+SourceGroupLease
Subscription
SubscriptionDelivery
Survey
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 8d0c7e57fd47..763ef3828e60 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
@@ -7,6 +7,7 @@ from collections import defaultdict
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any, Protocol
+from uuid import uuid4
import psycopg
import structlog
@@ -37,7 +38,7 @@ RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphaned
class OwnershipLostError(Exception):
- """Raised when the advisory lock for a (team_id, schema_id) group is no longer held."""
+ """Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@dataclass
@@ -55,6 +56,9 @@ class BatchConsumerConfig:
recovery_interval_seconds: float = RECOVERY_INTERVAL_SECONDS
retry_backoff_base_seconds: int = RETRY_BACKOFF_BASE_SECONDS
recovery_grace_seconds: int | None = None
+ # Group-lease validity window. Defaults to recovery_grace_seconds so lease
+ # reclamation and the executing-status recovery sweep fire together.
+ lease_ttl_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
@@ -67,6 +71,8 @@ class BatchConsumerConfig:
def __post_init__(self) -> None:
if self.recovery_grace_seconds is None:
self.recovery_grace_seconds = RECOVERY_GRACE_SECONDS
+ if self.lease_ttl_seconds is None:
+ self.lease_ttl_seconds = self.recovery_grace_seconds
class BatchConsumerAdapter(Protocol):
@@ -90,6 +96,8 @@ class BatchConsumerAdapter(Protocol):
*,
limit: int,
retry_backoff_base_seconds: int,
+ owner_token: str,
+ lease_ttl_seconds: int,
) -> list[PendingBatch]: ...
async def unlock(
@@ -97,8 +105,18 @@ class BatchConsumerAdapter(Protocol):
conn: psycopg.AsyncConnection[Any],
*,
batches: list[PendingBatch],
+ owner_token: str,
) -> None: ...
+ async def release_all_owned(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ owner_token: str,
+ ) -> None:
+ """Release every group this consumer owns. Best-effort cleanup on graceful shutdown."""
+ ...
+
async def update_status(
self,
conn: psycopg.AsyncConnection[Any],
@@ -123,6 +141,17 @@ class BatchConsumerAdapter(Protocol):
*,
team_id: int,
schema_id: str,
+ owner_token: str,
+ ) -> bool: ...
+
+ async def renew_lease(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int,
+ schema_id: str,
+ owner_token: str,
+ lease_ttl_seconds: int,
) -> bool: ...
async def get_stale_executing(
@@ -169,6 +198,9 @@ class BatchConsumer:
self._config = config
self._process_batch = process_batch
self._adapter = adapter
+ # Per-pod identity for group-lease ownership. A new token each start means
+ # a restarted pod cannot accidentally renew a lease it abandoned pre-restart.
+ self._owner_token = str(uuid4())
self._health_reporter = health_reporter
self._metrics = metrics or DELTA_CONSUMER_METRICS
self._semaphore = asyncio.Semaphore(config.max_concurrency)
@@ -186,6 +218,10 @@ class BatchConsumer:
self._inflight_started: dict[str, float] = {}
self._last_stuck_log_monotonic = 0.0
+ @property
+ def _lease_ttl_seconds(self) -> int:
+ return self._config.lease_ttl_seconds or self._config.recovery_grace_seconds or RECOVERY_GRACE_SECONDS
+
async def _connect(self) -> psycopg.AsyncConnection[Any]:
return await psycopg.AsyncConnection.connect(
self._config.database_url,
@@ -230,6 +266,7 @@ class BatchConsumer:
max_concurrency=self._config.max_concurrency,
poll_interval=self._config.poll_interval_seconds,
poll_limit=self._config.poll_limit,
+ owner_token=self._owner_token,
)
try:
@@ -247,6 +284,8 @@ class BatchConsumer:
conn,
limit=self._config.poll_limit,
retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
+ owner_token=self._owner_token,
+ lease_ttl_seconds=self._lease_ttl_seconds,
)
except psycopg.OperationalError as e:
# Queue DB unreachable — keep the pod alive; the next iteration reconnects.
@@ -281,7 +320,7 @@ class BatchConsumer:
async def _process_group(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
team_id, schema_id = key
- # Pin the connection that holds the advisory locks so status writes stay on the same session.
+ # Pin the connection that claimed the group lease so status writes and lease renewals stay together.
lock_conn = self._conn
await self._semaphore.acquire()
try:
@@ -329,9 +368,9 @@ class BatchConsumer:
self._semaphore.release()
try:
assert lock_conn is not None
- await self._adapter.unlock(lock_conn, batches=batches)
+ await self._adapter.unlock(lock_conn, batches=batches, owner_token=self._owner_token)
except Exception as e:
- # A dead session already released its locks server-side; don't crash every concurrent group.
+ # An abandoned lease just expires; releasing eagerly is best-effort, so don't crash sibling groups.
logger.exception(
self._event("unlock_for_batches_failed"),
team_id=team_id,
@@ -348,15 +387,17 @@ class BatchConsumer:
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."""
+ """Raise OwnershipLostError if this consumer no longer holds the group lease."""
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)
+ owns = await self._adapter.verify_advisory_lock(
+ lock_conn, team_id=batch.team_id, schema_id=batch.schema_id, owner_token=self._owner_token
+ )
except Exception as e:
- raise OwnershipLostError("lock verification query failed") from e
+ raise OwnershipLostError("lease verification query failed") from e
if not owns:
- raise OwnershipLostError(f"advisory lock lost for ({batch.team_id}, {batch.schema_id})")
+ raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")
async def _batch_heartbeat(
self,
@@ -364,12 +405,27 @@ class BatchConsumer:
batch: PendingBatch,
attempt: int,
) -> None:
- """Re-insert EXECUTING status periodically to prevent premature recovery."""
+ """Renew the group lease and re-insert EXECUTING status periodically to prevent premature recovery.
+
+ Renewing the lease and refreshing the executing-status grace window on
+ the same cadence keeps the two reclaim signals consistent: a pod that
+ stops heartbeating loses its lease and ages out of the grace window at
+ the same time. ``renew_lease`` returning False means another pod
+ reclaimed the group, so we stop heartbeating immediately.
+ """
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)
+ renewed = await self._adapter.renew_lease(
+ lock_conn,
+ team_id=batch.team_id,
+ schema_id=batch.schema_id,
+ owner_token=self._owner_token,
+ lease_ttl_seconds=self._lease_ttl_seconds,
+ )
+ if not renewed:
+ raise OwnershipLostError(f"group lease lost for ({batch.team_id}, {batch.schema_id})")
await self._adapter.update_status(
lock_conn,
batch_id=batch.id,
@@ -635,7 +691,11 @@ class BatchConsumer:
grace_seconds = self._config.recovery_grace_seconds
assert grace_seconds is not None
- # Hold probe locks so a concurrent consumer can't pick up these batches mid-recovery.
+ # keep_locks lets advisory-lock sinks (duckgres) hold their probe locks
+ # through the re-queue so a concurrent consumer can't pick a batch up
+ # 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)
if not stale:
self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()
@@ -686,9 +746,11 @@ class BatchConsumer:
finally:
structlog.contextvars.unbind_contextvars(*recovery_bound_keys)
finally:
- # Release probe locks acquired by keep_locks=True.
+ # Release probe locks held by keep_locks=True (advisory sinks). For the
+ # lease sink this only deletes leases this pod owns, so it's a no-op for
+ # the abandoned groups recovered above.
try:
- await self._adapter.unlock(conn, batches=stale)
+ await self._adapter.unlock(conn, batches=stale, owner_token=self._owner_token)
except Exception:
logger.exception(self._event("recovery_sweep_unlock_failed"))
@@ -709,13 +771,16 @@ class BatchConsumer:
if self._recovery_conn is not None and not self._recovery_conn.closed:
await self._recovery_conn.close()
- if self._conn is not None and not self._conn.closed:
+ # Release every group we own so a surviving pod can reclaim it immediately
+ # instead of waiting out the lease TTL. Best-effort: if the connection is
+ # broken (or this is a SIGKILL we never reach), the lease just expires.
+ if self._conn is not None and not self._conn.closed and not self._conn.broken:
try:
- await self._conn.execute("SELECT pg_advisory_unlock_all()")
+ await self._adapter.release_all_owned(self._conn, owner_token=self._owner_token)
except Exception as e:
- # A broken session already lost its advisory locks; still close below.
- logger.exception(self._event("advisory_unlock_all_failed_on_shutdown"))
+ logger.exception(self._event("release_all_owned_failed_on_shutdown"))
capture_exception(e)
+ if self._conn is not None and not self._conn.closed:
await self._conn.close()
logger.info(self._event("batch_consumer_stopped"))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
index b1906aaa10a1..6fdfdda5e694 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py
@@ -143,7 +143,12 @@ class DuckgresBatchConsumerAdapter:
*,
limit: int,
retry_backoff_base_seconds: int,
+ owner_token: str,
+ lease_ttl_seconds: int,
) -> list[PendingBatch]:
+ # The duckgres sink coordinates via session advisory locks, not leases:
+ # owner_token / lease_ttl_seconds are part of the shared adapter contract
+ # but unused here.
team_ids = await self._enabled_team_ids()
if team_ids is not None and not team_ids:
return []
@@ -168,9 +173,19 @@ class DuckgresBatchConsumerAdapter:
conn: psycopg.AsyncConnection[Any],
*,
batches: list[PendingBatch],
+ owner_token: str,
) -> None:
await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches)
+ async def release_all_owned(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ owner_token: str,
+ ) -> None:
+ # Duckgres holds session advisory locks; release them all on graceful shutdown.
+ await conn.execute("SELECT pg_advisory_unlock_all()")
+
async def update_status(
self,
conn: psycopg.AsyncConnection[Any],
@@ -212,9 +227,23 @@ class DuckgresBatchConsumerAdapter:
*,
team_id: int,
schema_id: str,
+ owner_token: str,
) -> bool:
return await DuckgresBatchQueue.verify_advisory_lock(conn, team_id=team_id, schema_id=schema_id)
+ async def renew_lease(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int,
+ schema_id: str,
+ owner_token: str,
+ lease_ttl_seconds: int,
+ ) -> bool:
+ # Duckgres ownership is the session advisory lock (checked by verify_advisory_lock),
+ # which has no TTL to renew; report ownership retained.
+ return True
+
async def get_stale_executing(
self,
conn: psycopg.AsyncConnection[Any],
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
index 69eb9e4b120a..45522d696e66 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py
@@ -186,7 +186,9 @@ class TestDuckgresEnablementGating:
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",
new_callable=AsyncMock,
) as mock_fetch:
- batches = await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=0)
+ batches = await adapter.fetch_and_lock(
+ conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300
+ )
assert batches == []
mock_fetch.assert_not_called()
@@ -222,7 +224,9 @@ class TestDuckgresEnablementGating:
return_value=["blocked-schema"],
),
):
- await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=30)
+ await adapter.fetch_and_lock(
+ conn, limit=50, retry_backoff_base_seconds=30, owner_token="test-owner", lease_ttl_seconds=300
+ )
assert mock_fetch.call_args[1]["team_ids"] == [1, 2]
assert mock_fetch.call_args[1]["retry_backoff_base_seconds"] == 30
@@ -258,7 +262,9 @@ class TestDuckgresEnablementGating:
side_effect=RuntimeError("app DB down"),
),
):
- batches = await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=0)
+ batches = await adapter.fetch_and_lock(
+ conn, limit=50, retry_backoff_base_seconds=0, owner_token="test-owner", lease_ttl_seconds=300
+ )
assert batches == []
mock_fetch.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
index cd2aee6ba2c4..4c6cd94f44c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BATCH_TABLE,
+ LEASE_TABLE,
STATUS_TABLE,
STATUS_VIEW,
BatchQueue,
@@ -101,11 +102,24 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
FROM {DUCKGRES_STATUS_TABLE}
ORDER BY batch_id ASC, created_at DESC, id DESC
""")
+ # Needed so the Delta queue's claim CTE (referenced by the contract test below) can plan.
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {LEASE_TABLE} (
+ id BIGSERIAL PRIMARY KEY,
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ owner_token VARCHAR(64) NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT sgl_team_schema_uniq UNIQUE (team_id, schema_id)
+ )
+ """)
def _truncate_tables(conn: psycopg.Connection[Any]) -> None:
conn.execute(
- f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE"
+ f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE}, {LEASE_TABLE} RESTART IDENTITY CASCADE"
)
@@ -433,7 +447,7 @@ class TestBackfillQueueContracts:
)
await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)
- assert await BatchQueue.get_unprocessed_and_lock(conn) == []
+ assert await BatchQueue.get_unprocessed_and_lock(conn, owner_token="test-owner") == []
duck = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)
assert [str(b.id) for b in duck] == [batch_id]
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 439de886d74d..e5f2b97887a4 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
@@ -61,11 +61,15 @@ class DeltaBatchConsumerAdapter:
*,
limit: int,
retry_backoff_base_seconds: int,
+ owner_token: str,
+ lease_ttl_seconds: int,
) -> list[PendingBatch]:
return await BatchQueue.get_unprocessed_and_lock(
conn,
+ owner_token=owner_token,
limit=limit,
retry_backoff_base_seconds=retry_backoff_base_seconds,
+ lease_ttl_seconds=lease_ttl_seconds,
)
async def unlock(
@@ -73,8 +77,17 @@ class DeltaBatchConsumerAdapter:
conn: psycopg.AsyncConnection[Any],
*,
batches: list[PendingBatch],
+ owner_token: str,
) -> None:
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await BatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner_token)
+
+ async def release_all_owned(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ owner_token: str,
+ ) -> None:
+ await BatchQueue.release_all_owned_leases(conn, owner_token=owner_token)
async def update_status(
self,
@@ -153,8 +166,28 @@ class DeltaBatchConsumerAdapter:
*,
team_id: int,
schema_id: str,
+ owner_token: str,
) -> bool:
- return await BatchQueue.verify_advisory_lock(conn, team_id=team_id, schema_id=schema_id)
+ return await BatchQueue.verify_advisory_lock(
+ conn, team_id=team_id, schema_id=schema_id, owner_token=owner_token
+ )
+
+ async def renew_lease(
+ self,
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int,
+ schema_id: str,
+ owner_token: str,
+ lease_ttl_seconds: int,
+ ) -> bool:
+ return await BatchQueue.renew_lease(
+ conn,
+ team_id=team_id,
+ schema_id=schema_id,
+ owner_token=owner_token,
+ lease_ttl_seconds=lease_ttl_seconds,
+ )
async def get_stale_executing(
self,
@@ -163,7 +196,9 @@ class DeltaBatchConsumerAdapter:
grace_seconds: int,
keep_locks: bool = False,
) -> list[PendingBatch]:
- return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds, keep_locks=keep_locks)
+ # keep_locks is meaningless for the lease sink: get_stale_executing holds
+ # no locks and the lease LEFT JOIN already excludes live groups.
+ return await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)
async def reconcile_failed_runs(
self,
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 0c0289287716..ab9f4ca2ecf2 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
@@ -2,8 +2,15 @@
Postgres-based job queue for warehouse source batch processing.
Replaces the Kafka topic `warehouse_sources_jobs` with direct Postgres inserts
-and advisory-lock-based coordination. All SQL is isolated here so that the
-producer (Temporal activity) and consumer share a single interface to the queue.
+and lease-based coordination. All SQL is isolated here so that the producer
+(Temporal activity) and consumer share a single interface to the queue.
+
+Group ownership uses a row-based lease (`sourcegrouplease`) keyed by
+(team_id, schema_id): claimed via a conditional upsert, renewed by the
+consumer heartbeat, and reclaimable by any pod once it expires. This replaces
+the old session-scoped Postgres advisory lock, whose ownership was tied to a
+live server session and so could be orphaned indefinitely on SIGKILL, pgbouncer
+session lingering, or node loss — wedging the whole loader fleet.
"""
from __future__ import annotations
@@ -20,9 +27,14 @@ from psycopg.rows import dict_row
BATCH_TABLE = "sourcebatch"
STATUS_TABLE = "sourcebatchstatus"
STATUS_VIEW = "v_latest_source_batch_status"
+LEASE_TABLE = "sourcegrouplease"
-# Namespace for advisory locks to avoid collisions with other PostHog subsystems.
-ADVISORY_LOCK_NAMESPACE = 0x57485300 # "WHS\0" in hex
+# 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
+# recovery_grace_seconds so lease reclamation and the executing-status recovery
+# sweep fire together.
+LEASE_TTL_SECONDS = 300
# Partition pruning hint: only scan partitions within this window.
# Set to 2x the retention period so the planner can skip dropped
@@ -43,6 +55,8 @@ def pending_batch_select_columns(status_alias: str) -> str:
"""
+# Retained for the duckgres sink, which still coordinates via session advisory
+# locks (see duckgres/jobs_db.py). The delta queue now uses leases instead.
async def unlock_advisory_locks(
conn: psycopg.AsyncConnection[Any],
*,
@@ -218,16 +232,26 @@ class BatchQueue:
async def get_unprocessed_and_lock(
conn: psycopg.AsyncConnection[Any],
*,
+ owner_token: str,
limit: int = 50,
retry_backoff_base_seconds: int = 0,
+ lease_ttl_seconds: int = LEASE_TTL_SECONDS,
) -> list[PendingBatch]:
- """Fetch unprocessed batches whose (team_id, schema_id) advisory lock is acquirable.
+ """Fetch unprocessed batches whose (team_id, schema_id) group lease is claimable by ``owner_token``.
+
+ Group ownership is a row in ``sourcegrouplease`` keyed by
+ (team_id, schema_id). The outer query claims-or-renews the lease for
+ each candidate group in a single writable CTE: a group is returned only
+ when the lease is free (no row), already owned by ``owner_token``, or
+ expired (a previous owner abandoned it). A live lease held by another
+ pod fails the conditional ``DO UPDATE`` and that group's rows are
+ dropped by the ``JOIN claimed``. This replaces the old session advisory
+ lock so an abandoned group simply expires rather than wedging the fleet.
Uses a MATERIALIZED CTE so that candidate selection (with LIMIT) is
- fully resolved before any advisory lock is acquired. Without this,
- Postgres is free to evaluate pg_try_advisory_lock on rows that are
- later discarded by other predicates or by LIMIT, creating phantom
- locks that unlock_for_batches never releases.
+ 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.
``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on
the age of the latest status row: a batch is only eligible when
@@ -244,9 +268,9 @@ class BatchQueue:
In-flight schema gating: a batch is also excluded if its
``(team_id, schema_id)`` already has an ``executing`` batch (i.e. the
- per-schema advisory lock is held by the pod processing it). This keeps a
- schema's other queued runs from consuming the ``LIMIT`` window ahead of
- the advisory-lock filter and starving other schemas' claimable work.
+ group is being processed by its lease holder). This keeps a schema's
+ other queued runs from consuming the ``LIMIT`` window ahead of the lease
+ claim and starving other schemas' claimable work.
"""
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
@@ -302,13 +326,32 @@ class BatchQueue:
)
ORDER BY b.created_at ASC, b.batch_index ASC
LIMIT %(limit)s
+ ),
+ candidate_groups AS (
+ SELECT DISTINCT team_id, schema_id FROM candidates
+ ),
+ claimed AS (
+ INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at)
+ SELECT team_id, schema_id, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now()
+ FROM candidate_groups
+ ON CONFLICT (team_id, schema_id) DO UPDATE
+ SET owner_token = excluded.owner_token,
+ expires_at = excluded.expires_at,
+ acquired_at = CASE
+ WHEN {LEASE_TABLE}.owner_token = excluded.owner_token THEN {LEASE_TABLE}.acquired_at
+ ELSE now()
+ END,
+ updated_at = now()
+ WHERE {LEASE_TABLE}.expires_at < now()
+ OR {LEASE_TABLE}.owner_token = excluded.owner_token
+ RETURNING team_id, schema_id
)
SELECT c.*
FROM candidates c
- WHERE pg_try_advisory_lock({ADVISORY_LOCK_NAMESPACE}, hashtext(c.team_id::text || ':' || c.schema_id))
+ JOIN claimed USING (team_id, schema_id)
ORDER BY c.created_at ASC, c.batch_index ASC
""",
- {"limit": limit, "backoff": retry_backoff_base_seconds},
+ {"limit": limit, "backoff": retry_backoff_base_seconds, "owner": owner_token, "ttl": lease_ttl_seconds},
)
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
@@ -336,27 +379,54 @@ class BatchQueue:
},
)
+ @staticmethod
+ async def renew_lease(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int,
+ schema_id: str,
+ owner_token: str,
+ lease_ttl_seconds: int = LEASE_TTL_SECONDS,
+ ) -> bool:
+ """Extend this owner's group lease. Returns False if the lease was lost (row gone or reclaimed)."""
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"""
+ UPDATE {LEASE_TABLE}
+ SET expires_at = now() + make_interval(secs => %(ttl)s), updated_at = now()
+ WHERE team_id = %(team_id)s AND schema_id = %(schema_id)s AND owner_token = %(owner)s
+ RETURNING 1
+ """,
+ {"team_id": team_id, "schema_id": schema_id, "owner": owner_token, "ttl": lease_ttl_seconds},
+ )
+ return (await cur.fetchone()) is not None
+
@staticmethod
async def verify_advisory_lock(
conn: psycopg.AsyncConnection[Any],
*,
team_id: int,
schema_id: str,
+ owner_token: str,
) -> bool:
- """Check if this session still holds the advisory lock for (team_id, schema_id)."""
+ """Check whether ``owner_token`` still holds a live group lease for (team_id, schema_id).
+
+ Named ``verify_advisory_lock`` for interface continuity with the
+ consumer engine and the duckgres sink; ownership is now a lease row, not
+ a session advisory lock.
+ """
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
+ SELECT 1 FROM {LEASE_TABLE}
+ WHERE team_id = %(team_id)s
+ AND schema_id = %(schema_id)s
+ AND owner_token = %(owner)s
+ AND expires_at > now()
)
""",
- {"key": f"{team_id}:{schema_id}"},
+ {"team_id": team_id, "schema_id": schema_id, "owner": owner_token},
)
row = await cur.fetchone()
return bool(row and row[0])
@@ -366,48 +436,39 @@ class BatchQueue:
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).
+ """Find batches stuck in 'executing' whose group lease is absent or expired (previous pod gone).
- Uses a MATERIALIZED CTE for the same reason as get_unprocessed_and_lock:
- candidate rows are fully resolved before any advisory lock is probed.
+ A batch is orphaned when its latest status is 'executing', that status
+ row is older than ``grace_seconds`` (the heartbeat stopped refreshing
+ it), and no live lease covers its (team_id, schema_id) group. Unlike the
+ old advisory-lock probe — which a lingering pgbouncer session could hold
+ indefinitely and block recovery — an abandoned lease simply expires, so
+ this sweep can always reclaim a genuinely orphaned group.
``grace_seconds`` requires the 'executing' status row to be older than
this 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(
f"""
- WITH candidates AS MATERIALIZED (
- SELECT
- {pending_batch_select_columns("s")}
- 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 = 'executing'
- AND s.created_at <= now() - make_interval(secs => %(grace)s)
- ORDER BY b.created_at ASC, b.batch_index ASC
- )
- SELECT c.*
- FROM candidates c
- WHERE pg_try_advisory_lock({ADVISORY_LOCK_NAMESPACE}, hashtext(c.team_id::text || ':' || c.schema_id))
- ORDER BY c.created_at ASC, c.batch_index ASC
+ SELECT
+ {pending_batch_select_columns("s")}
+ FROM {BATCH_TABLE} b
+ JOIN {STATUS_VIEW} s ON b.id = s.batch_id
+ LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND s.job_state = 'executing'
+ AND s.created_at <= now() - make_interval(secs => %(grace)s)
+ AND (l.team_id IS NULL OR l.expires_at <= now())
+ ORDER BY b.created_at ASC, b.batch_index ASC
""",
{"grace": grace_seconds},
)
rows = await cur.fetchall()
- result = [PendingBatch(**row) for row in rows]
-
- if not keep_locks:
- await BatchQueue.unlock_for_batches(conn, batches=result)
-
- return result
+ return [PendingBatch(**row) for row in rows]
@staticmethod
async def fail_run(
@@ -518,14 +579,41 @@ class BatchQueue:
conn: psycopg.AsyncConnection[Any],
*,
batches: list[PendingBatch],
+ owner_token: str,
) -> None:
- """Release advisory locks once per returned batch row.
+ """Release the group leases for ``batches``' (team_id, schema_id) groups held by ``owner_token``.
- The MATERIALIZED CTE in get_unprocessed_and_lock ensures locks are
- only acquired on rows that actually appear in the result set, so
- one unlock per row balances the depth exactly.
+ 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.
"""
- await unlock_advisory_locks(conn, batches=batches, namespace=ADVISORY_LOCK_NAMESPACE)
+ pairs = list({(b.team_id, b.schema_id) for b in batches})
+ if not pairs:
+ return
+ team_ids = [team_id for team_id, _ in pairs]
+ schema_ids = [schema_id for _, schema_id in pairs]
+ 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[])
+ )
+ """,
+ {"owner": owner_token, "team_ids": team_ids, "schema_ids": schema_ids},
+ )
+
+ @staticmethod
+ async def release_all_owned_leases(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ owner_token: str,
+ ) -> None:
+ """Delete every group lease held by ``owner_token``. Used for best-effort cleanup on shutdown."""
+ await conn.execute(
+ f"DELETE FROM {LEASE_TABLE} WHERE owner_token = %(owner)s",
+ {"owner": owner_token},
+ )
@staticmethod
def get_run_activity_summary(
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 0b6f74c35aa4..b302fd110926 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
@@ -308,7 +308,9 @@ class TestRecoverySweep:
attempt=1,
error_response={"error": "executing timed out - pod restart or OOM"},
)
- mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch])
+ mock_unlock.assert_called_once_with(
+ consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token
+ )
@pytest.mark.asyncio
async def test_fails_exhausted_stale_batch(self):
@@ -334,7 +336,7 @@ class TestRecoverySweep:
mock_unlock.assert_called_once()
@pytest.mark.asyncio
- async def test_recovery_sweep_releases_probe_locks_on_error(self):
+ async def test_recovery_sweep_unlocks_on_error(self):
consumer = _make_consumer(max_attempts=3)
stale_batch = _make_batch(latest_attempt=1)
@@ -357,7 +359,9 @@ class TestRecoverySweep:
):
await consumer._recovery_sweep()
- mock_unlock.assert_called_once_with(consumer._recovery_conn, batches=[stale_batch])
+ mock_unlock.assert_called_once_with(
+ consumer._recovery_conn, batches=[stale_batch], owner_token=consumer._owner_token
+ )
class TestFailRun:
@@ -834,3 +838,81 @@ class TestOwnershipVerification:
assert result is True
mock_verify.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_heartbeat_stops_when_lease_renewal_fails(self):
+ # A lost lease (another pod reclaimed the group) must end the heartbeat so the
+ # group isn't double-processed while still re-stamping executing.
+ consumer = _make_consumer()
+ consumer._config.recovery_grace_seconds = 30 # heartbeat interval -> max(30/3, 10) = 10s
+ batch = _make_batch()
+ lock_conn = _make_healthy_conn()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.renew_lease",
+ new_callable=AsyncMock,
+ return_value=False,
+ ) as mock_renew,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ) as mock_status,
+ patch("asyncio.sleep", new_callable=AsyncMock), # don't wait the real interval
+ ):
+ await consumer._batch_heartbeat(lock_conn, batch, attempt=1)
+
+ mock_renew.assert_awaited_once()
+ # Lease lost -> heartbeat returns before re-stamping executing.
+ mock_status.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_heartbeat_renews_lease_then_restamps_executing(self):
+ # The success path: a held lease is renewed and the executing-status grace
+ # window is refreshed on the same beat. update_status raising ends the loop.
+ consumer = _make_consumer()
+ consumer._config.recovery_grace_seconds = 30
+ batch = _make_batch()
+ lock_conn = _make_healthy_conn()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.renew_lease",
+ new_callable=AsyncMock,
+ return_value=True,
+ ) as mock_renew,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ side_effect=Exception("stop the loop"),
+ ) as mock_status,
+ patch("asyncio.sleep", new_callable=AsyncMock),
+ ):
+ await consumer._batch_heartbeat(lock_conn, batch, attempt=2)
+
+ mock_renew.assert_awaited_once_with(
+ lock_conn,
+ team_id=batch.team_id,
+ schema_id=batch.schema_id,
+ owner_token=consumer._owner_token,
+ lease_ttl_seconds=consumer._lease_ttl_seconds,
+ )
+ mock_status.assert_awaited_once()
+
+
+class TestShutdown:
+ @pytest.mark.asyncio
+ async def test_close_releases_owned_leases(self):
+ consumer = _make_consumer()
+ main_conn = _make_healthy_conn()
+ consumer._conn = main_conn
+ consumer._recovery_conn = _make_healthy_conn()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ) as mock_release:
+ await consumer._close()
+
+ mock_release.assert_awaited_once_with(main_conn, owner_token=consumer._owner_token)
+ main_conn.close.assert_awaited_once()
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 113db955db3e..ebe3e42c8f8e 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,4 +1,5 @@
from typing import Any
+from uuid import uuid4
import pytest
@@ -6,12 +7,25 @@ import psycopg
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BATCH_TABLE,
+ LEASE_TABLE,
STATUS_TABLE,
STATUS_VIEW,
BatchQueue,
PendingBatch,
)
+# Distinct per-pod identities for the group-lease tests.
+OWNER_A = str(uuid4())
+OWNER_B = str(uuid4())
+
+
+async def _claim(conn: psycopg.AsyncConnection[Any], owner: str = OWNER_A, **kwargs: Any) -> list[PendingBatch]:
+ return await BatchQueue.get_unprocessed_and_lock(conn, owner_token=owner, **kwargs)
+
+
+async def _release(conn: psycopg.AsyncConnection[Any], *, batches: list[PendingBatch], owner: str = OWNER_A) -> None:
+ await BatchQueue.unlock_for_batches(conn, batches=batches, owner_token=owner)
+
def _get_test_database_url() -> str:
from django.db import connection
@@ -58,6 +72,18 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
""")
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {LEASE_TABLE} (
+ id BIGSERIAL PRIMARY KEY,
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ owner_token VARCHAR(64) NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT sgl_team_schema_uniq UNIQUE (team_id, schema_id)
+ )
+ """)
conn.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")
conn.execute(f"""
CREATE VIEW {STATUS_VIEW} AS
@@ -68,7 +94,7 @@ def _ensure_tables(conn: psycopg.Connection[Any]) -> None:
def _truncate_tables(conn: psycopg.Connection[Any]) -> None:
- conn.execute(f"TRUNCATE {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE")
+ conn.execute(f"TRUNCATE {STATUS_TABLE}, {BATCH_TABLE}, {LEASE_TABLE} RESTART IDENTITY CASCADE")
_BATCH_DEFAULTS: dict[str, Any] = {
@@ -153,7 +179,7 @@ class TestBatchQueueGetUnprocessed:
await _insert_batch(conn, batch_index=1)
await _insert_batch(conn, batch_index=2)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert len(batches) == 3
assert sorted(b.batch_index for b in batches) == [0, 1, 2]
@@ -163,7 +189,7 @@ class TestBatchQueueGetUnprocessed:
bid = await _insert_batch(conn)
await BatchQueue.update_status(conn, batch_id=bid, job_state="succeeded", attempt=1)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert len(batches) == 0
@@ -172,7 +198,7 @@ class TestBatchQueueGetUnprocessed:
bid = await _insert_batch(conn)
await BatchQueue.update_status(conn, batch_id=bid, job_state="waiting_retry", attempt=1)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert len(batches) == 1
assert batches[0].latest_attempt == 1
@@ -183,7 +209,7 @@ class TestBatchQueueGetUnprocessed:
bid2 = await _insert_batch(conn, batch_index=1, run_uuid="run-fail")
await BatchQueue.update_status(conn, batch_id=bid2, job_state="failed", attempt=1)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert len(batches) == 0
@@ -192,7 +218,7 @@ class TestBatchQueueGetUnprocessed:
for i in range(10):
await _insert_batch(conn, batch_index=i)
- batches = await BatchQueue.get_unprocessed_and_lock(conn, limit=3)
+ batches = await _claim(conn, limit=3)
assert len(batches) == 3
@@ -204,7 +230,7 @@ class TestBatchQueueGetUnprocessed:
await _insert_batch(conn, schema_id="busy", run_uuid="run-b", batch_index=0)
await BatchQueue.update_status(conn, batch_id=executing_bid, job_state="executing", attempt=1)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert batches == []
@@ -218,10 +244,10 @@ class TestBatchQueueGetUnprocessed:
await _insert_batch(conn, schema_id="A", run_uuid="a-run-2", batch_index=i)
await _insert_batch(conn, schema_id="B", run_uuid="b-run-1", batch_index=0) # newest
- batches = await BatchQueue.get_unprocessed_and_lock(conn, limit=3)
+ batches = await _claim(conn, limit=3)
assert [b.schema_id for b in batches] == ["B"]
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await _release(conn, batches=batches)
@pytest.mark.asyncio
async def test_in_flight_gating_clears_after_terminal_status(self, conn):
@@ -236,17 +262,17 @@ class TestBatchQueueGetUnprocessed:
[exec_bid],
)
- assert await BatchQueue.get_unprocessed_and_lock(conn) == []
+ assert await _claim(conn) == []
await conn.execute(
f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) VALUES (%s, 'succeeded', 1, now())",
[exec_bid],
)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert [b.run_uuid for b in batches] == ["run-2"]
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await _release(conn, batches=batches)
@pytest.mark.django_db(transaction=True)
@@ -276,103 +302,237 @@ class TestBatchQueueFailRun:
assert count == 2
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn)
assert len(batches) == 0
+async def _insert_lease(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ team_id: int = 1,
+ schema_id: str = "schema-1",
+ owner: str = OWNER_A,
+ expires_in_seconds: int = 300,
+) -> None:
+ """Insert a lease row directly. Negative ``expires_in_seconds`` makes it already expired."""
+ await conn.execute(
+ f"INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at) "
+ f"VALUES (%s, %s, %s, now() + make_interval(secs => %s))",
+ [team_id, schema_id, owner, expires_in_seconds],
+ )
+
+
+async def _lease_owner(
+ conn: psycopg.AsyncConnection[Any], *, team_id: int = 1, schema_id: str = "schema-1"
+) -> str | None:
+ row = await (
+ await conn.execute(
+ f"SELECT owner_token FROM {LEASE_TABLE} WHERE team_id = %s AND schema_id = %s", [team_id, schema_id]
+ )
+ ).fetchone()
+ return row[0] if row else None
+
+
+async def _lease_expiry(conn: psycopg.AsyncConnection[Any], *, team_id: int = 1, schema_id: str = "schema-1") -> Any:
+ row = await (
+ await conn.execute(
+ f"SELECT expires_at FROM {LEASE_TABLE} WHERE team_id = %s AND schema_id = %s", [team_id, schema_id]
+ )
+ ).fetchone()
+ return row[0] if row else None
+
+
+async def _lease_count(conn: psycopg.AsyncConnection[Any], *, team_id: int = 1, schema_id: str = "schema-1") -> int:
+ row = await (
+ await conn.execute(
+ f"SELECT count(*) FROM {LEASE_TABLE} WHERE team_id = %s AND schema_id = %s", [team_id, schema_id]
+ )
+ ).fetchone()
+ return int(row[0]) if row else 0
+
+
+async def _insert_backdated_executing(
+ conn: psycopg.AsyncConnection[Any], *, batch_id: str, age_seconds: int = 120, attempt: int = 1
+) -> None:
+ await conn.execute(
+ f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
+ f"VALUES (%s, 'executing', %s, now() - make_interval(secs => %s))",
+ [batch_id, attempt, age_seconds],
+ )
+
+
@pytest.mark.django_db(transaction=True)
-class TestBatchQueueAdvisoryLocks:
+class TestBatchQueueGroupLease:
@pytest.mark.asyncio
- async def test_unlock_for_batches_releases_locks(self, conn, conn_b):
+ async def test_live_lease_excludes_other_owner(self, conn, conn_b):
await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=1)
await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=2)
- batches = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches = await _claim(conn, owner=OWNER_A)
assert len(batches) == 3
+ assert await _lease_owner(conn, schema_id="s1") == OWNER_A
+
+ batches_b = await _claim(conn_b, owner=OWNER_B)
+ assert len(batches_b) == 0, "another owner must not claim a group with a live lease"
- batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
- assert len(batches_b) == 0, "conn_b should not acquire lock held by conn"
+ await _release(conn, batches=batches, owner=OWNER_A)
+ assert await _lease_owner(conn, schema_id="s1") is None
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ batches_b = await _claim(conn_b, owner=OWNER_B)
+ assert len(batches_b) == 3, "the group is claimable once its lease is released"
+ assert await _lease_owner(conn, schema_id="s1") == OWNER_B
+
+ @pytest.mark.asyncio
+ async def test_same_owner_reclaim_is_idempotent(self, conn):
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=1)
- batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
- assert len(batches_b) == 3, "conn_b should acquire lock after conn released it"
+ first = await _claim(conn, owner=OWNER_A)
+ assert len(first) == 2
+ expiry_1 = await _lease_expiry(conn, schema_id="s1")
- await BatchQueue.unlock_for_batches(conn_b, batches=batches_b)
+ # Re-claiming the same group renews (no ON CONFLICT error, single lease row, later expiry).
+ second = await _claim(conn, owner=OWNER_A)
+ assert len(second) == 2
+ assert await _lease_count(conn, schema_id="s1") == 1
+ assert await _lease_expiry(conn, schema_id="s1") >= expiry_1
@pytest.mark.asyncio
- async def test_different_keys_lock_independently(self, conn, conn_b):
+ async def test_different_keys_lease_independently(self, conn, conn_b):
await _insert_batch(conn, team_id=1, schema_id="s1")
await _insert_batch(conn, team_id=2, schema_id="s2")
- batches_a = await BatchQueue.get_unprocessed_and_lock(conn)
+ batches_a = await _claim(conn, owner=OWNER_A)
assert len(batches_a) == 2
- await BatchQueue.unlock_for_batches(conn, batches=[b for b in batches_a if b.schema_id == "s1"])
+ await _release(conn, batches=[b for b in batches_a if b.schema_id == "s1"], owner=OWNER_A)
- batches_b = await BatchQueue.get_unprocessed_and_lock(conn_b)
- assert len(batches_b) == 1
+ batches_b = await _claim(conn_b, owner=OWNER_B)
+ assert len(batches_b) == 1, "only the released group is reclaimable"
assert batches_b[0].schema_id == "s1"
- await BatchQueue.unlock_for_batches(conn, batches=[b for b in batches_a if b.schema_id == "s2"])
- await BatchQueue.unlock_for_batches(conn_b, batches=batches_b)
+ @pytest.mark.asyncio
+ async def test_expired_lease_is_reclaimed(self, conn, conn_b):
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=0)
+ await _insert_batch(conn, team_id=1, schema_id="s1", batch_index=1)
+ # A previous owner died without releasing; its lease has already expired.
+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=-1)
+
+ batches = await _claim(conn_b, owner=OWNER_B)
+
+ assert len(batches) == 2, "an expired lease must not block a new owner"
+ assert await _lease_owner(conn, schema_id="s1") == OWNER_B
+ assert await _lease_expiry(conn, schema_id="s1") is not None
+
+ @pytest.mark.asyncio
+ async def test_release_does_not_delete_another_owners_lease(self, conn):
+ # A slow group whose lease already expired and was reclaimed by another pod
+ # must not delete the new owner's lease when its own finally-block releases.
+ await _insert_batch(conn, team_id=1, schema_id="s1")
+ claimed = await _claim(conn, owner=OWNER_B)
+ assert await _lease_owner(conn, schema_id="s1") == OWNER_B
+
+ # The old owner (A) tries to release the same group; its token no longer matches.
+ await _release(conn, batches=claimed, owner=OWNER_A)
+
+ assert await _lease_owner(conn, schema_id="s1") == OWNER_B, "a non-owner release must be a no-op"
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueLeaseRenewal:
+ @pytest.mark.asyncio
+ async def test_renew_extends_expiry_for_owner(self, conn):
+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=10)
+ before = await _lease_expiry(conn, schema_id="s1")
+
+ renewed = await BatchQueue.renew_lease(
+ conn, team_id=1, schema_id="s1", owner_token=OWNER_A, lease_ttl_seconds=300
+ )
+
+ assert renewed is True
+ assert await _lease_expiry(conn, schema_id="s1") > before
+
+ @pytest.mark.asyncio
+ async def test_renew_returns_false_for_non_owner(self, conn):
+ await _insert_lease(conn, team_id=1, schema_id="s1", owner=OWNER_A, expires_in_seconds=300)
+
+ renewed = await BatchQueue.renew_lease(
+ conn, team_id=1, schema_id="s1", owner_token=OWNER_B, lease_ttl_seconds=300
+ )
+
+ assert renewed is False, "a non-owner cannot renew the lease"
+
+ @pytest.mark.asyncio
+ async def test_renew_returns_false_when_absent(self, conn):
+ renewed = await BatchQueue.renew_lease(
+ conn, team_id=1, schema_id="s1", owner_token=OWNER_A, lease_ttl_seconds=300
+ )
+
+ assert renewed is False
@pytest.mark.django_db(transaction=True)
-class TestBatchQueueStaleExecuting:
+class TestGroupLeaseRecovery:
@pytest.mark.asyncio
- async def test_finds_orphaned_executing_batches(self, conn, conn_b, _db_url):
+ async def test_absent_lease_orphan_is_recovered(self, conn):
bid = await _insert_batch(conn)
+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120, attempt=1)
- async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as orphan_conn:
- await BatchQueue.get_unprocessed_and_lock(orphan_conn)
- await BatchQueue.update_status(orphan_conn, batch_id=bid, job_state="executing", attempt=1)
- # orphan_conn is now closed — advisory lock released
+ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)
- stale = await BatchQueue.get_stale_executing(conn, grace_seconds=0)
assert len(stale) == 1
assert str(stale[0].id) == bid
assert stale[0].latest_attempt == 1
@pytest.mark.asyncio
- async def test_does_not_find_actively_held_batches(self, conn, conn_b):
+ async def test_expired_lease_orphan_is_recovered(self, conn):
+ """The prod-US wedge, in lease terms.
+
+ A pod is SIGKILLed mid-group and never releases ownership; its lease
+ expires. Recovery must reclaim the orphaned 'executing' batch off the
+ expired lease. The old advisory lock had no expiry, so an orphaned owner
+ (SIGKILL / pgbouncer session lingering / node loss) blocked recovery
+ indefinitely — the wedge. An expired lease cannot.
+ """
bid = await _insert_batch(conn)
+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120)
+ await _insert_lease(conn, owner=OWNER_A, expires_in_seconds=-1)
- await BatchQueue.get_unprocessed_and_lock(conn)
- await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
-
- stale = await BatchQueue.get_stale_executing(conn_b, grace_seconds=0)
- assert len(stale) == 0
+ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)
- await conn.execute("SELECT pg_advisory_unlock_all()")
+ assert len(stale) == 1
+ assert str(stale[0].id) == bid
@pytest.mark.asyncio
- async def test_grace_shields_recent_executing_from_orphan_sweep(self, conn, _db_url):
+ async def test_live_lease_shields_executing_from_recovery(self, conn):
+ """A live lease means the owner is alive (heartbeating); its group is never reclaimed.
+
+ This is the discriminating guard for the lease behaviour: the batch's
+ 'executing' status is already past the grace window, so the only thing
+ keeping recovery from reclaiming it is the live lease. The pre-lease sweep
+ had no lease awareness and would reclaim it here.
+ """
bid = await _insert_batch(conn)
+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120)
+ await _insert_lease(conn, owner=OWNER_A, expires_in_seconds=300)
- async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as orphan_conn:
- await BatchQueue.get_unprocessed_and_lock(orphan_conn)
- await BatchQueue.update_status(orphan_conn, batch_id=bid, job_state="executing", attempt=1)
- # orphan_conn closed — advisory lock released, status row is fresh.
+ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)
- # Fresh 'executing' must be ignored until it ages past the grace window:
- # a live worker that briefly lost its psycopg session shouldn't be
- # racily reclaimed.
- assert await BatchQueue.get_stale_executing(conn, grace_seconds=3600) == []
+ assert stale == [], "a live lease shields its group from recovery"
@pytest.mark.asyncio
- async def test_grace_lets_aged_executing_through(self, conn, _db_url):
+ async def test_grace_shields_recent_executing(self, conn):
bid = await _insert_batch(conn)
+ # Fresh 'executing', no lease: still must wait out the grace window before recovery.
+ await BatchQueue.update_status(conn, batch_id=bid, job_state="executing", attempt=1)
- async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as orphan_conn:
- await BatchQueue.get_unprocessed_and_lock(orphan_conn)
- # Backdate the status row so it appears older than the grace window.
- await conn.execute(
- f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
- f"VALUES (%s, 'executing', 1, now() - interval '120 seconds')",
- [bid],
- )
+ assert await BatchQueue.get_stale_executing(conn, grace_seconds=3600) == []
+
+ @pytest.mark.asyncio
+ async def test_grace_lets_aged_executing_through(self, conn):
+ bid = await _insert_batch(conn)
+ await _insert_backdated_executing(conn, batch_id=bid, age_seconds=120)
stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)
assert len(stale) == 1
@@ -387,12 +547,12 @@ class TestBatchQueueRetryBackoff:
await BatchQueue.update_status(conn, batch_id=bid, job_state="waiting_retry", attempt=1)
# With a large backoff base, the just-failed batch isn't picked up.
- assert await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=3600) == []
+ assert await _claim(conn, retry_backoff_base_seconds=3600) == []
# With backoff disabled, it's eligible immediately.
- batches = await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=0)
+ batches = await _claim(conn, retry_backoff_base_seconds=0)
assert len(batches) == 1
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await _release(conn, batches=batches)
@pytest.mark.asyncio
async def test_backoff_scales_with_attempt(self, conn):
@@ -405,21 +565,21 @@ class TestBatchQueueRetryBackoff:
)
# base=5, attempt=3 -> 15s required, only 10s elapsed: blocked.
- assert await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=5) == []
+ assert await _claim(conn, retry_backoff_base_seconds=5) == []
# base=3, attempt=3 -> 9s required, 10s elapsed: eligible.
- batches = await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=3)
+ batches = await _claim(conn, retry_backoff_base_seconds=3)
assert len(batches) == 1
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await _release(conn, batches=batches)
@pytest.mark.asyncio
async def test_backoff_does_not_gate_first_pickup(self, conn):
# batches with no status rows (s.batch_id IS NULL) must always be eligible,
# regardless of the backoff knob.
await _insert_batch(conn)
- batches = await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=3600)
+ batches = await _claim(conn, retry_backoff_base_seconds=3600)
assert len(batches) == 1
- await BatchQueue.unlock_for_batches(conn, batches=batches)
+ await _release(conn, batches=batches)
class TestPendingBatchToExportSignal:
diff --git a/products/warehouse_sources_queue/backend/migrations/0004_source_group_lease.py b/products/warehouse_sources_queue/backend/migrations/0004_source_group_lease.py
new file mode 100644
index 000000000000..40395b5738b2
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0004_source_group_lease.py
@@ -0,0 +1,68 @@
+from django.db import migrations, models
+
+
+def _create_group_lease_table(apps, schema_editor):
+ schema_editor.execute("""
+ CREATE TABLE sourcegrouplease (
+ id BIGSERIAL PRIMARY KEY,
+ team_id BIGINT NOT NULL,
+ schema_id VARCHAR(200) NOT NULL,
+ owner_token VARCHAR(64) NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ acquired_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT sgl_team_schema_uniq UNIQUE (team_id, schema_id)
+ )
+ """)
+ schema_editor.execute("""
+ CREATE INDEX sgl_expires_at_idx ON sourcegrouplease (expires_at)
+ """)
+
+
+def _drop_group_lease_table(apps, schema_editor):
+ schema_editor.execute("DROP TABLE IF EXISTS sourcegrouplease CASCADE")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources_queue", "0003_duckgres_sink"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="SourceGroupLease",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("team_id", models.BigIntegerField()),
+ ("schema_id", models.CharField(max_length=200)),
+ (
+ "owner_token",
+ models.CharField(
+ help_text="Per-pod identity (uuid4) of the current lease holder.",
+ max_length=64,
+ ),
+ ),
+ ("expires_at", models.DateTimeField()),
+ ("acquired_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "db_table": "sourcegrouplease",
+ "constraints": [
+ models.UniqueConstraint(fields=("team_id", "schema_id"), name="sgl_team_schema_uniq")
+ ],
+ "indexes": [models.Index(fields=["expires_at"], name="sgl_expires_at_idx")],
+ },
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(_create_group_lease_table, _drop_group_lease_table),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
index 0d9e5787f4a4..6dd9cfaaa442 100644
--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_duckgres_sink
+0004_source_group_lease
\ No newline at end of file
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
index e9b0e7f64938..e2f706e965b3 100644
--- a/products/warehouse_sources_queue/backend/models.py
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -114,6 +114,36 @@ class SourceBatchDuckgresStatus(UUIDModel):
]
+class SourceGroupLease(models.Model):
+ """Lease-based mutual exclusion for processing a (team_id, schema_id) group.
+
+ Replaces the session-scoped Postgres advisory lock that previously gated
+ group claiming. A lease row is claimed via a conditional upsert and renewed
+ by the consumer heartbeat; an abandoned lease (pod SIGKILLed, pgbouncer
+ session lingering, node lost) simply expires, so any surviving pod can
+ reclaim the group once ``expires_at`` passes. All access is via raw SQL in
+ ``postgres_queue/jobs_db.py`` — this model exists for migration/introspection.
+ """
+
+ team_id = models.BigIntegerField()
+ schema_id = models.CharField(max_length=200)
+ owner_token = models.CharField(max_length=64, help_text="Per-pod identity (uuid4) of the current lease holder.")
+ expires_at = models.DateTimeField()
+ acquired_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ __repr__ = sane_repr("team_id", "schema_id", "owner_token", "expires_at")
+
+ class Meta:
+ db_table = "sourcegrouplease"
+ constraints = [
+ models.UniqueConstraint(fields=["team_id", "schema_id"], name="sgl_team_schema_uniq"),
+ ]
+ indexes = [
+ models.Index(fields=["expires_at"], name="sgl_expires_at_idx"),
+ ]
+
+
class SourceBatchDuckgresApply(ProductTeamModel, UUIDModel):
schema_id = models.CharField(max_length=200)
run_uuid = models.CharField(max_length=200)