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.

chore(ws): add retry backoff and recovery grace to batch consumer (#59597)

estefania5b6c584fe69d
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 1c06f2d8ac3f..864dd7167f11 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -43,6 +43,7 @@ POLL_INTERVAL_SECONDS = 2.0
RECOVERY_INTERVAL_SECONDS = 30.0
+RETRY_BACKOFF_BASE_SECONDS = 15
@dataclass
@@ -57,6 +58,12 @@ class ConsumerConfig:
health_port: int = 8080
health_timeout_seconds: float = 60.0
recovery_interval_seconds: float = RECOVERY_INTERVAL_SECONDS
+ retry_backoff_base_seconds: int = RETRY_BACKOFF_BASE_SECONDS
+ recovery_grace_seconds: int | None = None
+
+ def __post_init__(self) -> None:
+ if self.recovery_grace_seconds is None:
+ self.recovery_grace_seconds = int(self.recovery_interval_seconds)
class BatchConsumer:
@@ -114,6 +121,7 @@ class BatchConsumer:
batches = await BatchQueue.get_unprocessed_and_lock(
self._conn,
limit=self._config.poll_limit,
+ retry_backoff_base_seconds=self._config.retry_backoff_base_seconds,
)
POLL_DURATION_SECONDS.observe(time.monotonic() - poll_start)
POLL_BATCHES_FETCHED.observe(len(batches))
@@ -167,13 +175,24 @@ class BatchConsumer:
remaining=len(batches) - batches.index(batch),
)
break
- await self._process_single(batch)
+ succeeded = await self._process_single(batch)
+ if not succeeded:
+ # Stop processing sibling batches in this group
+ logger.info(
+ "group_halted_by_non_success",
+ team_id=team_id,
+ schema_id=schema_id,
+ run_uuid=batch.run_uuid,
+ batch_index=batch.batch_index,
+ remaining=len(batches) - batches.index(batch) - 1,
+ )
+ break
finally:
self._semaphore.release()
assert self._conn is not None
await BatchQueue.unlock_for_batches(self._conn, batches=batches)
- async def _process_single(self, batch: PendingBatch) -> None:
+ async def _process_single(self, batch: PendingBatch) -> bool:
"""Increment attempt, check max retries, then process the batch.
Binds per-batch contextvars so every downstream log line (including loader calls)
@@ -224,12 +243,12 @@ class BatchConsumer:
attempt=attempt,
)
try:
- await self._process_single_inner(batch, attempt, team_id, schema_id)
+ return await self._process_single_inner(batch, attempt, team_id, schema_id)
finally:
# Unbind only the keys we set so any ambient context (parent logger, test setup) survives.
structlog.contextvars.unbind_contextvars(*bound_keys)
- async def _process_single_inner(self, batch: PendingBatch, attempt: int, team_id: str, schema_id: str) -> None:
+ async def _process_single_inner(self, batch: PendingBatch, attempt: int, team_id: str, schema_id: str) -> bool:
assert self._conn is not None
# Check before we even try — if already at max, fail the whole run.
@@ -242,7 +261,7 @@ class BatchConsumer:
attempt=attempt,
)
await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")
- return
+ return False
logger.info(
"batch_picked_up",
@@ -284,6 +303,7 @@ class BatchConsumer:
is_final_batch=batch.is_final_batch,
duration_seconds=round(duration, 3),
)
+ return True
except Exception as e:
BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="error").inc()
BATCH_RETRY_TOTAL.labels(attempt=str(attempt), error_type=type(e).__name__).inc()
@@ -312,6 +332,7 @@ class BatchConsumer:
attempt=attempt,
error_response={"error": str(e)[:1000]},
)
+ return False
async def _fail_run(
self,
@@ -356,7 +377,9 @@ class BatchConsumer:
conn = self._recovery_conn or self._conn
assert conn is not None
- stale = await BatchQueue.get_stale_executing(conn)
+ grace_seconds = self._config.recovery_grace_seconds
+ assert grace_seconds is not None
+ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)
if not stale:
RECOVERY_SWEEPS_TOTAL.labels(outcome="clean").inc()
return
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index 654f13a892a3..dac8898baf09 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -173,6 +173,7 @@ class BatchQueue:
conn: psycopg.AsyncConnection[Any],
*,
limit: int = 50,
+ retry_backoff_base_seconds: int = 0,
) -> list[PendingBatch]:
"""Fetch unprocessed batches whose (team_id, schema_id) advisory lock is acquirable.
@@ -181,6 +182,19 @@ class BatchQueue:
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.
+
+ ``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on
+ the age of the latest status row: a batch is only eligible when
+ ``now() - s.created_at >= retry_backoff_base_seconds * GREATEST(s.attempt, 1)``
+ (attempt is floored at 1 so that a zero-attempt row still waits at least one
+ base period).
+
+ Head-of-line gating per run: a batch is excluded if any earlier
+ ``batch_index`` in the same ``run_uuid`` is currently ``executing`` or
+ in ``waiting_retry`` whose backoff window has not yet elapsed. Earlier
+ batches that are unprocessed (NULL status) or ``waiting_retry`` with
+ backoff met are treated as siblings that will be returned alongside
+ in the same poll and processed sequentially by the consumer.
"""
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
@@ -198,7 +212,32 @@ class BatchQueue:
LEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_id
WHERE
b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
- AND (s.batch_id IS NULL OR s.job_state = 'waiting_retry')
+ AND (
+ s.batch_id IS NULL
+ OR (
+ s.job_state = 'waiting_retry'
+ AND s.created_at <= now() - make_interval(
+ secs => %(backoff)s * GREATEST(COALESCE(s.attempt, 1), 1)
+ )
+ )
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM {BATCH_TABLE} b_prev
+ LEFT JOIN {STATUS_VIEW} s_prev ON b_prev.id = s_prev.batch_id
+ WHERE b_prev.run_uuid = b.run_uuid
+ AND b_prev.batch_index < b.batch_index
+ AND b_prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND (
+ s_prev.job_state = 'executing'
+ OR (
+ s_prev.job_state = 'waiting_retry'
+ AND s_prev.created_at > now() - make_interval(
+ secs => %(backoff)s * GREATEST(COALESCE(s_prev.attempt, 1), 1)
+ )
+ )
+ )
+ )
AND b.run_uuid NOT IN (
SELECT DISTINCT b2.run_uuid
FROM {BATCH_TABLE} b2
@@ -214,7 +253,7 @@ class BatchQueue:
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
""",
- {"limit": limit},
+ {"limit": limit, "backoff": retry_backoff_base_seconds},
)
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
@@ -245,11 +284,16 @@ class BatchQueue:
@staticmethod
async def get_stale_executing(
conn: psycopg.AsyncConnection[Any],
+ *,
+ grace_seconds: int = 0,
) -> list[PendingBatch]:
"""Find batches stuck in 'executing' whose advisory lock is not held (previous pod crashed).
Uses a MATERIALIZED CTE for the same reason as get_unprocessed_and_lock:
candidate rows are fully resolved before any advisory lock is probed.
+
+ ``grace_seconds`` requires the 'executing' status row to be older than
+ this threshold before the batch is considered orphaned.
"""
async with conn.cursor(row_factory=dict_row) as cur:
await cur.execute(
@@ -268,6 +312,7 @@ class BatchQueue:
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.*
@@ -275,6 +320,7 @@ class BatchQueue:
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
""",
+ {"grace": grace_seconds},
)
rows = await cur.fetchall()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index d8159a801aac..2e4b40ff310b 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -171,6 +171,35 @@ class TestProcessGroup:
mock_unlock.assert_called_once()
+ @pytest.mark.asyncio
+ async def test_halts_group_when_batch_does_not_succeed(self):
+ consumer = _make_consumer(max_attempts=3)
+ processed: list[int] = []
+
+ async def fail_on_one(batch):
+ processed.append(batch.batch_index)
+ if batch.batch_index == 1:
+ raise RuntimeError("boom")
+
+ consumer._process_batch = fail_on_one
+
+ batches = [_make_batch(batch_index=i, id=f"00000000-0000-0000-0000-{i + 1:012d}") for i in range(3)]
+
+ with (
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.update_status",
+ new_callable=AsyncMock,
+ ),
+ patch(
+ "posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.BatchQueue.unlock_for_batches",
+ new_callable=AsyncMock,
+ ),
+ ):
+ await consumer._process_group((1, "schema-1"), batches)
+
+ # batch 2 must not be processed once batch 1 enters waiting_retry
+ assert processed == [0, 1]
+
@pytest.mark.asyncio
async def test_stops_on_shutdown(self):
consumer = _make_consumer()
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
index 63270c4f2bb7..8676ef3dc892 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_jobs_db.py
@@ -278,7 +278,7 @@ class TestBatchQueueStaleExecuting:
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)
+ 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
@@ -290,11 +290,85 @@ class TestBatchQueueStaleExecuting:
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)
+ stale = await BatchQueue.get_stale_executing(conn_b, grace_seconds=0)
assert len(stale) == 0
await conn.execute("SELECT pg_advisory_unlock_all()")
+ @pytest.mark.asyncio
+ async def test_grace_shields_recent_executing_from_orphan_sweep(self, conn, _db_url):
+ bid = await _insert_batch(conn)
+
+ 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.
+
+ # 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) == []
+
+ @pytest.mark.asyncio
+ async def test_grace_lets_aged_executing_through(self, conn, _db_url):
+ bid = await _insert_batch(conn)
+
+ 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],
+ )
+
+ stale = await BatchQueue.get_stale_executing(conn, grace_seconds=60)
+ assert len(stale) == 1
+ assert str(stale[0].id) == bid
+
+
[email protected]_db(transaction=True)
+class TestBatchQueueRetryBackoff:
+ @pytest.mark.asyncio
+ async def test_backoff_gates_fresh_waiting_retry(self, conn):
+ bid = await _insert_batch(conn)
+ 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) == []
+
+ # With backoff disabled, it's eligible immediately.
+ batches = await BatchQueue.get_unprocessed_and_lock(conn, retry_backoff_base_seconds=0)
+ assert len(batches) == 1
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
+ @pytest.mark.asyncio
+ async def test_backoff_scales_with_attempt(self, conn):
+ bid = await _insert_batch(conn)
+ # Backdate the status row by 10 seconds with attempt=3.
+ await conn.execute(
+ f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, created_at) "
+ f"VALUES (%s, 'waiting_retry', 3, now() - interval '10 seconds')",
+ [bid],
+ )
+
+ # base=5, attempt=3 -> 15s required, only 10s elapsed: blocked.
+ assert await BatchQueue.get_unprocessed_and_lock(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)
+ assert len(batches) == 1
+ await BatchQueue.unlock_for_batches(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)
+ assert len(batches) == 1
+ await BatchQueue.unlock_for_batches(conn, batches=batches)
+
class TestPendingBatchToExportSignal:
def test_maps_all_fields(self):
diff --git a/products/warehouse_sources_queue/backend/migrations/0002_sourcebatch_run_uuid_batch_index_idx.py b/products/warehouse_sources_queue/backend/migrations/0002_sourcebatch_run_uuid_batch_index_idx.py
new file mode 100644
index 000000000000..72683464451d
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0002_sourcebatch_run_uuid_batch_index_idx.py
@@ -0,0 +1,54 @@
+from django.db import migrations, models
+
+# Guarded with to_regclass so the migration no-ops on DBs without the sourcebatch table.
+_CREATE_INDEX_SQL = """
+DO $$
+BEGIN
+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN
+ CREATE INDEX IF NOT EXISTS sb_run_uuid_bi_idx
+ ON sourcebatch (run_uuid, batch_index);
+ END IF;
+END
+$$;
+"""
+
+_DROP_INDEX_SQL = """
+DO $$
+BEGIN
+ IF to_regclass('public.sourcebatch') IS NOT NULL THEN
+ DROP INDEX IF EXISTS sb_run_uuid_bi_idx;
+ END IF;
+END
+$$;
+"""
+
+
+def _create_index(apps, schema_editor):
+ schema_editor.execute(_CREATE_INDEX_SQL)
+
+
+def _drop_index(apps, schema_editor):
+ schema_editor.execute(_DROP_INDEX_SQL)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources_queue", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="sourcebatch",
+ index=models.Index(
+ fields=["run_uuid", "batch_index"],
+ name="sb_run_uuid_bi_idx",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.RunPython(_create_index, _drop_index),
+ ],
+ ),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
index cbab66dde92a..8d5811080b8a 100644
--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0002_sourcebatch_run_uuid_batch_index_idx
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
index cd5ea0eb6b0d..442b322fa182 100644
--- a/products/warehouse_sources_queue/backend/models.py
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -45,6 +45,7 @@ class SourceBatch(UUIDModel):
indexes = [
models.Index(fields=["team_id", "schema_id"], name="sb_team_schema_idx"),
models.Index(fields=["run_uuid"], name="sb_run_uuid_idx"),
+ models.Index(fields=["run_uuid", "batch_index"], name="sb_run_uuid_bi_idx"),
]