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): per-group connection isolation for v3 batch consumer (#66720)

estefaniac9dad7221a96
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 763ef3828e60..3fe9301168d2 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
@@ -36,6 +36,8 @@ RECONCILE_INTERVAL_SECONDS = 300.0
RECONCILE_GRACE_SECONDS = 120 # don't race a _fail_run that is still in flight
RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphaned by consumer outages
+SHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0
+
class OwnershipLostError(Exception):
"""Raised when the group lease for a (team_id, schema_id) is no longer held by this consumer."""
@@ -89,6 +91,11 @@ class BatchConsumerAdapter(Protocol):
executing_state: str
succeeded_state: str
waiting_retry_state: str
+ # Whether each group task gets its own dedicated connection. Lease-based
+ # adapters set True (lease ownership is token-based, any connection works).
+ # Advisory-lock-based adapters set False (lock is session-scoped, must stay
+ # on the poll connection that acquired it).
+ per_group_connections: bool
async def fetch_and_lock(
self,
@@ -203,15 +210,14 @@ class BatchConsumer:
self._owner_token = str(uuid4())
self._health_reporter = health_reporter
self._metrics = metrics or DELTA_CONSUMER_METRICS
- self._semaphore = asyncio.Semaphore(config.max_concurrency)
self._shutdown = asyncio.Event()
- self._conn: psycopg.AsyncConnection[Any] | None = None
+ self._poll_conn: psycopg.AsyncConnection[Any] | None = None
self._recovery_conn: psycopg.AsyncConnection[Any] | None = None
- # Serialize reconnects: concurrent groups all hit _ensure_*_conn on a bounce; without a lock each would dial its own connection and orphan all but the last.
- self._main_conn_lock = asyncio.Lock()
+ self._poll_conn_lock = asyncio.Lock()
self._recovery_conn_lock = asyncio.Lock()
self._recovery_task: asyncio.Task[None] | None = None
self._heartbeat_task: asyncio.Task[None] | None = None
+ self._in_flight: dict[tuple[int, str], asyncio.Task[None]] = {}
# Monotonic stamp of the last reconcile sweep; runs inside the recovery loop so both share one connection.
self._last_reconcile_monotonic = 0.0
# batch_id -> monotonic start, for the stuck-batch watchdog.
@@ -228,16 +234,15 @@ class BatchConsumer:
autocommit=True,
)
- async def _ensure_main_conn(self) -> psycopg.AsyncConnection[Any]:
- """Return the main queue connection, reconnecting if a failover/pgbouncer bounce dropped it."""
- if self._conn is not None and not self._conn.closed and not self._conn.broken:
- return self._conn
- async with self._main_conn_lock:
- # Re-check under the lock: another coroutine may have already reconnected while we waited.
- if self._conn is None or self._conn.closed or self._conn.broken:
- logger.warning(self._event("queue_db_main_connection_reconnecting"))
- self._conn = await self._connect()
- return self._conn
+ async def _ensure_poll_conn(self) -> psycopg.AsyncConnection[Any]:
+ """Return the poll connection, reconnecting if a failover/pgbouncer bounce dropped it."""
+ if self._poll_conn is not None and not self._poll_conn.closed and not self._poll_conn.broken:
+ return self._poll_conn
+ async with self._poll_conn_lock:
+ if self._poll_conn is None or self._poll_conn.closed or self._poll_conn.broken:
+ logger.warning(self._event("queue_db_poll_connection_reconnecting"))
+ self._poll_conn = await self._connect()
+ return self._poll_conn
async def _ensure_recovery_conn(self) -> psycopg.AsyncConnection[Any]:
"""Return the recovery/reconcile connection, reconnecting so a dropped one can't disable the sweeps forever."""
@@ -258,7 +263,7 @@ class BatchConsumer:
async def run(self) -> None:
self._install_signal_handlers()
- self._conn = await self._connect()
+ self._poll_conn = await self._connect()
self._recovery_conn = await self._connect()
logger.info(
@@ -267,6 +272,7 @@ class BatchConsumer:
poll_interval=self._config.poll_interval_seconds,
poll_limit=self._config.poll_limit,
owner_token=self._owner_token,
+ per_group_connections=self._adapter.per_group_connections,
)
try:
@@ -277,9 +283,21 @@ class BatchConsumer:
while not self._shutdown.is_set():
self._report_health()
+ self._reap_finished_tasks()
+
+ # Skip polling while shared-connection groups are in-flight to avoid concurrent _poll_conn access.
+ if not self._adapter.per_group_connections and self._in_flight:
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
+ continue
+
+ available = self._config.max_concurrency - len(self._in_flight)
+ if available <= 0:
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
+ continue
+
poll_start = time.monotonic()
try:
- conn = await self._ensure_main_conn()
+ conn = await self._ensure_poll_conn()
batches = await self._adapter.fetch_and_lock(
conn,
limit=self._config.poll_limit,
@@ -288,7 +306,6 @@ class BatchConsumer:
lease_ttl_seconds=self._lease_ttl_seconds,
)
except psycopg.OperationalError as e:
- # Queue DB unreachable — keep the pod alive; the next iteration reconnects.
logger.exception(self._event("poll_failed_queue_db_unreachable"))
capture_exception(e)
await self._wait_or_shutdown(self._config.poll_interval_seconds)
@@ -308,22 +325,49 @@ class BatchConsumer:
group_count=len(groups),
)
- self._metrics.active_groups.inc(len(groups))
- try:
- await asyncio.gather(
- *[self._process_group(key, group_batches) for key, group_batches in groups.items()]
- )
- finally:
- self._metrics.active_groups.dec(len(groups))
+ for key, group_batches in groups.items():
+ if key in self._in_flight:
+ continue
+ if len(self._in_flight) >= self._config.max_concurrency:
+ break
+ task = asyncio.create_task(self._process_group_tracked(key, group_batches))
+ self._in_flight[key] = task
+ self._metrics.active_groups.inc()
+
+ await self._wait_or_shutdown(self._config.poll_interval_seconds)
finally:
await self._close()
+ def _reap_finished_tasks(self) -> None:
+ """Remove completed group tasks from the in-flight registry."""
+ finished = [key for key, task in self._in_flight.items() if task.done()]
+ for key in finished:
+ self._in_flight.pop(key)
+ self._metrics.active_groups.dec()
+
+ async def _process_group_tracked(self, key: tuple[int, str], batches: list[PendingBatch]) -> None:
+ """Wrapper that ensures the group task never propagates exceptions to the event loop."""
+ try:
+ await self._process_group(key, batches)
+ except Exception as e:
+ logger.exception(
+ self._event("process_group_unhandled_error"),
+ 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
- # Pin the connection that claimed the group lease so status writes and lease renewals stay together.
- lock_conn = self._conn
- await self._semaphore.acquire()
+ owns_conn = self._adapter.per_group_connections
+ group_conn: psycopg.AsyncConnection[Any] | None = None
try:
+ if owns_conn:
+ group_conn = await self._connect()
+ else:
+ group_conn = self._poll_conn
+ assert group_conn is not None
+
for batch in batches:
if self._shutdown.is_set():
logger.info(
@@ -334,7 +378,7 @@ class BatchConsumer:
)
break
try:
- succeeded = await self._process_single(batch, lock_conn=lock_conn)
+ succeeded = await self._process_single(batch, lock_conn=group_conn)
except OwnershipLostError:
logger.warning(
self._event("ownership_lost_abandoning_group"),
@@ -343,7 +387,6 @@ class BatchConsumer:
)
break
except Exception as e:
- # A queue-DB write failing mid-batch (e.g. stale conn after a bounce) must cost this group, not the pod.
logger.exception(
self._event("process_single_unhandled_error"),
team_id=team_id,
@@ -354,8 +397,6 @@ class BatchConsumer:
capture_exception(e)
succeeded = False
if not succeeded:
- # Stop processing sibling batches in this run once one fails or
- # enters waiting_retry -- later batches depend on earlier ones.
logger.info(
self._event("group_halted_by_non_success"),
team_id=team_id,
@@ -365,18 +406,21 @@ class BatchConsumer:
)
break
finally:
- self._semaphore.release()
- try:
- assert lock_conn is not None
- await self._adapter.unlock(lock_conn, batches=batches, owner_token=self._owner_token)
- except Exception as e:
- # 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,
- external_data_schema_id=schema_id,
- )
- capture_exception(e)
+ if group_conn is not None:
+ try:
+ await self._adapter.unlock(group_conn, batches=batches, owner_token=self._owner_token)
+ except Exception as e:
+ logger.exception(
+ self._event("unlock_for_batches_failed"),
+ team_id=team_id,
+ external_data_schema_id=schema_id,
+ )
+ capture_exception(e)
+ if owns_conn and group_conn is not None:
+ try:
+ await group_conn.close()
+ except Exception:
+ pass
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."""
@@ -384,7 +428,7 @@ class BatchConsumer:
if lock_conn.closed or lock_conn.broken:
raise OwnershipLostError("lock session is dead")
return lock_conn
- return await self._ensure_main_conn()
+ return await self._ensure_poll_conn()
async def _verify_ownership(self, lock_conn: psycopg.AsyncConnection[Any] | None, batch: PendingBatch) -> None:
"""Raise OwnershipLostError if this consumer no longer holds the group lease."""
@@ -500,7 +544,7 @@ class BatchConsumer:
run_uuid=batch.run_uuid,
attempt=attempt,
)
- await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")
+ await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})", conn=lock_conn)
return False
status_conn = await self._get_status_conn(lock_conn)
@@ -526,12 +570,24 @@ class BatchConsumer:
heartbeat_task: asyncio.Task[None] | None = None
try:
start = time.monotonic()
- should_process = await self._adapter.should_process_batch(await self._ensure_main_conn(), batch=batch)
+ should_process = await self._adapter.should_process_batch(status_conn, batch=batch)
if should_process:
if lock_conn is not None:
heartbeat_task = asyncio.create_task(self._batch_heartbeat(lock_conn, batch, attempt))
await self._process_batch(batch)
- await self._adapter.after_batch_processed(await self._ensure_main_conn(), batch=batch)
+
+ # Cancel heartbeat before post-processing DB writes to avoid
+ # concurrent use of the group connection (psycopg async
+ # connections are not safe for concurrent coroutine access).
+ if heartbeat_task is not None:
+ heartbeat_task.cancel()
+ try:
+ await heartbeat_task
+ except asyncio.CancelledError:
+ pass
+ heartbeat_task = None
+
+ await self._adapter.after_batch_processed(status_conn, batch=batch)
duration = time.monotonic() - start
self._metrics.batch_processing_duration_seconds.labels(team_id=team_id, schema_id=schema_id).observe(
@@ -569,7 +625,7 @@ class BatchConsumer:
attempt=attempt,
)
capture_exception(err)
- await self._fail_run(batch, reason=f"max retries exceeded: {err}")
+ await self._fail_run(batch, reason=f"max retries exceeded: {err}", conn=lock_conn)
else:
logger.warning(
self._event("batch_failed_will_retry"),
@@ -600,7 +656,7 @@ class BatchConsumer:
conn: psycopg.AsyncConnection[Any] | None = None,
) -> None:
"""Fail the run via the adapter; the adapter isolates each step so a failure can't crash the consumer."""
- conn = conn or await self._ensure_main_conn()
+ conn = conn or await self._ensure_poll_conn()
try:
await self._adapter.fail_run(conn, batch=batch, reason=reason)
@@ -652,7 +708,7 @@ class BatchConsumer:
Withholding the report makes the health server's timeout fail the liveness
probe, so Kubernetes restarts the pod and the recovery sweep reassigns the
- wedged batch — a sync thread blocked on a dead sink connection cannot be
+ wedged batch -- a sync thread blocked on a dead sink connection cannot be
cancelled from the event loop, so a restart is the only real remedy.
"""
if self._health_reporter is None:
@@ -760,6 +816,8 @@ class BatchConsumer:
loop.add_signal_handler(sig, self._shutdown.set)
async def _close(self) -> None:
+ self._shutdown.set()
+
for task in (self._recovery_task, self._heartbeat_task):
if task is not None:
task.cancel()
@@ -768,20 +826,32 @@ class BatchConsumer:
except asyncio.CancelledError:
pass
+ # Drain in-flight group tasks; each task releases its own lease and closes its connection.
+ if self._in_flight:
+ logger.info(self._event("draining_in_flight_groups"), count=len(self._in_flight))
+ tasks = list(self._in_flight.values())
+ done, pending = await asyncio.wait(tasks, timeout=SHUTDOWN_DRAIN_TIMEOUT_SECONDS)
+ for task in pending:
+ task.cancel()
+ if pending:
+ await asyncio.wait(pending, timeout=5.0)
+ self._metrics.active_groups.dec(len(self._in_flight))
+ self._in_flight.clear()
+
if self._recovery_conn is not None and not self._recovery_conn.closed:
await self._recovery_conn.close()
# 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:
+ if self._poll_conn is not None and not self._poll_conn.closed and not self._poll_conn.broken:
try:
- await self._adapter.release_all_owned(self._conn, owner_token=self._owner_token)
+ await self._adapter.release_all_owned(self._poll_conn, owner_token=self._owner_token)
except Exception as e:
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()
+ if self._poll_conn is not None and not self._poll_conn.closed:
+ await self._poll_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 6fdfdda5e694..077bb6ebd306 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
@@ -80,6 +80,10 @@ class DuckgresBatchConsumerAdapter:
executing_state: str = SourceBatchDuckgresStatus.State.EXECUTING.value
succeeded_state: str = SourceBatchDuckgresStatus.State.SUCCEEDED.value
waiting_retry_state: str = SourceBatchDuckgresStatus.State.WAITING_RETRY.value
+ # Advisory locks are session-scoped: the lock acquired during fetch_and_lock
+ # must be verified/released on the same connection, so groups share the poll
+ # connection. Migrating duckgres to leases is tracked separately.
+ per_group_connections: bool = False
def __init__(self) -> None:
self._team_ids: list[int] | None = None
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 45522d696e66..d3436578169f 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
@@ -49,7 +49,7 @@ def _make_consumer(max_attempts: int = 3, **kwargs) -> DuckgresBatchConsumer:
**kwargs,
)
consumer = DuckgresBatchConsumer(config=config, process_batch=AsyncMock())
- consumer._conn = _make_healthy_conn()
+ consumer._poll_conn = _make_healthy_conn()
consumer._recovery_conn = _make_healthy_conn()
return consumer
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 e5f2b97887a4..21c4a4d15062 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
@@ -54,6 +54,7 @@ class DeltaBatchConsumerAdapter:
executing_state: str = SourceBatchStatus.State.EXECUTING.value
succeeded_state: str = SourceBatchStatus.State.SUCCEEDED.value
waiting_retry_state: str = SourceBatchStatus.State.WAITING_RETRY.value
+ per_group_connections: bool = True
async def fetch_and_lock(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index b302fd110926..fa9ee2e54e73 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
@@ -71,7 +71,7 @@ def _make_consumer(max_attempts: int = 3, **kwargs) -> BatchConsumer:
)
mock_process = AsyncMock()
consumer = BatchConsumer(config=config, process_batch=mock_process)
- consumer._conn = _make_healthy_conn()
+ consumer._poll_conn = _make_healthy_conn()
consumer._recovery_conn = _make_healthy_conn()
return consumer
@@ -177,6 +177,7 @@ class TestProcessGroup:
new_callable=AsyncMock,
return_value=True,
),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), batches)
@@ -205,6 +206,7 @@ class TestProcessGroup:
return_value=True,
),
patch.object(consumer, "_fail_run", new_callable=AsyncMock),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), batches)
@@ -238,6 +240,7 @@ class TestProcessGroup:
new_callable=AsyncMock,
return_value=True,
),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), batches)
@@ -272,6 +275,7 @@ class TestProcessGroup:
new_callable=AsyncMock,
return_value=True,
),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), batches)
@@ -381,7 +385,9 @@ class TestFailRun:
side_effect=Exception("the connection is closed"),
),
):
- await consumer._fail_run(batch, reason="max retries exceeded: the connection is closed")
+ await consumer._fail_run(
+ batch, reason="max retries exceeded: the connection is closed", conn=consumer._poll_conn
+ )
mock_fail_run.assert_called_once() # queue batches still marked failed
@@ -400,7 +406,7 @@ class TestFailRun:
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._update_job_status_to_failed",
) as mock_status,
):
- await consumer._fail_run(batch, reason="boom")
+ await consumer._fail_run(batch, reason="boom", conn=consumer._poll_conn)
mock_status.assert_called_once()
@@ -490,14 +496,14 @@ class TestConnectionRecovery:
ids=["healthy", "closed", "broken"],
)
@pytest.mark.asyncio
- async def test_ensure_main_conn_reconnects_only_when_dead(self, closed, broken, expect_reconnect):
+ async def test_ensure_poll_conn_reconnects_only_when_dead(self, closed, broken, expect_reconnect):
consumer = _make_consumer()
original = _make_healthy_conn(closed=closed, broken=broken)
- consumer._conn = original
+ consumer._poll_conn = original
fresh = _make_healthy_conn()
with patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=fresh) as mock_connect:
- conn = await consumer._ensure_main_conn()
+ conn = await consumer._ensure_poll_conn()
if expect_reconnect:
mock_connect.assert_awaited_once()
@@ -507,10 +513,9 @@ class TestConnectionRecovery:
assert conn is original
@pytest.mark.asyncio
- async def test_concurrent_ensure_main_conn_dials_only_once(self):
- # All concurrent groups hitting a dead conn must share one reconnect, not dial N connections.
+ async def test_concurrent_ensure_poll_conn_dials_only_once(self):
consumer = _make_consumer()
- consumer._conn = _make_healthy_conn(closed=True)
+ consumer._poll_conn = _make_healthy_conn(closed=True)
fresh = _make_healthy_conn()
async def slow_connect() -> AsyncMock:
@@ -518,7 +523,7 @@ class TestConnectionRecovery:
return fresh
with patch.object(consumer, "_connect", side_effect=slow_connect) as mock_connect:
- conns = await asyncio.gather(*[consumer._ensure_main_conn() for _ in range(5)])
+ conns = await asyncio.gather(*[consumer._ensure_poll_conn() for _ in range(5)])
assert mock_connect.call_count == 1
assert all(conn is fresh for conn in conns)
@@ -537,7 +542,6 @@ class TestConnectionRecovery:
@pytest.mark.asyncio
async def test_process_group_does_not_raise_when_unlock_fails(self):
- # An unlock failure must not crash the gather() running every concurrent group.
consumer = _make_consumer()
consumer._process_batch = AsyncMock()
@@ -556,6 +560,7 @@ class TestConnectionRecovery:
new_callable=AsyncMock,
return_value=True,
),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), [_make_batch()])
@@ -574,6 +579,7 @@ class TestConnectionRecovery:
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
new_callable=AsyncMock,
) as mock_unlock,
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), [_make_batch(), _make_batch(batch_index=1)])
@@ -600,6 +606,117 @@ class TestConnectionRecovery:
assert mock_get_stale.call_args[0][0] is fresh
+class TestPerGroupConnectionIsolation:
+ @pytest.mark.asyncio
+ async def test_each_group_gets_distinct_connection(self):
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+ conns_seen: list[Any] = []
+
+ group_conn_a = _make_healthy_conn()
+ group_conn_b = _make_healthy_conn()
+ connect_returns = iter([group_conn_a, group_conn_b])
+
+ async def mock_connect():
+ return next(connect_returns)
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch.object(consumer, "_connect", side_effect=mock_connect),
+ ):
+ batch_a = _make_batch(team_id=1, schema_id="a")
+ batch_b = _make_batch(team_id=1, schema_id="b")
+
+ original_process_single = consumer._process_single
+
+ async def track_conn(batch, lock_conn=None):
+ conns_seen.append(lock_conn)
+ return await original_process_single(batch, lock_conn=lock_conn)
+
+ consumer._process_single = track_conn # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+
+ await consumer._process_group((1, "a"), [batch_a])
+ await consumer._process_group((1, "b"), [batch_b])
+
+ assert conns_seen[0] is group_conn_a
+ assert conns_seen[1] is group_conn_b
+ assert conns_seen[0] is not conns_seen[1]
+
+ @pytest.mark.asyncio
+ async def test_group_connection_not_shared_with_poll(self):
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+ group_conn = _make_healthy_conn()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=group_conn),
+ ):
+ conn_used = None
+ original = consumer._process_single
+
+ async def capture_conn(batch, lock_conn=None):
+ nonlocal conn_used
+ conn_used = lock_conn
+ return await original(batch, lock_conn=lock_conn)
+
+ consumer._process_single = capture_conn # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+ await consumer._process_group((1, "schema-1"), [_make_batch()])
+
+ assert conn_used is group_conn
+ assert conn_used is not consumer._poll_conn
+
+ @pytest.mark.asyncio
+ async def test_group_connection_closed_after_processing(self):
+ consumer = _make_consumer()
+ consumer._process_batch = AsyncMock()
+ group_conn = _make_healthy_conn()
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.verify_advisory_lock",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=group_conn),
+ ):
+ await consumer._process_group((1, "schema-1"), [_make_batch()])
+
+ group_conn.close.assert_awaited_once()
+
+
class TestGroupByKey:
def test_groups_by_team_and_schema(self):
batches = [
@@ -699,7 +816,7 @@ class TestLogContextBinding:
@pytest.mark.asyncio
async def test_process_single_handles_missing_workflow_ids_in_metadata(self):
- """Old batches enqueued before this change have no workflow ids in metadata — must not crash."""
+ """Old batches enqueued before this change have no workflow ids in metadata -- must not crash."""
consumer = _make_consumer()
consumer._process_batch = AsyncMock()
@@ -793,6 +910,7 @@ class TestOwnershipVerification:
new_callable=AsyncMock,
side_effect=[True, True, False],
),
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
):
await consumer._process_group((1, "schema-1"), batches)
@@ -807,7 +925,6 @@ class TestOwnershipVerification:
batch = _make_batch(latest_attempt=0)
dead_conn = _make_healthy_conn(closed=True)
- consumer._conn = dead_conn
with (
patch(
@@ -905,7 +1022,7 @@ class TestShutdown:
async def test_close_releases_owned_leases(self):
consumer = _make_consumer()
main_conn = _make_healthy_conn()
- consumer._conn = main_conn
+ consumer._poll_conn = main_conn
consumer._recovery_conn = _make_healthy_conn()
with patch(
@@ -916,3 +1033,27 @@ class TestShutdown:
mock_release.assert_awaited_once_with(main_conn, owner_token=consumer._owner_token)
main_conn.close.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_close_drains_in_flight_tasks(self):
+ consumer = _make_consumer()
+ consumer._poll_conn = _make_healthy_conn()
+ consumer._recovery_conn = _make_healthy_conn()
+ drained = asyncio.Event()
+
+ async def slow_group():
+ await asyncio.sleep(0.01)
+ drained.set()
+
+ task = asyncio.create_task(slow_group())
+ consumer._in_flight[(1, "schema-1")] = task
+ consumer._metrics.active_groups.inc()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.release_all_owned_leases",
+ new_callable=AsyncMock,
+ ):
+ await consumer._close()
+
+ assert drained.is_set()
+ assert len(consumer._in_flight) == 0