:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): split failing backfills out of the duckgres blocked backlog (#68785)
Eric Duongd4891c22e55e
diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex 7ab4a3a2df5a..32ff155605fe 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -152,6 +152,13 @@ class DuckgresSinkSchemaState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):chunk_count = models.IntegerField(null=True, blank=True)chunks_applied = models.IntegerField(default=0)last_error = models.TextField(null=True, blank=True)+ # Failure streak since the last forward progress. Drives planner retry+ # backoff and the failing-schema classification that splits these schemas'+ # backlog out of the pageable blocked gauges. Reset on any progress.+ consecutive_failures = models.IntegerField(default=0)+ # When the current failure streak began — the durable "backfill owed since"+ # anchor. Unlike batch-derived gauges it survives queue retention.+ first_failed_at = models.DateTimeField(null=True, blank=True)# Override CreatedMetaFields.created_by to drop the DB-level FK: a real# constraint on posthog_user takes a lock on that hot table when this table# is created (HotTableAlterPolicy). App-level enforcement is enough for andiff --git a/posthog/migrations/1249_duckgressinkschemastate_consecutive_failures_and_more.py b/posthog/migrations/1249_duckgressinkschemastate_consecutive_failures_and_more.pynew file mode 100644index 000000000000..6273b3b37907--- /dev/null+++ b/posthog/migrations/1249_duckgressinkschemastate_consecutive_failures_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-07-06 21:24++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1248_personal_api_key_description"),+ ]++ operations = [+ migrations.AddField(+ model_name="duckgressinkschemastate",+ name="consecutive_failures",+ field=models.IntegerField(default=0),+ ),+ migrations.AddField(+ model_name="duckgressinkschemastate",+ name="first_failed_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 63da0a9c4fda..062a454be4c4 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1248_personal_api_key_description+1249_duckgressinkschemastate_consecutive_failures_and_morediff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.pyindex ccff7267ad30..2f33204fb1dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py@@ -37,12 +37,14 @@ metadata at the pinned snapshot version (see backfill_queue.preapply_covered_batfrom __future__ import annotations+import randomfrom datetime import timedeltafrom typing import Anyfrom django.conf import settingsfrom django.db import close_old_connections-from django.db.models import Count+from django.db.models import Count, F, Min, Q, Value+from django.db.models.functions import Coalesce, Greatestfrom django.utils import timezoneimport psycopg@@ -90,18 +92,43 @@ MAX_CONCURRENT_BACKFILLS_GLOBAL = 5# metadata-only (Delta log read + row inserts), so minutes of lease are ample.PLANNING_LEASE_SECONDS = 900+# A schema with this many consecutive failed backfill attempts (and not primed)+# is classified "failing": its blocked backlog moves off the pageable gauges+# into the failing bucket, and the planner retries it with backoff instead of+# every tick. 3 rides out a single transient blip without flapping the buckets.+FAILING_THRESHOLD = 3+# Planner retry backoff for failing schemas: BASE * 2**(failures-1), capped.+# Never gives up — at the cap the schema retries every ~30min forever, so it+# self-heals the moment the underlying issue clears.+RETRY_BACKOFF_BASE_SECONDS = 30+RETRY_BACKOFF_CAP_SECONDS = 30 * 60+BACKFILL_SCHEMAS_GAUGE = Gauge("duckgres_backfill_schemas","Duckgres sink schemas per backfill lifecycle state",labelnames=["state"],multiprocess_mode="livemax",)+# Visibility-only (dashboards / future UI). Deliberately unalerted: a stuck+# backfill is an operator-remediation queue, not a page — the pageable signal+# is the healthy blocked backlog in the consumer's gauges.+STUCK_BACKFILL_GAUGE = Gauge(+ "duckgres_sink_stuck_backfill",+ "Schemas whose backfill is persistently failing (failure streak at threshold, or parked in needs_resync)",+ multiprocess_mode="livemax",+)+STUCK_BACKFILL_OLDEST_AGE_GAUGE = Gauge(+ "duckgres_sink_stuck_oldest_age_seconds",+ "Age of the oldest failing schema's failure streak (first_failed_at) — survives queue retention",+ multiprocess_mode="livemax",+)__all__ = ["BACKFILL_JOB_ID","BackfillUnsupportedError","backfill_run_uuid","blocked_schema_ids",+ "failing_schema_ids","mark_primed","replan_backfill","run_backfill_planner",@@ -149,6 +176,30 @@ def blocked_schema_ids(team_ids: list[int] | None) -> list[str]:return [str(sid) for sid in schemas.values_list("id", flat=True) if str(sid) not in primed_ids]+def _failing_q() -> Q:+ """Hard-blocked classification: the failure streak reached threshold, or the+ schema is parked in NEEDS_RESYNC (unbackfillable / awaiting a replace run) —+ either way its backlog will not drain without intervention or healing."""+ return Q(consecutive_failures__gte=FAILING_THRESHOLD) | Q(state=DuckgresSinkSchemaState.State.NEEDS_RESYNC)+++def failing_schema_ids(team_ids: list[int] | None) -> list[str]:+ """Schemas whose blocked backlog is hard-blocked, not merely in-progress.++ A subset of blocked_schema_ids: the consumer subtracts these batches from+ the pageable blocked gauges so a wedged schema cannot mask (or trigger) a+ genuine-throughput page, and reports them in the failing bucket instead.+ """+ close_old_connections()+ if team_ids is not None and not team_ids:+ return []++ qs = DuckgresSinkSchemaState.objects.exclude(state=DuckgresSinkSchemaState.State.PRIMED).filter(_failing_q())+ if team_ids is not None:+ qs = qs.filter(team_id__in=team_ids)+ return [str(sid) for sid in qs.values_list("schema_id", flat=True)]++def sink_eligible_schema_ids(team_ids: list[int]) -> list[str]:"""Schema ids whose (team, source_type) is on warehouse-pipelines-v3.@@ -204,7 +255,9 @@ def mark_primed(schema_id: str, *, chunks_applied: int | None = None) -> None:"""updates: dict[str, Any] = {"state": DuckgresSinkSchemaState.State.PRIMED,+ "last_error": None,"updated_at": timezone.now(),+ **_STREAK_RESET_UPDATES,}if chunks_applied is not None:updates["chunks_applied"] = chunks_applied@@ -242,6 +295,9 @@ def replan_backfill(schema_id: str) -> None:chunks_applied=0,last_error=None,updated_at=timezone.now(),+ # Operator fresh start: the streak (and its backoff) must not outlive+ # the run it was recorded against.+ **_STREAK_RESET_UPDATES,)@@ -325,6 +381,26 @@ def _bootstrap_state_rows(team_ids: list[int] | None) -> None:logger.info("duckgres_backfill_bootstrapped", created=created)+def _failure_streak_updates(*, now: Any) -> dict[str, Any]:+ """Update-dict fragment recording one failed attempt: bump the streak and+ stamp first_failed_at once per streak. Merged into the site's own CAS so a+ failure is never recorded over a state another pod already advanced."""+ return {+ "consecutive_failures": F("consecutive_failures") + 1,+ "first_failed_at": Coalesce(F("first_failed_at"), Value(now)),+ }+++_STREAK_RESET_UPDATES: dict[str, Any] = {"consecutive_failures": 0, "first_failed_at": None}+++def _retry_backoff_seconds(failures: int) -> float:+ if failures <= 0:+ return 0.0+ base = min(RETRY_BACKOFF_BASE_SECONDS * 2 ** (failures - 1), RETRY_BACKOFF_CAP_SECONDS)+ return base * random.uniform(0.8, 1.2)++def _plan_pending(team_ids: list[int] | None) -> None:pending = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.PENDING_BACKFILL)if team_ids is not None:@@ -339,6 +415,20 @@ def _plan_pending(team_ids: list[int] | None) -> None:if _global_at_capacity():break+ # Failing schemas retry with backoff instead of hammering a broken+ # Delta table every tick. updated_at is the last-attempt anchor (each+ # recorded failure bumps it). Never gives up: at the cap this is one+ # attempt per ~30min forever, so it self-heals when the table recovers.+ # auto_now makes updated_at nullable to the type checker only; a missing+ # anchor means no backoff to honour, so attempt rather than skip forever.+ last_attempt_at = state.updated_at+ if (+ state.consecutive_failures > 0+ and last_attempt_at is not None+ and timezone.now() < last_attempt_at + timedelta(seconds=_retry_backoff_seconds(state.consecutive_failures))+ ):+ continue+org_id = state.team.organization_idif _org_at_capacity(org_id):continue@@ -361,16 +451,18 @@ def _plan_pending(team_ids: list[int] | None) -> None:try:_plan_one(state)except BackfillUnsupportedError as e:+ now = timezone.now()DuckgresSinkSchemaState.objects.filter(id=state.id).update(state=DuckgresSinkSchemaState.State.NEEDS_RESYNC,last_error=str(e)[:2000],- updated_at=timezone.now(),+ updated_at=now,+ **_failure_streak_updates(now=now),)logger.warning("duckgres_backfill_unsupported", schema_id=str(state.schema_id), error=str(e))except Exception as e:logger.exception("duckgres_backfill_plan_failed", schema_id=str(state.schema_id))capture_exception(e)- _revert_to_pending(state.id, error=str(e)[:2000])+ _revert_to_pending(state.id, error=str(e)[:2000], record_failure=True)def _org_at_capacity(org_id: Any, *, exclude_id: Any = None) -> bool:@@ -394,13 +486,19 @@ def _global_at_capacity(*, exclude_id: Any = None) -> bool:return qs.count() >= MAX_CONCURRENT_BACKFILLS_GLOBAL-def _revert_to_pending(state_id: Any, error: str | None = None) -> None:+def _revert_to_pending(state_id: Any, error: str | None = None, *, record_failure: bool = False) -> None:+ """record_failure distinguishes a failed attempt from a neutral revert+ (capacity re-check lost the race) — capacity is pacing, not failure, and+ must not start a streak."""+ now = timezone.now()updates: dict[str, Any] = {"state": DuckgresSinkSchemaState.State.PENDING_BACKFILL,- "updated_at": timezone.now(),+ "updated_at": now,}if error is not None:updates["last_error"] = error+ if record_failure:+ updates.update(_failure_streak_updates(now=now))DuckgresSinkSchemaState.objects.filter(id=state_id, state=DuckgresSinkSchemaState.State.BACKFILLING, backfill_run_uuid__isnull=True).update(**updates)@@ -443,7 +541,10 @@ def _plan_one(state: DuckgresSinkSchemaState) -> None:if not chunks:# Empty Delta table: nothing to prime.DuckgresSinkSchemaState.objects.filter(id=state.id).update(- state=DuckgresSinkSchemaState.State.PRIMED, updated_at=timezone.now()+ state=DuckgresSinkSchemaState.State.PRIMED,+ last_error=None,+ updated_at=timezone.now(),+ **_STREAK_RESET_UPDATES,)return@@ -462,6 +563,7 @@ def _plan_one(state: DuckgresSinkSchemaState) -> None:chunks_applied=0,last_error=None,updated_at=timezone.now(),+ **_STREAK_RESET_UPDATES,)if not planned:return@@ -594,7 +696,9 @@ def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaStateDuckgresSinkSchemaState.objects.filter(id=state.id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(state=DuckgresSinkSchemaState.State.PRIMED,chunks_applied=applied,+ last_error=None,updated_at=timezone.now(),+ **_STREAK_RESET_UPDATES,)return@@ -628,9 +732,23 @@ def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaStateschema_id=str(state.schema_id),run_uuid=run_uuid,)- elif state.last_error != reason:+ elif (+ state.last_error != reason+ or state.consecutive_failures < FAILING_THRESHOLD+ or state.first_failed_at is None+ ):+ # Mid-backfill wedge: a duckgres 'failed' status is terminal, so this+ # run will never progress on its own — classify the schema failing+ # immediately (jump the streak to threshold rather than drip one per+ # tick), else its backlog sits in the pageable healthy bucket forever.+ # The condition gates re-writes so a steady wedge stops churning the row.+ now = timezone.now()DuckgresSinkSchemaState.objects.filter(id=state.id).update(- last_error=reason[:2000], chunks_applied=applied, updated_at=timezone.now()+ last_error=reason[:2000],+ chunks_applied=applied,+ consecutive_failures=Greatest(F("consecutive_failures"), Value(FAILING_THRESHOLD)),+ first_failed_at=Coalesce(F("first_failed_at"), Value(now)),+ updated_at=now,)return@@ -665,7 +783,11 @@ def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaState)if applied != state.chunks_applied:- DuckgresSinkSchemaState.objects.filter(id=state.id).update(chunks_applied=applied, updated_at=timezone.now())+ updates: dict[str, Any] = {"chunks_applied": applied, "updated_at": timezone.now()}+ if applied > state.chunks_applied:+ # Chunks are landing again — forward progress ends the failure streak.+ updates.update(_STREAK_RESET_UPDATES)+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(**updates)def _reconcile_needs_resync(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaState) -> None:@@ -708,7 +830,12 @@ def _reconcile_needs_resync(conn: psycopg.Connection[Any], state: DuckgresSinkScflipped = DuckgresSinkSchemaState.objects.filter(id=state.id, state=DuckgresSinkSchemaState.State.NEEDS_RESYNC- ).update(state=DuckgresSinkSchemaState.State.PRIMED, last_error=None, updated_at=timezone.now())+ ).update(+ state=DuckgresSinkSchemaState.State.PRIMED,+ last_error=None,+ updated_at=timezone.now(),+ **_STREAK_RESET_UPDATES,+ )if flipped:logger.info("duckgres_backfill_resync_completed", schema_id=str(state.schema_id))@@ -717,3 +844,11 @@ def _emit_state_gauge() -> None:counts = dict(DuckgresSinkSchemaState.objects.values_list("state").annotate(n=Count("id")))for state_value, _label in DuckgresSinkSchemaState.State.choices:BACKFILL_SCHEMAS_GAUGE.labels(state=state_value).set(counts.get(state_value, 0))++ # Derived from the state table, not batches, so a stuck schema stays visible+ # past queue retention — the durable "backfill owed since" high-watermark.+ failing = DuckgresSinkSchemaState.objects.exclude(state=DuckgresSinkSchemaState.State.PRIMED).filter(_failing_q())+ stats = failing.aggregate(n=Count("id"), oldest=Min("first_failed_at"))+ STUCK_BACKFILL_GAUGE.set(stats["n"] or 0)+ oldest = stats["oldest"]+ STUCK_BACKFILL_OLDEST_AGE_GAUGE.set((timezone.now() - oldest).total_seconds() if oldest else 0.0)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.pyindex ec7ce79cfb85..22fdc6ec3e29 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@@ -24,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (blocked_schema_ids as compute_blocked_schema_ids,+ failing_schema_ids as compute_failing_schema_ids,run_backfill_planner,sink_eligible_schema_ids as compute_eligible_schema_ids,)@@ -64,12 +65,20 @@ SINK_OLDEST_ELIGIBLE_AGE_SECONDS = Gauge()SINK_BLOCKED_BACKLOG = Gauge("duckgres_sink_blocked_backlog",- "Delta-succeeded batches held back because their schema is not yet primed (backfill pending/in-flight)",+ "Delta-succeeded batches held back behind a healthily progressing backfill (pending/in-flight). "+ "Excludes failing schemas, so this is the pageable signal: sustained growth is a real throughput problem.",multiprocess_mode="livemax",)SINK_BLOCKED_OLDEST_AGE_SECONDS = Gauge("duckgres_sink_blocked_oldest_age_seconds",- "Age of the oldest blocked batch — approaching queue retention means the post-backfill handoff will gap",+ "Age of the oldest healthily blocked batch — approaching queue retention means the post-backfill handoff will gap",+ multiprocess_mode="livemax",+)+# Visibility-only, deliberately unalerted: hard-blocked schemas are an operator+# remediation queue (durably tracked on DuckgresSinkSchemaState), not a page.+SINK_FAILING_BLOCKED_BACKLOG = Gauge(+ "duckgres_sink_failing_blocked_backlog",+ "Delta-succeeded batches held back behind a hard-blocked schema (backfill failure streak / needs_resync)",multiprocess_mode="livemax",)SINK_SUPERSEDED_BATCHES_TOTAL = Gauge(@@ -98,6 +107,10 @@ class DuckgresBatchConsumerAdapter:# None = not yet computed; the fetch claims nothing until the first# successful planner pass so unprimed schemas can't sneak live batches in.self._blocked_schema_ids: list[str] | None = None+ # Subset of the blocked set whose backfill is hard-blocked (failure+ # streak / needs_resync); their batches report on the unalerted failing+ # gauge instead of the pageable blocked gauges.+ self._failing_schema_ids: list[str] | None = None# Allow-list of v3-enabled schema ids (prod only). None = not yet computed# (fetch claims nothing) in prod; stays None in dev where team_ids is None# and the sink is intentionally ungated.@@ -141,23 +154,24 @@ class DuckgresBatchConsumerAdapter:# Eligibility-CTE queries scan the queue DB over the partition-pruning# window per enabled team; they are statement-timeout bounded (see# jobs_db). A timeout or transient queue-DB error must not wedge or- # crash the poll loop — skip this tick and retry on the next one- # rather than stacking long-running scans on the shared queue DB.+ # crash the poll loop — skip this tick and retry on the next one.superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn, team_ids=team_ids)SINK_SUPERSEDED_BATCHES_TOTAL.set(superseded)if superseded:logger.info("duckgres_superseded_obsolete_batches", count=superseded)- backlog, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ backlog, oldest_age, blocked, blocked_age, failing_blocked = await DuckgresBatchQueue.get_backlog_stats(conn,team_ids=team_ids,blocked_schema_ids=self._blocked_schema_ids,eligible_schema_ids=self._eligible_schema_ids,+ failing_schema_ids=self._failing_schema_ids,)SINK_ELIGIBLE_BACKLOG.set(backlog)SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)SINK_BLOCKED_BACKLOG.set(blocked)SINK_BLOCKED_OLDEST_AGE_SECONDS.set(blocked_age or 0.0)+ SINK_FAILING_BLOCKED_BACKLOG.set(failing_blocked)except Exception as e:logger.exception("duckgres_sink_maintenance_query_failed")capture_exception(e)@@ -169,6 +183,7 @@ class DuckgresBatchConsumerAdapter:# refresh the live-batch block list it derives from.await sync_to_async(run_backfill_planner, thread_sensitive=False)(team_ids)self._blocked_schema_ids = await sync_to_async(compute_blocked_schema_ids, thread_sensitive=False)(team_ids)+ self._failing_schema_ids = await sync_to_async(compute_failing_schema_ids, thread_sensitive=False)(team_ids)# v3 allow-list: prod only. In dev (team_ids None) the sink stays# ungated, matching the team filter. Kept in the planner try so a# transient app-DB/flag blip leaves the previous allow-list intact.@@ -196,7 +211,9 @@ class DuckgresBatchConsumerAdapter:team_count=None if team_ids is None else len(team_ids),eligible_backlog=backlog,blocked_backlog=blocked,+ failing_blocked_backlog=failing_blocked,blocked_schema_count=None if self._blocked_schema_ids is None else len(self._blocked_schema_ids),+ failing_schema_count=None if self._failing_schema_ids is None else len(self._failing_schema_ids),eligible_schema_count=None if self._eligible_schema_ids is None else len(self._eligible_schema_ids),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pyindex ce9f1a1c6719..48721653c6cb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -507,14 +507,20 @@ class DuckgresBatchQueue:team_ids: list[int] | None = None,blocked_schema_ids: list[str] | None = None,eligible_schema_ids: list[str] | None = None,- ) -> tuple[int, float | None, int, float | None]:- """(eligible_count, eligible_oldest_age, blocked_count, blocked_oldest_age).+ failing_schema_ids: list[str] | None = None,+ ) -> tuple[int, float | None, int, float | None, int]:+ """(eligible_count, eligible_oldest_age, blocked_count, blocked_oldest_age, failing_blocked_count).Eligible = delta-succeeded, unapplied, non-failed data batches the sinkcan claim now — the lag/alert signal (7-day retention and permanent runfailure are time-bounded loss modes). Blocked = the same but held back- by an unprimed schema; reported separately so weeks of backfill cannot- pin the alert gauge while still being visible.+ by an unprimed schema whose backfill is progressing normally; this is+ the pageable bucket — it drains on its own, so sustained growth means a+ real throughput problem. Failing-blocked = blocked batches behind a+ hard-blocked schema (failure streak at threshold / needs_resync);+ counted separately so one wedged schema can neither trigger nor mask+ the page. Durable per-schema failure tracking lives on+ DuckgresSinkSchemaState (this count ages out with queue retention)."""async with _statement_timeout(conn, ELIGIBILITY_QUERY_STATEMENT_TIMEOUT_MS), conn.cursor() as cur:await cur.execute(@@ -523,7 +529,11 @@ class DuckgresBatchQueue:backlog AS (SELECTb.created_at,- {BLOCKED_LIVE_BATCH_CONDITION} AS is_blocked+ {BLOCKED_LIVE_BATCH_CONDITION} AS is_blocked,+ (+ %(failing_schema_ids)s::varchar[] IS NOT NULL+ AND b.schema_id = ANY(%(failing_schema_ids)s)+ ) AS is_failingFROM {BATCH_TABLE} bJOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON trueLEFT JOIN {DUCKGRES_APPLY_TABLE} a@@ -542,14 +552,16 @@ class DuckgresBatchQueue:SELECTcount(*) FILTER (WHERE NOT is_blocked),EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE NOT is_blocked)),- count(*) FILTER (WHERE is_blocked),- EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE is_blocked))+ count(*) FILTER (WHERE is_blocked AND NOT is_failing),+ EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE is_blocked AND NOT is_failing)),+ count(*) FILTER (WHERE is_blocked AND is_failing)FROM backlog""",{"team_ids": team_ids,"blocked_schema_ids": blocked_schema_ids,"eligible_schema_ids": eligible_schema_ids,+ "failing_schema_ids": failing_schema_ids,},)row = await cur.fetchone()@@ -558,8 +570,8 @@ class DuckgresBatchQueue:return float(v) if v is not None else Noneif row is None:- return 0, None, 0, None- return int(row[0]), _age(row[1]), int(row[2]), _age(row[3])+ return 0, None, 0, None, 0+ return int(row[0]), _age(row[1]), int(row[2]), _age(row[3]), int(row[4])@staticmethodasync def update_status(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.pyindex 29f61d2cc2c2..7ece400d4ca3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py@@ -1,7 +1,13 @@import uuid+from datetime import timedelta+from types import SimpleNamespace+from typing import Any, castimport pytest-from unittest.mock import MagicMock, patch+from freezegun import freeze_time+from unittest.mock import MagicMock, Mock, patch++from django.utils import timezoneimport psycopg@@ -19,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (backfill_run_uuid,+ enqueue_chunks,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (CHUNK_TARGET_BYTES,@@ -26,6 +33,9 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_committed_batch_keys,_group_files_into_chunks,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (+ RETIRE_KIND_SUPERSEDED_BY_REPLACE,+)from products.warehouse_sources.backend.temporal.data_imports.workflow_activities import create_job_model_State = DuckgresSinkSchemaState.State@@ -229,6 +239,239 @@ class TestBootstrapV3SourceGate:assert non_v3_schema.id not in primed+# Stands in for the queue-DB connection in _reconcile_one: the SQL results are+# the boundary; the assertions are on the Django state writes.+class _FakeQueueConn:+ def __init__(self, results: list) -> None:+ self._results = list(results)++ def execute(self, *args, **kwargs):+ row = self._results.pop(0)+ return SimpleNamespace(fetchone=lambda: row)+++def _fake_conn(results: list) -> psycopg.Connection[Any]:+ return cast("psycopg.Connection[Any]", _FakeQueueConn(results))+++class TestFailureStreak:+ def _team(self) -> Team:+ return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")++ def _backdate(self, state: DuckgresSinkSchemaState, seconds: int) -> None:+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(+ updated_at=timezone.now() - timedelta(seconds=seconds)+ )++ def test_plan_failure_records_streak_and_first_failed_at_once(self, monkeypatch):+ monkeypatch.setattr(backfill_module, "_plan_one", Mock(side_effect=RuntimeError("no files in log segment")))+ candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)++ _plan_pending(team_ids=[candidate.team_id])+ candidate.refresh_from_db()+ assert candidate.state == _State.PENDING_BACKFILL+ assert candidate.consecutive_failures == 1+ assert candidate.first_failed_at is not None+ assert "no files in log segment" in (candidate.last_error or "")+ streak_started_at = candidate.first_failed_at++ # Second failed attempt: the streak grows but the high-watermark anchor+ # must not move — it is the durable "backfill owed since" timestamp.+ self._backdate(candidate, seconds=3600) # clear the retry backoff window+ _plan_pending(team_ids=[candidate.team_id])+ candidate.refresh_from_db()+ assert candidate.consecutive_failures == 2+ assert candidate.first_failed_at == streak_started_at++ def test_unsupported_table_parks_needs_resync_with_streak(self, monkeypatch):+ monkeypatch.setattr(+ backfill_module, "_plan_one", Mock(side_effect=backfill_module.BackfillUnsupportedError("deletion vectors"))+ )+ candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)++ _plan_pending(team_ids=[candidate.team_id])++ candidate.refresh_from_db()+ assert candidate.state == _State.NEEDS_RESYNC+ assert candidate.consecutive_failures == 1+ assert candidate.first_failed_at is not None++ def test_capacity_revert_does_not_start_a_streak(self, monkeypatch):+ # Pre-check passes, post-claim re-check trips: the revert is pacing, not+ # failure — recording it would misclassify busy-but-healthy orgs.+ monkeypatch.setattr(backfill_module, "_org_at_capacity", Mock(side_effect=[False, True]))+ monkeypatch.setattr(backfill_module, "_plan_one", Mock(side_effect=AssertionError("must not plan")))+ candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)++ _plan_pending(team_ids=[candidate.team_id])++ candidate.refresh_from_db()+ assert candidate.state == _State.PENDING_BACKFILL+ assert candidate.consecutive_failures == 0+ assert candidate.first_failed_at is None++ @freeze_time("2026-01-15T12:00:00Z")+ def test_backoff_skips_recent_failure_then_retries_after_window(self, monkeypatch):+ plan_one = Mock(side_effect=RuntimeError("still broken"))+ monkeypatch.setattr(backfill_module, "_plan_one", plan_one)+ candidate = _sink_state(self._team(), _State.PENDING_BACKFILL)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(+ consecutive_failures=10, first_failed_at=timezone.now()+ )++ # Streak at cap, updated_at fresh: inside the backoff window, no attempt.+ _plan_pending(team_ids=[candidate.team_id])+ plan_one.assert_not_called()++ # Past the max window (cap * max jitter): retried — backoff delays, never gives up.+ self._backdate(candidate, seconds=int(backfill_module.RETRY_BACKOFF_CAP_SECONDS * 1.2) + 1)+ _plan_pending(team_ids=[candidate.team_id])+ plan_one.assert_called_once()++ @freeze_time("2026-01-15T12:00:00Z")+ def test_mark_primed_resets_streak(self):+ candidate = _sink_state(self._team(), _State.BACKFILLING)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(+ consecutive_failures=5, first_failed_at=timezone.now(), last_error="boom"+ )++ backfill_module.mark_primed(str(candidate.schema_id))++ candidate.refresh_from_db()+ assert candidate.state == _State.PRIMED+ assert candidate.consecutive_failures == 0+ assert candidate.first_failed_at is None+ assert candidate.last_error is None++ @freeze_time("2026-01-15T12:00:00Z")+ def test_replan_backfill_resets_streak(self):+ candidate = _sink_state(self._team(), _State.NEEDS_RESYNC)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(+ consecutive_failures=5, first_failed_at=timezone.now(), last_error="boom"+ )++ backfill_module.replan_backfill(str(candidate.schema_id))++ candidate.refresh_from_db()+ assert candidate.state == _State.PENDING_BACKFILL+ assert candidate.consecutive_failures == 0+ assert candidate.first_failed_at is None++ @freeze_time("2026-01-15T12:00:00Z")+ def test_stuck_gauges_derive_from_state_without_any_batches(self):+ # The whole point of the state-derived gauges: a wedged schema stays+ # visible with zero rows in the (retention-bounded) batch queue.+ team = self._team()+ stuck = _sink_state(team, _State.PENDING_BACKFILL)+ DuckgresSinkSchemaState.objects.filter(id=stuck.id).update(+ consecutive_failures=backfill_module.FAILING_THRESHOLD,+ first_failed_at=timezone.now() - timedelta(days=20),+ )+ _sink_state(team, _State.PENDING_BACKFILL) # healthy: not counted++ backfill_module._emit_state_gauge()++ assert backfill_module.STUCK_BACKFILL_GAUGE._value.get() == 1+ assert backfill_module.STUCK_BACKFILL_OLDEST_AGE_GAUGE._value.get() == pytest.approx(+ timedelta(days=20).total_seconds(), rel=0.01+ )++ def test_reconcile_escalates_wedged_run_to_failing_once(self):+ # A duckgres 'failed' status is terminal — the run never retries itself,+ # so reconcile must classify the schema failing immediately or its+ # backlog sits in the pageable healthy bucket forever.+ candidate = _sink_state(self._team(), _State.BACKFILLING)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(+ backfill_run_uuid="bf-run", chunk_count=5, chunks_applied=1+ )+ candidate.refresh_from_db()++ backfill_module._reconcile_one(_fake_conn([(1,), ("chunk exploded", None)]), candidate)++ candidate.refresh_from_db()+ assert candidate.state == _State.BACKFILLING+ assert candidate.consecutive_failures >= backfill_module.FAILING_THRESHOLD+ assert candidate.first_failed_at is not None+ assert candidate.last_error == "chunk exploded"+ streak_started_at = candidate.first_failed_at+ marked_at = candidate.updated_at++ # A steady wedge stops churning the row once recorded (same error,+ # streak already at threshold, anchor stamped).+ backfill_module._reconcile_one(_fake_conn([(1,), ("chunk exploded", None)]), candidate)+ candidate.refresh_from_db()+ assert candidate.first_failed_at == streak_started_at+ assert candidate.updated_at == marked_at++ def test_reconcile_supersession_is_streak_neutral(self):+ # Retirement by a newer live replace run is normal lifecycle, not failure.+ candidate = _sink_state(self._team(), _State.BACKFILLING)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(backfill_run_uuid="bf-run", chunk_count=5)+ candidate.refresh_from_db()++ backfill_module._reconcile_one(_fake_conn([(0,), ("superseded", RETIRE_KIND_SUPERSEDED_BY_REPLACE)]), candidate)++ candidate.refresh_from_db()+ assert candidate.state == _State.NEEDS_RESYNC+ assert candidate.consecutive_failures == 0+ assert candidate.first_failed_at is None++ @freeze_time("2026-01-15T12:00:00Z")+ def test_reconcile_chunk_progress_resets_streak(self):+ # Chunks landing again is forward progress: the streak (and with it the+ # failing classification) must end, or a healed schema stays unalerted.+ candidate = _sink_state(self._team(), _State.BACKFILLING)+ DuckgresSinkSchemaState.objects.filter(id=candidate.id).update(+ backfill_run_uuid="bf-run",+ chunk_count=5,+ chunks_applied=1,+ snapshot_version=None,+ consecutive_failures=4,+ first_failed_at=timezone.now(),+ )+ candidate.refresh_from_db()++ # applied=3 (progress), no failed batch, all 5 chunk rows still present.+ backfill_module._reconcile_one(_fake_conn([(3,), None, (5,)]), candidate)++ candidate.refresh_from_db()+ assert candidate.chunks_applied == 3+ assert candidate.consecutive_failures == 0+ assert candidate.first_failed_at is None+++# transaction=True: failing_schema_ids calls close_old_connections (thread-entry+# hygiene for the consumer's sync_to_async maintenance calls), which severs the+# TestCase-style transaction-wrapped connection.[email protected]_db(transaction=True)+class TestFailingSchemaClassification:+ def test_failing_schema_ids_classification(self):+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")++ def _state_with(state: str, failures: int) -> DuckgresSinkSchemaState:+ row = _sink_state(team, state)+ DuckgresSinkSchemaState.objects.filter(id=row.id).update(consecutive_failures=failures)+ return row++ healthy_pending = _state_with(_State.PENDING_BACKFILL, 0)+ below_threshold = _state_with(_State.PENDING_BACKFILL, backfill_module.FAILING_THRESHOLD - 1)+ failing_pending = _state_with(_State.PENDING_BACKFILL, backfill_module.FAILING_THRESHOLD)+ failing_backfilling = _state_with(_State.BACKFILLING, backfill_module.FAILING_THRESHOLD)+ parked = _state_with(_State.NEEDS_RESYNC, 0)+ # PRIMED is never failing, even with a stale streak left behind.+ primed_stale_streak = _state_with(_State.PRIMED, 10)++ assert set(backfill_module.failing_schema_ids([team.id])) == {+ str(failing_pending.schema_id),+ str(failing_backfilling.schema_id),+ str(parked.schema_id),+ }+ assert backfill_module.failing_schema_ids([]) == []+ for row in (healthy_pending, below_threshold, primed_stale_streak):+ assert str(row.schema_id) not in backfill_module.failing_schema_ids(None)++@pytest.mark.django_dbclass TestDeletedSchemaPurge:def _fixture(self, deleted: bool, run_uuid: str | None = "run-1"):@@ -238,60 +481,39 @@ class TestDeletedSchemaPurge:)schema = ExternalDataSchema.objects.create(team=team, source=source, name="customers", deleted=deleted)state = DuckgresSinkSchemaState.objects.create(- team=team,- schema_id=schema.id,- state=DuckgresSinkSchemaState.State.BACKFILLING,- backfill_run_uuid=run_uuid,+ team=team, schema_id=schema.id, state=DuckgresSinkSchemaState.State.BACKFILLING, backfill_run_uuid=run_uuid)return schema, statedef test_purge_retires_run_and_drops_state_for_deleted_schema(self):- # A deleted schema's chunks are unclaimable, so its BACKFILLING row would- # otherwise pin one of the global backfill slots forever with zero- # failures on any gauge._, state = self._fixture(deleted=True)conn = MagicMock()-with patch.object(backfill_module, "retire_backfill_run") as retire:backfill_module._purge_deleted_schema_states(conn, None)-retire.assert_called_once_with(conn, run_uuid="run-1")assert not DuckgresSinkSchemaState.objects.filter(id=state.id).exists()def test_purge_leaves_live_schemas_untouched(self):_, state = self._fixture(deleted=False)conn = MagicMock()-with patch.object(backfill_module, "retire_backfill_run") as retire:backfill_module._purge_deleted_schema_states(conn, None)-retire.assert_not_called()assert DuckgresSinkSchemaState.objects.filter(id=state.id).exists()def test_plan_one_skips_deleted_schema(self):- # The default manager includes soft-deleted rows, so without the guard a- # deleted schema would be planned and its unclaimable chunks enqueued- # (and re-enqueued after every queue prune).- schema, state = self._fixture(deleted=True, run_uuid=None)-+ _, state = self._fixture(deleted=True, run_uuid=None)with (patch.object(backfill_module, "resolve_snapshot_plan") as resolve,patch.object(backfill_module.psycopg, "connect") as connect,):backfill_module._plan_one(state)-resolve.assert_not_called()connect.assert_not_called()class TestEnqueueLockTimeout:def test_lock_timeout_skips_replay_and_resets(self):- # A dead lock-holder session previously blocked every pod's reconciler- # replay indefinitely, inline in the consumer fetch path.- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (- backfill_queue,- )-conn = MagicMock()def execute(query, *args, **kwargs):@@ -300,12 +522,8 @@ class TestEnqueueLockTimeout:return MagicMock()conn.execute.side_effect = execute- schema = MagicMock()-- inserted = backfill_queue.enqueue_chunks(conn, schema, "run-x", [])-- assert inserted == 0- executed = [str(c.args[0]) for c in conn.execute.call_args_list]- assert any("SET lock_timeout" in q for q in executed)- assert any("RESET lock_timeout" in q for q in executed)- assert not any("INSERT INTO" in q for q in executed)+ assert enqueue_chunks(conn, MagicMock(), "run-x", []) == 0+ executed = [str(call.args[0]) for call in conn.execute.call_args_list]+ assert any("SET lock_timeout" in query for query in executed)+ assert any("RESET lock_timeout" in query for query in executed)+ assert not any("INSERT INTO" in query for query in executed)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.pyindex 45edbc3b926d..e78b26eb9cfa 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@@ -265,7 +265,7 @@ class TestDuckgresEnablementGating:patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",new_callable=AsyncMock,- return_value=(0, None, 0, None),+ return_value=(0, None, 0, None, 0),) as mock_backlog,patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",@@ -274,6 +274,10 @@ class TestDuckgresEnablementGating:"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",return_value=["blocked-schema"],),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_failing_schema_ids",+ return_value=[],+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",return_value=["eligible-schema"],@@ -320,7 +324,7 @@ class TestDuckgresEnablementGating:patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",new_callable=AsyncMock,- return_value=(0, None, 0, None),+ return_value=(0, None, 0, None, 0),),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",@@ -362,7 +366,7 @@ class TestDuckgresEnablementGating:patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",new_callable=AsyncMock,- return_value=(0, None, 0, None),+ return_value=(0, None, 0, None, 0),),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",@@ -371,6 +375,10 @@ class TestDuckgresEnablementGating:"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",return_value=["blocked-schema"],),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_failing_schema_ids",+ return_value=[],+ ),patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_eligible_schema_ids",side_effect=RuntimeError("flag eval down"),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.pyindex 532e729cdce7..27885f4a258d 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@@ -397,28 +397,44 @@ class TestDuckgresTeamFilterAndBacklog:batch_id = await _insert_batch(conn, sync_type="incremental")await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)- count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(conn)- assert (count, blocked) == (1, 0)+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn)+ assert (count, blocked, failing) == (1, 0, 0)assert oldest_age is not None and oldest_age >= 0assert blocked_age is None# The same batch counts as blocked (not eligible) once its schema is gated.- count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn, blocked_schema_ids=["schema-1"])- assert (count, blocked) == (0, 1)+ assert (count, blocked, failing) == (0, 1, 0)assert oldest_age is None and blocked_age is not None+ # A hard-blocked schema's batches leave the pageable blocked bucket+ # (count AND oldest-age) for the failing one — a wedged schema must not+ # be able to trigger or mask the blocked-backlog page.+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(+ conn, blocked_schema_ids=["schema-1"], failing_schema_ids=["schema-1"]+ )+ assert (count, blocked, failing) == (0, 0, 1)+ assert blocked_age is None++ # A failing schema whose batches are NOT blocked (still eligible) never+ # counts in the failing bucket: failing splits the blocked set only.+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(+ conn, failing_schema_ids=["schema-1"]+ )+ assert (count, blocked, failing) == (1, 0, 0)+# The v3 allow-list scopes the gauges too: a non-eligible schema drops# out of both the eligible and blocked counts.- count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn, eligible_schema_ids=["other-schema"])- assert (count, blocked) == (0, 0)+ assert (count, blocked, failing) == (0, 0, 0)await _mark_applied_raw(conn, batch_id=batch_id, run_uuid="run-1", batch_index=0)- count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(conn)- assert (count, blocked) == (0, 0)+ count, oldest_age, blocked, blocked_age, failing = await DuckgresBatchQueue.get_backlog_stats(conn)+ assert (count, blocked, failing) == (0, 0, 0)assert oldest_age is None and blocked_age is None