: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): duckgres sink backfill primer (#63144)
Eric Duong47ed91facb78
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 85124478cc60..ab0473a48507 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -163,6 +163,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"DuckLakeCatalog","DuckgresServer","DuckgresServerTeam",+ "DuckgresSinkSchemaState","EvaluationConfig","RemoteConfig","TeamConversationsSlackConfig",diff --git a/.github/scripts/conftest.py b/.github/scripts/conftest.pynew file mode 100644index 000000000000..2416fda6a29e--- /dev/null+++ b/.github/scripts/conftest.py@@ -0,0 +1,15 @@+import pytest++[email protected](autouse=True)+def _activate_personhog_fake():+ """No-op override of the repo-root autouse fixture for the script tests.++ The repo-root ``conftest.py`` registers an autouse ``_activate_personhog_fake``+ that imports ``posthog`` -> ``django``. The ``.github/scripts`` unit tests run+ under a deliberately minimal environment with only ``pytest`` installed and no+ ``django`` (see ``.github/workflows/ci-scripts.yml``), and they never read+ person/group data, so the personhog fake is unnecessary here. Shadowing the+ fixture by name keeps these tests runnable without django.+ """+ yielddiff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.pyindex aca66374ae00..7ab4a3a2df5a 100644--- a/posthog/ducklake/models.py+++ b/posthog/ducklake/models.py@@ -109,3 +109,63 @@ class DuckgresServerTeam(CreatedMetaFields, UpdatedMetaFields, UUIDModel):db_table = "posthog_duckgresserverteam"verbose_name = "Duckgres server team"verbose_name_plural = "Duckgres server teams"+++class DuckgresSinkSchemaState(CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ r"""Per-schema lifecycle of the Duckgres v3 batch sink.++ The sink only applies live batches for a schema once its history has been+ primed into duckgres (or it needs no priming). The backfill planner owns+ the transitions:++ PENDING_BACKFILL -> BACKFILLING -> PRIMED+ \-> (superseded by a live full refresh) -> PRIMED+ PRIMED -> NEEDS_RESYNC (retention-loss gap) -> PENDING_BACKFILL+ """++ class State(models.TextChoices):+ PENDING_BACKFILL = "pending_backfill", "Pending backfill"+ BACKFILLING = "backfilling", "Backfilling"+ PRIMED = "primed", "Primed"+ NEEDS_RESYNC = "needs_resync", "Needs resync"++ # db_constraint=False: a real FK constraint on posthog_team locks that hot+ # table when this table is created (HotTableAlterPolicy). The tenant link is+ # enforced at the app level.+ team = models.ForeignKey(+ "posthog.Team",+ on_delete=models.CASCADE,+ related_name="duckgres_sink_schema_states",+ db_constraint=False,+ )+ # ExternalDataSchema id. Not a FK: the queue addresses schemas by string id+ # and the schema row may be soft-deleted while sink state must survive for+ # cleanup decisions.+ schema_id = models.UUIDField(unique=True)+ state = models.CharField(max_length=32, choices=State.choices, default=State.PENDING_BACKFILL)+ # Delta table version the backfill is pinned to.+ snapshot_version = models.BigIntegerField(null=True, blank=True)+ # Deprecated planning boundary retained for rows created by older planner+ # revisions. New plans derive containment from Delta commit versions.+ plan_cutoff = models.DateTimeField(null=True, blank=True)+ backfill_run_uuid = models.CharField(max_length=200, null=True, blank=True)+ chunk_count = models.IntegerField(null=True, blank=True)+ chunks_applied = models.IntegerField(default=0)+ last_error = models.TextField(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 an+ # optional audit pointer.+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ db_constraint=False,+ )++ class Meta:+ db_table = "posthog_duckgressinkschemastate"+ verbose_name = "Duckgres sink schema state"+ verbose_name_plural = "Duckgres sink schema states"+ indexes = [models.Index(fields=["team", "state"], name="duckgres_sink_team_state_idx")]diff --git a/posthog/migrations/1245_duckgres_sink_schema_state.py b/posthog/migrations/1245_duckgres_sink_schema_state.pynew file mode 100644index 000000000000..48591efe264f--- /dev/null+++ b/posthog/migrations/1245_duckgres_sink_schema_state.py@@ -0,0 +1,75 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1244_team_event_retention_months"),+ ]++ operations = [+ migrations.CreateModel(+ name="DuckgresSinkSchemaState",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False+ ),+ ),+ ("schema_id", models.UUIDField(unique=True)),+ (+ "state",+ models.CharField(+ choices=[+ ("pending_backfill", "Pending backfill"),+ ("backfilling", "Backfilling"),+ ("primed", "Primed"),+ ("needs_resync", "Needs resync"),+ ],+ default="pending_backfill",+ max_length=32,+ ),+ ),+ ("snapshot_version", models.BigIntegerField(blank=True, null=True)),+ ("plan_cutoff", models.DateTimeField(blank=True, null=True)),+ ("backfill_run_uuid", models.CharField(blank=True, max_length=200, null=True)),+ ("chunk_count", models.IntegerField(blank=True, null=True)),+ ("chunks_applied", models.IntegerField(default=0)),+ ("last_error", models.TextField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="duckgres_sink_schema_states",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "verbose_name": "Duckgres sink schema state",+ "verbose_name_plural": "Duckgres sink schema states",+ "db_table": "posthog_duckgressinkschemastate",+ },+ ),+ migrations.AddIndex(+ model_name="duckgressinkschemastate",+ index=models.Index(fields=["team", "state"], name="duckgres_sink_team_state_idx"),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 173198f725e0..66a71b80d784 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1244_team_event_retention_months+1245_duckgres_sink_schema_statediff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 4a6f1f9d5147..5f1db954e23f 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -15,7 +15,7 @@ from .comment import Commentfrom .core_event import CoreEventfrom .data_deletion_request import DataDeletionRequestfrom .data_color_theme import DataColorTheme-from ..ducklake.models import DuckgresServer, DuckgresServerTeam+from ..ducklake.models import DuckgresServer, DuckgresServerTeam, DuckgresSinkSchemaStatefrom .element import Elementfrom .element_group import ElementGroupfrom .entity import Entity@@ -101,6 +101,7 @@ __all__ = ["DeletionType","DuckgresServer","DuckgresServerTeam",+ "DuckgresSinkSchemaState","Element","ElementGroup","Entity",diff --git a/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.py b/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.pyindex 1f87243a641f..37e5ad5e35d4 100644--- a/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.py+++ b/products/warehouse_sources/backend/management/commands/reset_duckgres_failed_runs.py@@ -1,3 +1,4 @@+from django.core.exceptions import ValidationErrorfrom django.core.management.base import BaseCommand, CommandErrorimport psycopg@@ -30,8 +31,37 @@ class Command(BaseCommand):parser.add_argument("--team-id", type=int, help="Scope by team (with --schema-id)")parser.add_argument("--schema-id", type=str, help="Reset all failed duckgres runs of this schema")parser.add_argument("--dry-run", action="store_true", help="Report what would be reset without writing")+ parser.add_argument(+ "--replan-backfill",+ metavar="SCHEMA_ID",+ help="Retire the schema's current backfill run and re-enter backfill planning "+ "(use when extracts were lost to retention or the backfill is wedged)",+ )def handle(self, *args, **options):+ replan_schema = options.get("replan_backfill")+ if replan_schema:+ from posthog.models import DuckgresSinkSchemaState++ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (+ replan_backfill,+ )++ try:+ state = DuckgresSinkSchemaState.objects.get(schema_id=replan_schema)+ except (DuckgresSinkSchemaState.DoesNotExist, ValueError, ValidationError) as e:+ raise CommandError(f"No duckgres sink state for schema {replan_schema!r}: {e}")+ if options.get("dry_run"):+ self.stdout.write(+ f"Would retire backfill run {state.backfill_run_uuid!r} "+ f"(state={state.state}, applied={state.chunks_applied}/{state.chunk_count}) "+ "and re-enter planning. Dry run — no changes written."+ )+ return+ replan_backfill(replan_schema)+ self.stdout.write(self.style.SUCCESS(f"Schema {replan_schema} re-entered backfill planning."))+ return+run_uuid = options.get("run_uuid")team_id = options.get("team_id")schema_id = options.get("schema_id")diff --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.pynew file mode 100644index 000000000000..8142547f56de--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill.py@@ -0,0 +1,538 @@+"""Backfill primer for the Duckgres batch sink — durable state machine.++Pre-existing incremental/append schemas have history in Delta that the sink's+per-batch stream will never replay. The primer backfills it with bounded+memory and resume-from-checkpoint. This module owns the lifecycle+(DuckgresSinkSchemaState transitions + reconciliation); the moving parts live+in sibling modules:++- backfill_snapshot.py — Delta snapshot resolution and chunk planning (pure).+- backfill_queue.py — idempotent queue writes (pre-apply, enqueue, retire).+- batch_kind.py — the canonical live-vs-backfill batch discriminator.++Lifecycle (every transition is a compare-and-swap; the planner runs in every+consumer pod's maintenance tick with no leader election):++ PENDING_BACKFILL --lease CAS--> BACKFILLING(no run) [lease-reset on crash]+ BACKFILLING(no run) --plan CAS--> BACKFILLING(run) [the durable plan:+ run_uuid + snapshot_version + chunk_count, written+ BEFORE any queue rows; reconcile replays pre-apply/enqueue from it]+ BACKFILLING(run) --> PRIMED when chunks_applied == chunk_count (the last+ chunk's apply marker shares the swap's transaction, so full+ application proves the swap), or fast-path via mark_primed after the swap.+ BACKFILLING(run) --> NEEDS_RESYNC when superseded by a LIVE replace run+ (structured kind): the replace has only reached Delta and may still+ fail in duckgres, so it heals to PRIMED through the resync path below+ rather than flipping PRIMED on a not-yet-complete table.+ *_ --> NEEDS_RESYNC for unbackfillable tables (deletion vectors) or a+ superseding replace; heals to PRIMED only when a live replace-head run+ has FULLY applied (its final marker reached duckgres-succeeded) —+ replace-head runs bypass the blocked gate precisely so that healing+ path can run.++PRIMED always means "the duckgres table is complete"; nothing else ever sets+it. Containment of pre-applied work is proven per batch from Delta commit+metadata at the pinned snapshot version (see backfill_queue.preapply_covered_batches).+"""++from __future__ import annotations++from datetime import timedelta+from typing import Any++from django.conf import settings+from django.db import close_old_connections+from django.db.models import Count+from django.utils import timezone++import psycopg+import structlog+from prometheus_client import Gauge++from posthog.exceptions_capture import capture_exception+from posthog.models import DuckgresSinkSchemaState++from products.warehouse_sources.backend.models import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (+ BACKFILL_JOB_ID,+ REASON_COVERED_BY_SNAPSHOT,+ backfill_run_uuid,+ enqueue_chunks,+ preapply_covered_batches,+ retire_backfill_run,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (+ BackfillUnsupportedError,+ resolve_snapshot_plan,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (+ LIVE_BATCH_SQL_PREDICATE,+)+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.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ PARTITION_PRUNING_INTERVAL,+)++logger = structlog.get_logger(__name__)++MAX_CONCURRENT_BACKFILLS_PER_ORG = 1 # best-effort across pods (see _plan_pending)+# A claim that never produced a durable run plan within this window is+# considered crashed and is returned to PENDING by the reconciler. Planning is+# metadata-only (Delta log read + row inserts), so minutes of lease are ample.+PLANNING_LEASE_SECONDS = 900++BACKFILL_SCHEMAS_GAUGE = Gauge(+ "duckgres_backfill_schemas",+ "Duckgres sink schemas per backfill lifecycle state",+ labelnames=["state"],+ multiprocess_mode="livemax",+)++__all__ = [+ "BACKFILL_JOB_ID",+ "BackfillUnsupportedError",+ "backfill_run_uuid",+ "blocked_schema_ids",+ "mark_primed",+ "replan_backfill",+ "run_backfill_planner",+]+++def run_backfill_planner(team_ids: list[int] | None) -> None:+ """One planner pass: bootstrap state rows, reconcile in-flight, plan pending.++ Per-schema failures are isolated; called from the consumer's maintenance+ tick (sync_to_async, thread_sensitive=False).+ """+ close_old_connections()+ if team_ids is not None and not team_ids:+ return++ _bootstrap_state_rows(team_ids)+ _reconcile(team_ids)+ _plan_pending(team_ids)+ _emit_state_gauge()+++def blocked_schema_ids(team_ids: list[int] | None) -> list[str]:+ """Schemas whose live batches the sink must not apply yet.++ A schema is blocked unless it has a PRIMED state row — including schemas+ with no row at all, so there is no window between flag-flip and the first+ planner pass where a pre-existing schema's live batches sneak in. The+ queue grants one exception: replace-head runs bypass the block (they+ rebuild the table from scratch, which is always safe and is the healing+ path for NEEDS_RESYNC).+ """+ close_old_connections()+ if team_ids is not None and not team_ids:+ return []++ schemas = ExternalDataSchema.objects.exclude(deleted=True)+ if team_ids is not None:+ schemas = schemas.filter(team_id__in=team_ids)+ primed = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.PRIMED)+ if team_ids is not None:+ primed = primed.filter(team_id__in=team_ids)+ primed_ids = {str(s) for s in primed.values_list("schema_id", flat=True)}+ return [str(sid) for sid in schemas.values_list("id", flat=True) if str(sid) not in primed_ids]+++def mark_primed(schema_id: str, *, chunks_applied: int | None = None) -> None:+ """Fast path called by the processor right after the swap commits.++ CAS from BACKFILLING only — the reconciler is the authoritative healer,+ and a late call must never clobber a state that has since moved on.+ """+ updates: dict[str, Any] = {+ "state": DuckgresSinkSchemaState.State.PRIMED,+ "updated_at": timezone.now(),+ }+ if chunks_applied is not None:+ updates["chunks_applied"] = chunks_applied+ DuckgresSinkSchemaState.objects.filter(schema_id=schema_id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(+ **updates+ )+++def replan_backfill(schema_id: str) -> None:+ """Operator entrypoint: retire the current backfill run and re-enter planning.++ The next plan gets a fresh generation nonce, so an unadvanced Delta+ version still yields a new, claimable run.+ """+ state = DuckgresSinkSchemaState.objects.get(schema_id=schema_id)+ if state.backfill_run_uuid:+ with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ retire_backfill_run(conn, run_uuid=state.backfill_run_uuid)+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(+ state=DuckgresSinkSchemaState.State.PENDING_BACKFILL,+ snapshot_version=None,+ plan_cutoff=None,+ backfill_run_uuid=None,+ chunk_count=None,+ chunks_applied=0,+ last_error=None,+ updated_at=timezone.now(),+ )+++# ---------------------------------------------------------------------------+# Bootstrap & planning+# ---------------------------------------------------------------------------+++def _bootstrap_state_rows(team_ids: list[int] | None) -> None:+ """Create state rows for enabled teams' schemas that have none.++ Straight to PRIMED when no priming is needed:+ - full_refresh: every run's batch 0 replaces the table completely.+ - no Delta table yet: the first sync creates everything.+ - cdc: the sink rejects CDC batches outright; do not block the queue on it.+ """+ schemas = ExternalDataSchema.objects.exclude(deleted=True).select_related("team")+ if team_ids is not None:+ schemas = schemas.filter(team_id__in=team_ids)+ existing = {str(s) for s in DuckgresSinkSchemaState.objects.all().values_list("schema_id", flat=True)}++ to_create: list[DuckgresSinkSchemaState] = []+ for schema in schemas:+ if str(schema.id) in existing:+ continue+ needs_backfill = schema.sync_type not in ("full_refresh", "cdc", None) and schema.table_id is not None+ to_create.append(+ DuckgresSinkSchemaState(+ team_id=schema.team_id,+ schema_id=schema.id,+ state=(+ DuckgresSinkSchemaState.State.PENDING_BACKFILL+ if needs_backfill+ else DuckgresSinkSchemaState.State.PRIMED+ ),+ )+ )+ if to_create:+ DuckgresSinkSchemaState.objects.bulk_create(to_create, ignore_conflicts=True)+ logger.info("duckgres_backfill_bootstrapped", created=len(to_create))+++def _plan_pending(team_ids: list[int] | None) -> None:+ pending = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.PENDING_BACKFILL)+ if team_ids is not None:+ pending = pending.filter(team_id__in=team_ids)++ # Oldest-touched first so a failing schema cannot starve the rest of the slice.+ for state in pending.select_related("team").order_by("updated_at")[:50]:+ org_id = state.team.organization_id+ if _org_busy(org_id):+ continue++ # Lease claim: exactly one pod proceeds past this line per schema.+ claimed = DuckgresSinkSchemaState.objects.filter(+ id=state.id, state=DuckgresSinkSchemaState.State.PENDING_BACKFILL+ ).update(state=DuckgresSinkSchemaState.State.BACKFILLING, updated_at=timezone.now())+ if not claimed:+ continue++ # Re-check the org cap after winning the claim; the pre-check raced+ # against other pods. (Still best-effort across orgs — a transient+ # second concurrent backfill per org is wasteful, not incorrect.)+ if (+ DuckgresSinkSchemaState.objects.filter(+ state=DuckgresSinkSchemaState.State.BACKFILLING,+ team__organization_id=org_id,+ )+ .exclude(id=state.id)+ .exists()+ ):+ _revert_to_pending(state.id)+ continue++ try:+ _plan_one(state)+ except BackfillUnsupportedError as e:+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(+ state=DuckgresSinkSchemaState.State.NEEDS_RESYNC,+ last_error=str(e)[:2000],+ updated_at=timezone.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])+++def _org_busy(org_id: Any) -> bool:+ return (+ DuckgresSinkSchemaState.objects.filter(+ state=DuckgresSinkSchemaState.State.BACKFILLING,+ team__organization_id=org_id,+ ).count()+ >= MAX_CONCURRENT_BACKFILLS_PER_ORG+ )+++def _revert_to_pending(state_id: Any, error: str | None = None) -> None:+ updates: dict[str, Any] = {+ "state": DuckgresSinkSchemaState.State.PENDING_BACKFILL,+ "updated_at": timezone.now(),+ }+ if error is not None:+ updates["last_error"] = error+ DuckgresSinkSchemaState.objects.filter(+ id=state_id, state=DuckgresSinkSchemaState.State.BACKFILLING, backfill_run_uuid__isnull=True+ ).update(**updates)+++def _plan_one(state: DuckgresSinkSchemaState) -> None:+ """Runs only on the pod that won the lease claim.++ Ordering is crash-safety-critical:+ 1. resolve the snapshot (no side effects),+ 2. CAS the durable run plan onto the state row — the real claim,+ 3. pre-apply covered batches, 4. enqueue chunks.+ A crash after step 2 is healed by _reconcile_one (replay 3-4 from the+ stored plan); a crash before it is healed by the planning lease.+ """+ schema = ExternalDataSchema.objects.select_related("source", "team").get(id=state.schema_id)++ with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ plan = resolve_snapshot_plan(schema)+ snapshot_version = plan.snapshot_version+ chunks = plan.chunks+ if not chunks:+ # Empty Delta table: nothing to prime.+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(+ state=DuckgresSinkSchemaState.State.PRIMED, updated_at=timezone.now()+ )+ return++ run_uuid = backfill_run_uuid(str(state.schema_id), snapshot_version)++ # Durable plan claim: only one pod can attach a run to this state row.+ planned = DuckgresSinkSchemaState.objects.filter(+ id=state.id,+ state=DuckgresSinkSchemaState.State.BACKFILLING,+ backfill_run_uuid__isnull=True,+ ).update(+ snapshot_version=snapshot_version,+ plan_cutoff=None,+ backfill_run_uuid=run_uuid,+ chunk_count=len(chunks),+ chunks_applied=0,+ last_error=None,+ updated_at=timezone.now(),+ )+ if not planned:+ return++ preapplied = preapply_covered_batches(+ conn,+ team_id=schema.team_id,+ schema_id=str(state.schema_id),+ covered_batches=plan.covered_batches,+ reason=f"{REASON_COVERED_BY_SNAPSHOT} v{snapshot_version}",+ )+ inserted = enqueue_chunks(conn, schema, run_uuid, chunks)++ logger.info(+ "duckgres_backfill_planned",+ schema_id=str(state.schema_id),+ team_id=schema.team_id,+ run_uuid=run_uuid,+ snapshot_version=snapshot_version,+ chunk_count=len(chunks),+ inserted=inserted,+ preapplied_covered_batches=preapplied,+ total_bytes=sum(c.byte_size for c in chunks),+ )+++# ---------------------------------------------------------------------------+# Reconciliation+# ---------------------------------------------------------------------------+++def _reconcile(team_ids: list[int] | None) -> None:+ """Heal and progress every non-terminal state. Authoritative for PRIMED."""+ # Half-claimed rows (crash between the lease CAS and the plan CAS) carry+ # no run plan; after the lease they return to PENDING for a fresh attempt.+ lease_deadline = timezone.now() - timedelta(seconds=PLANNING_LEASE_SECONDS)+ stale = DuckgresSinkSchemaState.objects.filter(+ state=DuckgresSinkSchemaState.State.BACKFILLING,+ backfill_run_uuid__isnull=True,+ updated_at__lt=lease_deadline,+ )+ if team_ids is not None:+ stale = stale.filter(team_id__in=team_ids)+ reset = stale.update(state=DuckgresSinkSchemaState.State.PENDING_BACKFILL, updated_at=timezone.now())+ if reset:+ logger.warning("duckgres_backfill_stale_claims_reset", count=reset)++ backfilling = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.BACKFILLING)+ needs_resync = DuckgresSinkSchemaState.objects.filter(state=DuckgresSinkSchemaState.State.NEEDS_RESYNC)+ if team_ids is not None:+ backfilling = backfilling.filter(team_id__in=team_ids)+ needs_resync = needs_resync.filter(team_id__in=team_ids)+ rows = [s for s in backfilling if s.backfill_run_uuid]+ resync_rows = list(needs_resync)+ if not rows and not resync_rows:+ return++ with psycopg.connect(settings.WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ for state in rows:+ try:+ _reconcile_one(conn, state)+ except Exception as e:+ logger.exception("duckgres_backfill_reconcile_failed", schema_id=str(state.schema_id))+ capture_exception(e)+ for state in resync_rows:+ try:+ _reconcile_needs_resync(conn, state)+ except Exception as e:+ logger.exception("duckgres_backfill_resync_check_failed", schema_id=str(state.schema_id))+ capture_exception(e)+++def _reconcile_one(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaState) -> None:+ run_uuid = state.backfill_run_uuid+ applied_row = conn.execute(+ "SELECT count(DISTINCT batch_index) FROM sourcebatchduckgresapply WHERE run_uuid = %s", [run_uuid]+ ).fetchone()+ applied = int(applied_row[0]) if applied_row else 0++ if state.chunk_count and applied >= state.chunk_count:+ # Full application proves the swap committed (the last chunk's apply+ # marker shares the swap's transaction). CAS so a stale pass can never+ # resurrect a state another pod already advanced.+ DuckgresSinkSchemaState.objects.filter(id=state.id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(+ state=DuckgresSinkSchemaState.State.PRIMED,+ chunks_applied=applied,+ updated_at=timezone.now(),+ )+ return++ failed = conn.execute(+ f"""+ SELECT dgs.error_response->>'error', dgs.error_response->>'kind'+ FROM v_latest_source_batch_duckgres_status dgs+ JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id+ WHERE b.run_uuid = %s AND dgs.job_state = 'failed'+ LIMIT 1+ """,+ [run_uuid],+ ).fetchone()++ if failed is not None:+ reason = failed[0] or ""+ kind = failed[1]+ if kind == RETIRE_KIND_SUPERSEDED_BY_REPLACE:+ # A LIVE replace run retired the backfill. The replace rebuilds the+ # table completely, but at this point it has only reached Delta — it+ # may still fail in duckgres. Flipping straight to PRIMED here would+ # unblock live batches over a stale/incomplete table if the replace+ # later exhausts retries. Park in NEEDS_RESYNC so the resync path+ # promotes to PRIMED only once the replace run's final marker reaches+ # duckgres-succeeded (the same completion proof every PRIMED requires).+ DuckgresSinkSchemaState.objects.filter(id=state.id, state=DuckgresSinkSchemaState.State.BACKFILLING).update(+ state=DuckgresSinkSchemaState.State.NEEDS_RESYNC, last_error=None, updated_at=timezone.now()+ )+ logger.info(+ "duckgres_backfill_superseded_by_live_refresh",+ schema_id=str(state.schema_id),+ run_uuid=run_uuid,+ )+ elif state.last_error != reason:+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(+ last_error=reason[:2000], chunks_applied=applied, updated_at=timezone.now()+ )+ return++ # Healthy in-flight run: track progress and replay plan side effects lost+ # to a crash or to 7-day queue retention (apply markers persist 30d, so+ # resume is exact; all replayed writes are idempotent).+ # count DISTINCT batch_index, not count(*): a duplicate chunk row must never+ # inflate the count and mask a genuinely missing index, which would stop the+ # replay from re-enqueueing it.+ present_row = conn.execute(+ f"SELECT count(DISTINCT batch_index) FROM {BATCH_TABLE} WHERE run_uuid = %s", [run_uuid]+ ).fetchone()+ present = int(present_row[0]) if present_row else 0+ if state.chunk_count and present < state.chunk_count and state.snapshot_version is not None:+ schema = ExternalDataSchema.objects.select_related("source").get(id=state.schema_id)+ plan = resolve_snapshot_plan(schema, version=state.snapshot_version)+ preapply_covered_batches(+ conn,+ team_id=state.team_id,+ schema_id=str(state.schema_id),+ covered_batches=plan.covered_batches,+ reason=f"{REASON_COVERED_BY_SNAPSHOT} v{state.snapshot_version}",+ )+ chunks = plan.chunks+ reinserted = enqueue_chunks(conn, schema, str(run_uuid), chunks)+ if reinserted:+ logger.info(+ "duckgres_backfill_reenqueued_dropped_chunks",+ schema_id=str(state.schema_id),+ run_uuid=run_uuid,+ reinserted=reinserted,+ )++ if applied != state.chunks_applied:+ DuckgresSinkSchemaState.objects.filter(id=state.id).update(chunks_applied=applied, updated_at=timezone.now())+++def _reconcile_needs_resync(conn: psycopg.Connection[Any], state: DuckgresSinkSchemaState) -> None:+ """Flip NEEDS_RESYNC to PRIMED only when a replace run has FULLY applied.++ Replace-head runs bypass the blocked gate (jobs_db), so a user-triggered+ full refresh can run while the schema is parked. Its final marker reaches+ duckgres-succeeded only after every prior batch applied — that is the+ completion proof, so PRIMED keeps its single meaning: the table is+ complete.+ """+ live_predicate_f = LIVE_BATCH_SQL_PREDICATE.replace("b.", "f.")+ done = conn.execute(+ f"""+ SELECT 1+ FROM {BATCH_TABLE} f+ JOIN v_latest_source_batch_duckgres_status fdgs ON f.id = fdgs.batch_id+ WHERE f.team_id = %(team_id)s+ AND f.schema_id = %(schema_id)s+ AND f.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND {live_predicate_f}+ AND f.is_final_batch = true+ AND fdgs.job_state = 'succeeded'+ AND EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} h+ WHERE h.run_uuid = f.run_uuid+ AND h.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND h.batch_index = 0+ AND h.is_final_batch = false+ AND h.is_resume = false+ AND (h.sync_type = 'full_refresh' OR (h.sync_type = 'incremental' AND h.is_first_ever_sync))+ )+ LIMIT 1+ """,+ {"team_id": state.team_id, "schema_id": str(state.schema_id)},+ ).fetchone()+ if done is None:+ return++ flipped = DuckgresSinkSchemaState.objects.filter(+ id=state.id, state=DuckgresSinkSchemaState.State.NEEDS_RESYNC+ ).update(state=DuckgresSinkSchemaState.State.PRIMED, last_error=None, updated_at=timezone.now())+ if flipped:+ logger.info("duckgres_backfill_resync_completed", schema_id=str(state.schema_id))+++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))diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.pynew file mode 100644index 000000000000..6fc67103de36--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_queue.py@@ -0,0 +1,230 @@+"""Queue-side writes for the duckgres backfill.++Everything here is idempotent so the reconciler can replay any step after a+crash: pre-apply markers upsert by their natural key, status inserts guard on+the latest-status view, and chunk enqueue keys on (run_uuid, batch_index).+"""++from __future__ import annotations++import uuid+from typing import Any++import psycopg++from products.warehouse_sources.backend.models import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (+ BackfillChunk,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (+ LIVE_BATCH_SQL_PREDICATE,+ build_backfill_metadata,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ PARTITION_PRUNING_INTERVAL,+ STATUS_TABLE as DELTA_STATUS_TABLE,+)++BACKFILL_JOB_ID = "duckgres-backfill"++# Session advisory-lock namespace that serializes enqueue_chunks per run_uuid.+# Distinct from the batch-claim lock namespace (0x44475300) so the two never+# conflict: (run_uuid, batch_index) has no DB uniqueness guard, so without this+# two pods replaying _reconcile_one for the same run could both pass the+# existing-index check and insert duplicate chunk rows.+BACKFILL_ENQUEUE_LOCK_NAMESPACE = 0x44475301 # "DGS\x01"++# Structured kinds stamped into duckgres status error_response by this module's+# writers (the reconciler dispatches on these, never on message prose).+KIND_COVERED_BY_SNAPSHOT = "covered_by_backfill_snapshot"+KIND_RETIRED_BY_REPLAN = "retired_by_backfill_replan"++REASON_COVERED_BY_SNAPSHOT = "covered by duckgres backfill snapshot"+REASON_RETIRED_BY_REPLAN = "retired by backfill replan"+++def backfill_run_uuid(schema_id: str, snapshot_version: int) -> str:+ """Unique per planning attempt: the generation nonce guarantees a replan at+ an unadvanced Delta version still gets a fresh, claimable run."""+ return f"{BACKFILL_JOB_ID}-{schema_id}-v{snapshot_version}-g{uuid.uuid4().hex[:8]}"+++def preapply_covered_batches(+ conn: psycopg.Connection[Any],+ *,+ team_id: int,+ schema_id: str,+ covered_batches: list[tuple[str, int]],+ reason: str,+) -> int:+ """Mark snapshot-contained batches as already applied — skip, never fail.++ Containment proof is per BATCH: the planner reads the pinned Delta snapshot's+ commit metadata and passes every (run_uuid, batch_index) whose commit version+ is <= the snapshot version. Queue timestamps are deliberately not used here;+ they can race the Delta snapshot read.++ "Applied" is the correct verb (not "failed"): a failed batch poisons its+ whole run via the failed-run exclusion, which would drop a mid-flight run's+ later, post-snapshot batches. Pre-applying instead composes with every+ existing gate: the batch stops being claimable (succeeded status), and its+ siblings' head-of-line check sees it applied (apply marker).++ Idempotent: the marker upserts on its natural key and the status insert+ guards on the latest-status view. Final markers are skipped (they never+ carry apply rows; their no-op pass after PRIMED converges them).+ """+ if not covered_batches:+ return 0++ covered_batch_rows = [+ {"run_uuid": run_uuid, "batch_index": batch_index} for run_uuid, batch_index in covered_batches+ ]+ covered_scope = f"""+ FROM {BATCH_TABLE} b+ JOIN (+ SELECT *+ FROM jsonb_to_recordset(%(covered_batches)s::jsonb)+ AS covered(run_uuid text, batch_index int)+ ) covered+ ON covered.run_uuid = b.run_uuid+ AND covered.batch_index = b.batch_index+ JOIN v_latest_source_batch_status ds ON b.id = ds.batch_id+ LEFT JOIN v_latest_source_batch_duckgres_status dgs ON b.id = dgs.batch_id+ WHERE b.team_id = %(team_id)s+ AND b.schema_id = %(schema_id)s+ AND b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND {LIVE_BATCH_SQL_PREDICATE}+ AND b.is_final_batch = false+ AND ds.job_state = 'succeeded'+ AND (dgs.batch_id IS NULL OR dgs.job_state = 'waiting_retry')+ """+ params = {+ "team_id": team_id,+ "schema_id": schema_id,+ "covered_batches": psycopg.types.json.Jsonb(covered_batch_rows),+ "reason": reason,+ "kind": KIND_COVERED_BY_SNAPSHOT,+ }+ with conn.transaction():+ cursor = conn.execute(+ f"""+ INSERT INTO sourcebatchduckgresapply (team_id, schema_id, run_uuid, batch_index, batch_id, row_count)+ SELECT b.team_id, b.schema_id, b.run_uuid, b.batch_index, b.id, b.row_count+ {covered_scope}+ ON CONFLICT (team_id, schema_id, run_uuid, batch_index) DO NOTHING+ """,+ params,+ )+ conn.execute(+ f"""+ INSERT INTO sourcebatchduckgresstatus (batch_id, job_state, attempt, error_response)+ SELECT b.id, 'succeeded', 0, jsonb_build_object('note', %(reason)s::text, 'kind', %(kind)s::text)+ {covered_scope}+ """,+ params,+ )+ return cursor.rowcount or 0+++def enqueue_chunks(+ conn: psycopg.Connection[Any],+ schema: ExternalDataSchema,+ run_uuid: str,+ chunks: list[BackfillChunk],+) -> int:+ """Insert the synthetic run, idempotently by (run_uuid, batch_index).++ Each batch row and its pre-succeeded Delta status row commit in ONE+ transaction: a synthetic row visible without 'succeeded' status would be+ claimed by the Delta consumer and loaded into the Delta table.++ (run_uuid, batch_index) has no DB uniqueness guard, so a bare+ read-existing-then-insert races: two pods replaying _reconcile_one for the+ same run could both miss a chunk in ``existing`` and insert it twice. A+ session advisory lock keyed on run_uuid serializes enqueue across pods, so+ the later pod reads a complete ``existing`` set and inserts nothing.+ """+ inserted = 0+ conn.execute(+ "SELECT pg_advisory_lock(%s, hashtext(%s))",+ [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],+ )+ try:+ existing = {+ row[0]+ for row in conn.execute(f"SELECT batch_index FROM {BATCH_TABLE} WHERE run_uuid = %s", [run_uuid]).fetchall()+ }+ for chunk in chunks:+ if chunk.index in existing:+ continue+ batch_id = str(uuid.uuid4())+ with conn.transaction():+ conn.execute(+ f"""+ INSERT INTO {BATCH_TABLE} (+ id, team_id, schema_id, source_id, job_id, run_uuid,+ batch_index, s3_path, row_count, byte_size, is_final_batch,+ total_batches, total_rows, sync_type, cumulative_row_count,+ resource_name, is_resume, is_first_ever_sync, metadata+ ) VALUES (+ %(id)s, %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, false,+ %(total_batches)s, NULL, 'full_refresh', 0,+ %(resource_name)s, true, false, %(metadata)s+ )+ """,+ {+ "id": batch_id,+ "team_id": schema.team_id,+ "schema_id": str(schema.id),+ "source_id": str(schema.source_id),+ "job_id": BACKFILL_JOB_ID,+ "run_uuid": run_uuid,+ "batch_index": chunk.index,+ "s3_path": chunk.paths[0],+ "row_count": chunk.row_count,+ "byte_size": chunk.byte_size,+ "total_batches": len(chunks),+ "resource_name": schema.name,+ "metadata": psycopg.types.json.Jsonb(+ build_backfill_metadata(chunk_paths=chunk.paths, chunk_count=len(chunks))+ ),+ },+ )+ conn.execute(+ f"INSERT INTO {DELTA_STATUS_TABLE} (batch_id, job_state, attempt) VALUES (%s, 'succeeded', 1)",+ [batch_id],+ )+ inserted += 1+ finally:+ conn.execute(+ "SELECT pg_advisory_unlock(%s, hashtext(%s))",+ [BACKFILL_ENQUEUE_LOCK_NAMESPACE, run_uuid],+ )+ return inserted+++def retire_backfill_run(conn: psycopg.Connection[Any], *, run_uuid: str) -> None:+ """Terminally fail a backfill run's unapplied chunks (operator replan).++ Failing (not pre-applying) is correct HERE: a replanned run's chunks must+ never execute, and the failed-run exclusion is exactly that. The kind is+ deliberately distinct from a live-replace supersession so the reconciler+ can never mistake a replan for a completed refresh.+ """+ conn.execute(+ f"""+ INSERT INTO sourcebatchduckgresstatus (batch_id, job_state, attempt, error_response)+ SELECT b.id, 'failed', 0, jsonb_build_object('error', %(reason)s, 'kind', %(kind)s)+ FROM {BATCH_TABLE} b+ LEFT JOIN sourcebatchduckgresapply a+ ON a.team_id = b.team_id AND a.schema_id = b.schema_id+ AND a.run_uuid = b.run_uuid AND a.batch_index = b.batch_index+ WHERE b.run_uuid = %(run_uuid)s+ AND b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND a.id IS NULL+ """,+ {"run_uuid": run_uuid, "reason": REASON_RETIRED_BY_REPLAN, "kind": KIND_RETIRED_BY_REPLAN},+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.pynew file mode 100644index 000000000000..21db3995fd31--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/backfill_snapshot.py@@ -0,0 +1,174 @@+"""Delta snapshot resolution and chunk planning for the duckgres backfill.++Pure read-side: no queue or app-DB writes live here. Given a schema (and+optionally a pinned version), produce the chunk plan — groups of the Delta+table's own live parquet files bounded by bytes and file count.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from typing import Any+from urllib.parse import unquote++from django.conf import settings++from products.warehouse_sources.backend.models import ExternalDataSchema++CHUNK_TARGET_BYTES = 1024**3 # ~1 GiB of parquet per chunk statement+MAX_FILES_PER_CHUNK = 512 # bound the read_parquet([...]) literal list+++class BackfillUnsupportedError(Exception):+ """The Delta table cannot be backfilled by this planner (parks NEEDS_RESYNC)."""+++@dataclass(frozen=True)+class BackfillChunk:+ index: int+ paths: list[str]+ byte_size: int+ row_count: int+++@dataclass(frozen=True)+class BackfillSnapshotPlan:+ snapshot_version: int+ chunks: list[BackfillChunk]+ covered_batches: list[tuple[str, int]]+++def delta_table_uri(schema: ExternalDataSchema) -> str:+ return f"{settings.BUCKET_URL}/{schema.folder_path()}/{schema.normalized_name}"+++def _delta_storage_options() -> dict[str, str]:+ """Storage options for metadata-only Delta log reads from the consumer pod.++ Prod: empty — deltalake's object_store resolves the pod's ambient AWS+ credential chain (IRSA/env) itself. Local dev: MinIO endpoint + keys.+ (posthog.ducklake.storage.get_deltalake_storage_options is NOT usable+ here: it requires DuckLake RDS env that consumer pods do not carry.)+ """+ if settings.USE_LOCAL_SETUP:+ return {+ "AWS_ACCESS_KEY_ID": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,+ "AWS_SECRET_ACCESS_KEY": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,+ "AWS_ENDPOINT_URL": settings.OBJECT_STORAGE_ENDPOINT,+ "AWS_ALLOW_HTTP": "true",+ "AWS_REGION": "us-east-1",+ }+ return {}+++def resolve_snapshot_chunks(schema: ExternalDataSchema, version: int | None = None) -> tuple[int, list[BackfillChunk]]:+ plan = resolve_snapshot_plan(schema, version=version)+ return plan.snapshot_version, plan.chunks+++def resolve_snapshot_plan(schema: ExternalDataSchema, version: int | None = None) -> BackfillSnapshotPlan:+ from deltalake import DeltaTable++ uri = delta_table_uri(schema)+ dt = DeltaTable(uri, version=version, storage_options=_delta_storage_options())+ resolved_version = dt.version()++ if _has_deletion_vectors(dt):+ # deltalake 1.4.0 cannot stream DV tables (to_pyarrow_dataset rejects+ # the reader feature), and reading the add files directly would serve+ # deleted rows. Park the schema; a full-refresh resync heals it.+ raise BackfillUnsupportedError(+ "Delta table has the deletionVectors reader feature; backfill requires a full resync"+ )++ adds = dt.get_add_actions(flatten=True)+ paths = adds.column("path").to_pylist()+ sizes = adds.column("size_bytes").to_pylist()+ counts: list[int]+ try:+ counts = [int(c) if c is not None else 0 for c in adds.column("num_records").to_pylist()]+ except KeyError:+ counts = [0] * len(paths)++ files = []+ for p, size, rows in zip(paths, sizes, counts):+ # Add-action paths are percent-encoded relative paths (or, rarely,+ # absolute URIs). Decode so read_parquet sees the real object key.+ decoded = unquote(p)+ full = decoded if decoded.startswith(("s3://", "s3a://")) else f"{uri.rstrip('/')}/{decoded}"+ files.append((full, size or 0, rows or 0))+ return BackfillSnapshotPlan(+ snapshot_version=resolved_version,+ chunks=_group_files_into_chunks(files),+ covered_batches=_committed_batch_keys(dt, snapshot_version=resolved_version),+ )+++def _has_deletion_vectors(dt: Any) -> bool:+ """Conservative: a DV-enabled table parks even if no DV is currently active —+ re-deriving per-file DV state is not worth the risk of serving deleted rows."""+ try:+ protocol = dt.protocol()+ features = list(protocol.reader_features or [])+ return "deletionVectors" in features+ except Exception:+ return True # unknown protocol shape: park, never lie+++def _committed_batch_keys(dt: Any, *, snapshot_version: int) -> list[tuple[str, int]]:+ """Return live v3 batch keys committed at or before the pinned snapshot.++ Delta commits are the only exact boundary for snapshot containment. Queue+ timestamps can race the snapshot read, but a commit with version <= the+ pinned version is necessarily represented in the files this backfill reads.+ """+ keys: list[tuple[str, int]] = []+ for commit in dt.history():+ commit_version = commit.get("version")+ if isinstance(commit_version, int) and commit_version > snapshot_version:+ continue++ metadata = _commit_metadata(commit)+ run_uuid = metadata.get("run_uuid")+ batch_index = metadata.get("batch_index")+ if run_uuid is None or batch_index is None:+ continue+ try:+ keys.append((str(run_uuid), int(batch_index)))+ except (TypeError, ValueError):+ continue+ return keys+++def _commit_metadata(commit: dict[str, Any]) -> dict[str, Any]:+ metadata: dict[str, Any] = dict(commit)+ raw = commit.get("userMetadata")+ if isinstance(raw, str):+ try:+ nested = json.loads(raw)+ except (json.JSONDecodeError, ValueError):+ nested = {}+ elif isinstance(raw, dict):+ nested = raw+ else:+ nested = {}+ metadata.update(nested)+ return metadata+++def _group_files_into_chunks(files: list[tuple[str, int, int]]) -> list[BackfillChunk]:+ chunks: list[BackfillChunk] = []+ cur_paths: list[str] = []+ cur_bytes = 0+ cur_rows = 0+ for path, size, rows in files:+ if cur_paths and (cur_bytes + size > CHUNK_TARGET_BYTES or len(cur_paths) >= MAX_FILES_PER_CHUNK):+ chunks.append(BackfillChunk(len(chunks), cur_paths, cur_bytes, cur_rows))+ cur_paths, cur_bytes, cur_rows = [], 0, 0+ cur_paths.append(path)+ cur_bytes += size+ cur_rows += rows+ if cur_paths:+ chunks.append(BackfillChunk(len(chunks), cur_paths, cur_bytes, cur_rows))+ return chunksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.pynew file mode 100644index 000000000000..1a6c71b8e8ef--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/batch_kind.py@@ -0,0 +1,44 @@+"""Canonical definition of "what kind of batch is this?" for the duckgres sink.++Two kinds exist: LIVE batches produced by the v3 sync pipeline, and synthetic+DUCKGRES_BACKFILL batches enqueued by the backfill planner. The discriminator+travels in batch metadata (the queue schema predates the distinction; a typed+``kind`` column on sourcebatch is the planned follow-up migration). Every+consumer of the distinction — queue SQL, processor dispatch, planner enqueue —+derives it from THIS module so the convention has exactly one definition per+language (one Python predicate, one SQL fragment).+"""++from __future__ import annotations++from typing import Any++BACKFILL_METADATA_KEY = "duckgres_backfill"++# SQL twin of is_backfill_metadata, for queries aliasing sourcebatch as ``b``.+LIVE_BATCH_SQL_PREDICATE = f"(b.metadata->>'{BACKFILL_METADATA_KEY}') IS NULL"+BACKFILL_BATCH_SQL_PREDICATE = f"(b.metadata->>'{BACKFILL_METADATA_KEY}') IS NOT NULL"+++def is_backfill_metadata(metadata: dict[str, Any] | None) -> bool:+ return bool(metadata and metadata.get(BACKFILL_METADATA_KEY))+++def build_backfill_metadata(*, chunk_paths: list[str], chunk_count: int) -> dict[str, Any]:+ """The only shape backfill batch metadata is ever written in."""+ return {+ BACKFILL_METADATA_KEY: True,+ "chunk_paths": chunk_paths,+ "chunk_count": chunk_count,+ }+++def backfill_chunk_paths(metadata: dict[str, Any]) -> list[str]:+ paths = metadata.get("chunk_paths")+ if not isinstance(paths, list) or not paths:+ raise ValueError("backfill batch has no chunk_paths metadata")+ return [str(p) for p in paths]+++def backfill_chunk_count(metadata: dict[str, Any]) -> int:+ return int(metadata.get("chunk_count") or 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 dff4346f1e99..b1906aaa10a1 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@@ -20,6 +20,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipelineProcessBatchFn,_group_by_key,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (+ blocked_schema_ids as compute_blocked_schema_ids,+ run_backfill_planner,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import (duckgres_sink_team_ids,)@@ -54,6 +58,16 @@ SINK_OLDEST_ELIGIBLE_AGE_SECONDS = Gauge("Queue retention permanently drops batches after RETENTION_DAYS — alert well before that.",multiprocess_mode="livemax",)+SINK_BLOCKED_BACKLOG = Gauge(+ "duckgres_sink_blocked_backlog",+ "Delta-succeeded batches held back because their schema is not yet primed (backfill pending/in-flight)",+ 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",+ multiprocess_mode="livemax",+)SINK_SUPERSEDED_BATCHES_TOTAL = Gauge("duckgres_sink_superseded_batches","Batches retired because a newer replace-run made their work obsolete (last sweep)",@@ -71,6 +85,9 @@ class DuckgresBatchConsumerAdapter:self._team_ids: list[int] | None = Noneself._team_ids_fetched_at: float | None = Noneself._last_maintenance_at = 0.0+ # 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 = Noneasync def _enabled_team_ids(self) -> list[int] | None:"""Cached duckgres-enabled team set; keeps the previous set on app-DB errors."""@@ -101,9 +118,24 @@ class DuckgresBatchConsumerAdapter:if superseded:logger.info("duckgres_superseded_obsolete_batches", count=superseded)- backlog, oldest_age = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=team_ids)+ backlog, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(+ conn, team_ids=team_ids, blocked_schema_ids=self._blocked_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)++ try:+ # Backfill planner: bootstrap/plan/reconcile schema priming, then+ # 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)+ except Exception as e:+ # An app-DB blip must not crash the poll loop; keep the previous+ # block list (or keep claiming nothing if we never had one).+ logger.exception("duckgres_backfill_planner_failed")+ capture_exception(e)async def fetch_and_lock(self,@@ -118,11 +150,17 @@ class DuckgresBatchConsumerAdapter:await self._run_maintenance(conn, team_ids)+ if self._blocked_schema_ids is None:+ # Planner has not succeeded yet: claiming live batches now could+ # write partial history for unprimed schemas. Wait for it.+ return []+return await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn,limit=limit,retry_backoff_base_seconds=retry_backoff_base_seconds,team_ids=team_ids,+ blocked_schema_ids=self._blocked_schema_ids,)async def unlock(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 b23022645151..4f75be588b82 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@@ -6,6 +6,9 @@ from typing import Anyimport psycopgfrom psycopg.rows import dict_row+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.batch_kind import (+ LIVE_BATCH_SQL_PREDICATE,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (BATCH_TABLE,PARTITION_PRUNING_INTERVAL,@@ -21,6 +24,35 @@ DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"DUCKGRES_ADVISORY_LOCK_NAMESPACE = 0x44475300 # "DGS\0" in hex+# Structured classification key written into duckgres status error_response by+# every terminal-retire writer. Consumers (the backfill reconciler) dispatch on+# this, not on error-message prose.+RETIRE_KIND_SUPERSEDED_BY_REPLACE = "superseded_by_replace"++# A LIVE batch held back because its schema's history is not yet primed.+# Replace-head runs bypass the block: they rebuild the table from scratch, so+# applying them to an unprimed schema is always safe — and they are the+# healing path for schemas parked in NEEDS_RESYNC. Single definition, used by+# both the eligibility gate and the backlog split. Expects %(blocked_schema_ids)s.+BLOCKED_LIVE_BATCH_CONDITION = f"""(+ %(blocked_schema_ids)s::varchar[] IS NOT NULL+ AND b.schema_id = ANY(%(blocked_schema_ids)s)+ AND {LIVE_BATCH_SQL_PREDICATE}+ AND NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} bh+ WHERE bh.run_uuid = b.run_uuid+ AND bh.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND bh.batch_index = 0+ AND bh.is_final_batch = false+ AND bh.is_resume = false+ AND (+ bh.sync_type = 'full_refresh'+ OR (bh.sync_type = 'incremental' AND bh.is_first_ever_sync)+ )+ )+ )"""+# Shared CTE prelude for eligibility queries (note the trailing comma — callers# append their own CTEs/SELECT). Expects a %(team_ids)s bigint[] parameter# (NULL = no team filter).@@ -54,7 +86,8 @@ ELIGIBILITY_CTES = f"""run_starts AS MATERIALIZED (AND dgs3.job_state = 'failed'),incomplete_runs AS MATERIALIZED (- SELECT old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at+ SELECT old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at,+ bool_or((old.metadata->>'duckgres_backfill') IS NOT NULL) AS is_backfill_runFROM {BATCH_TABLE} oldJOIN {DELTA_STATUS_VIEW} ods ON old.id = ods.batch_idJOIN run_starts rs_ir ON rs_ir.run_uuid = old.run_uuid@@ -81,6 +114,7 @@ class DuckgresBatchQueue:limit: int = 50,retry_backoff_base_seconds: int = 0,team_ids: list[int] | None = None,+ blocked_schema_ids: list[str] | None = None,) -> list[PendingBatch]:"""Fetch Duckgres-eligible batches whose Delta load has succeeded.@@ -94,6 +128,10 @@ class DuckgresBatchQueue:filter, for tests/dev). The sink must never claim batches for orgs withouta Duckgres deployment — they would burn retries and fail runs for nothing.+ ``blocked_schema_ids`` excludes LIVE batches for schemas whose history is+ not yet primed into duckgres (backfill pending/in-flight) — the schema's+ own backfill-run batches (metadata.duckgres_backfill) pass through.+Cross-run head-of-line: a batch is ineligible while an older run (by runstart time) of the same (team_id, schema_id) still has unapplied,non-failed data batches. Without this, a newer run's batch-0@@ -116,6 +154,7 @@ class DuckgresBatchQueue:WHEREb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ AND NOT {BLOCKED_LIVE_BATCH_CONDITION}AND ds.job_state = 'succeeded'AND (dgs.batch_id IS NULL@@ -164,15 +203,28 @@ class DuckgresBatchQueue:)AND a.id IS NULL)- AND NOT EXISTS (+ AND (-- Cross-run head-of-line: an older non-failed run of this- -- schema still has unapplied data batches.- SELECT 1- FROM incomplete_runs ir- WHERE ir.team_id = b.team_id- AND ir.schema_id = b.schema_id- AND ir.run_uuid <> b.run_uuid- AND (ir.started_at, ir.run_uuid) < (rs_b.started_at, b.run_uuid)+ -- schema still has unapplied data batches. Applies to LIVE+ -- batches only: a backfill run is ordered manually —+ -- batches provably contained in its Delta snapshot are+ -- pre-applied at plan time, and anything not contained must+ -- apply AFTER the swap, so it must not gate the chunks. Live+ -- batches still queue behind the backfill run itself via+ -- this same check.+ NOT EXISTS (+ SELECT 1+ FROM incomplete_runs ir+ WHERE ir.team_id = b.team_id+ AND ir.schema_id = b.schema_id+ AND ir.run_uuid <> b.run_uuid+ AND (ir.started_at, ir.run_uuid) < (rs_b.started_at, b.run_uuid)+ -- A backfill chunk ignores older LIVE runs (see above)+ -- but still orders behind an older backfill run, so+ -- two generations can never interleave on the+ -- staging table.+ AND ({LIVE_BATCH_SQL_PREDICATE} OR ir.is_backfill_run)+ ))ORDER BY b.created_at ASC, b.batch_index ASC, b.is_final_batch ASCLIMIT %(limit)s@@ -185,7 +237,12 @@ class DuckgresBatchQueue:)ORDER BY c.created_at ASC, c.batch_index ASC, c.is_final_batch ASC""",- {"limit": limit, "backoff": retry_backoff_base_seconds, "team_ids": team_ids},+ {+ "limit": limit,+ "backoff": retry_backoff_base_seconds,+ "team_ids": team_ids,+ "blocked_schema_ids": blocked_schema_ids,+ },)rows = await cur.fetchall()return [PendingBatch(**row) for row in rows]@@ -262,7 +319,7 @@ class DuckgresBatchQueue:v.batch_id,'failed',0,- jsonb_build_object('error', 'superseded by newer replace run ' || v.superseded_by)+ jsonb_build_object('error', 'superseded by newer replace run ' || v.superseded_by, 'kind', '{RETIRE_KIND_SUPERSEDED_BY_REPLACE}')FROM victims v""",{"team_ids": team_ids},@@ -274,19 +331,24 @@ class DuckgresBatchQueue:conn: psycopg.AsyncConnection[Any],*,team_ids: list[int] | None = None,- ) -> tuple[int, float | None]:- """(count, oldest age seconds) of delta-succeeded, unapplied, non-failed data batches.+ blocked_schema_ids: list[str] | None = None,+ ) -> tuple[int, float | None, int, float | None]:+ """(eligible_count, eligible_oldest_age, blocked_count, blocked_oldest_age).- This is the sink's lag signal: both silent-loss modes (7-day queue- retention, permanently failed runs) are time-bounded, so alerting needs- the age of the oldest batch the sink still owes.+ Eligible = delta-succeeded, unapplied, non-failed data batches the sink+ can claim now — the lag/alert signal (7-day retention and permanent run+ failure 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."""async with conn.cursor() as cur:await cur.execute(f"""WITH {ELIGIBILITY_CTES}backlog AS (- SELECT b.created_at+ SELECT+ b.created_at,+ {BLOCKED_LIVE_BATCH_CONDITION} AS is_blockedFROM {BATCH_TABLE} bJOIN {DELTA_STATUS_VIEW} ds ON b.id = ds.batch_idLEFT JOIN {DUCKGRES_APPLY_TABLE} a@@ -301,15 +363,23 @@ class DuckgresBatchQueue:AND a.id IS NULLAND b.run_uuid NOT IN (SELECT run_uuid FROM failed_runs))- SELECT count(*), EXTRACT(EPOCH FROM now() - min(created_at))+ SELECT+ count(*) 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))FROM backlog""",- {"team_ids": team_ids},+ {"team_ids": team_ids, "blocked_schema_ids": blocked_schema_ids},)row = await cur.fetchone()- count = int(row[0]) if row else 0- oldest_age = float(row[1]) if row and row[1] is not None else None- return count, oldest_age++ def _age(v: Any) -> float | None:+ return float(v) if v is not None else None++ if row is None:+ return 0, None, 0, None+ return int(row[0]), _age(row[1]), int(row[2]), _age(row[3])@staticmethodasync def update_status(diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pyindex eaf317028dfb..566b56dfba46 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py@@ -16,6 +16,7 @@ from posthog.models import Teamfrom products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchemafrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import batch_kindfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (PendingBatch,)@@ -54,13 +55,22 @@ def process_batch(batch: PendingBatch) -> None:# reads below reconnect instead of failing every attempt after a DB bounce.close_old_connections()- job = ExternalDataJob.objects.select_related("schema", "schema__source").get(- id=batch.job_id,- team_id=batch.team_id,- )- schema = job.schema- if schema is None:- raise ValueError(f"ExternalDataJob {batch.job_id} has no schema")+ schema: ExternalDataSchema+ if _is_backfill_batch(batch):+ # Synthetic backfill batches carry a sentinel job_id; resolve the schema+ # directly instead of via ExternalDataJob.+ schema = ExternalDataSchema.objects.select_related("source").get(+ id=batch.schema_id,+ team_id=batch.team_id,+ )+ else:+ job = ExternalDataJob.objects.select_related("schema", "schema__source").get(+ id=batch.job_id,+ team_id=batch.team_id,+ )+ if job.schema is None:+ raise ValueError(f"ExternalDataJob {batch.job_id} has no schema")+ schema = job.schemawith _connect_to_duckgres(batch.team_id) as conn:# The sink only reads parquet over S3; httpfs is bundled in the duckgres@@ -70,7 +80,10 @@ def process_batch(batch: PendingBatch) -> None:setup_duckgres_session(conn, extensions=("httpfs",))_create_extract_read_secret(conn)try:- _process_batch(conn, batch, schema)+ if _is_backfill_batch(batch):+ _process_backfill_batch(conn, batch, schema)+ else:+ _process_batch(conn, batch, schema)except DuckgresBatchAlreadyAppliedError:# A concurrent processor (lost advisory-lock session + recovery sweep)# won the marker insert; its committed write is the canonical one and@@ -156,6 +169,37 @@ def _sql_str(value: str) -> str:return "'" + str(value).replace("'", "''") + "'"+def _is_backfill_batch(batch: PendingBatch) -> bool:+ return batch_kind.is_backfill_metadata(batch.metadata)+++def _backfill_chunk_paths(batch: PendingBatch) -> list[str]:+ try:+ return batch_kind.backfill_chunk_paths(batch.metadata)+ except ValueError as e:+ # Falling back to s3_path would silently apply only the chunk's first+ # file; a malformed synthetic row must fail loudly instead.+ raise ValueError(f"backfill batch {batch.id}: {e}") from e+++def _read_parquet_expr(paths: list[str], *, union_by_name: bool = False) -> sql.Composable:+ """read_parquet([...]) with inlined literals — list parameters do not bind+ reliably over the duckgres extended protocol. union_by_name aligns+ schema-evolved files within one chunk by column name (backfill chunks span+ months of Delta writes; positional unification fails on added columns)."""+ opts = sql.SQL(", union_by_name=true") if union_by_name else sql.SQL("")+ return sql.SQL("read_parquet([{}]{})").format(+ sql.SQL(", ").join(sql.Literal(p) for p in paths),+ opts,+ )+++def _backfill_table_name(live_table: str, schema_id: str) -> str:+ # Suffix with a schema-id fragment: pure prefix truncation could collide+ # for two schemas sharing a long name prefix in the same team schema.+ return f"{live_table[:42]}__bf_{schema_id.replace('-', '')[:8]}"++def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: ExternalDataSchema) -> None:duckgres_schema = _duckgres_schema_name(batch.team_id)duckgres_table = _duckgres_table_name(schema)@@ -180,7 +224,7 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: E)return- parquet_schema = _read_parquet_schema(conn, batch.s3_path)+ parquet_schema = _read_parquet_schema(conn, [batch.s3_path])columns = [column.name for column in parquet_schema]operation = _plan_batch_operation(conn,@@ -206,13 +250,104 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: Eoperation,duckgres_schema=duckgres_schema,duckgres_table=duckgres_table,- s3_path=batch.s3_path,+ paths=[batch.s3_path],columns=columns,)_mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)return+def _process_backfill_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: ExternalDataSchema) -> None:+ """Apply one backfill chunk into <table>__backfill; the last chunk swaps it live.++ See BACKFILL_SPEC.md. The swap (DROP live + RENAME) shares the last chunk's+ transaction together with the apply-marker arbiter, so it is atomic and+ exactly-once even with a concurrent processor.+ """+ duckgres_schema = _duckgres_schema_name(batch.team_id)+ live_table = _duckgres_table_name(schema)+ backfill_table = _backfill_table_name(live_table, batch.schema_id)+ chunk_count = batch_kind.backfill_chunk_count(batch.metadata)+ is_last = chunk_count > 0 and batch.batch_index == chunk_count - 1++ conn.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(duckgres_schema)))+ _ensure_duckgres_apply_table(conn, duckgres_schema)++ if _has_duckgres_batch_applied(conn, duckgres_schema, batch=batch):+ logger.info(+ "duckgres_backfill_chunk_already_applied",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ )+ if is_last:+ # Crash between the swap's commit and the state flip lands here on+ # retry: the swap is proven (the marker shared its transaction),+ # only the app-DB flip is missing. Idempotent via CAS.+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (+ mark_primed,+ )++ mark_primed(batch.schema_id, chunks_applied=chunk_count)+ return++ chunk_paths = _backfill_chunk_paths(batch)+ parquet_schema = _read_parquet_schema(conn, chunk_paths, union_by_name=True)+ columns = [column.name for column in parquet_schema]++ with conn.transaction():+ if batch.batch_index == 0:+ # CREATE OR REPLACE makes a re-planned backfill self-cleaning.+ conn.execute(+ sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(backfill_table),+ _read_parquet_expr(chunk_paths, union_by_name=True),+ )+ )+ else:+ _ensure_target_columns(conn, duckgres_schema, backfill_table, parquet_schema)+ _insert_batch(conn, duckgres_schema, backfill_table, chunk_paths, columns, union_by_name=True)++ if is_last:+ logger.info(+ "duckgres_backfill_swapping",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ table=live_table,+ chunk_count=chunk_count,+ )+ conn.execute(+ sql.SQL("DROP TABLE IF EXISTS {}.{}").format(+ sql.Identifier(duckgres_schema), sql.Identifier(live_table)+ )+ )+ conn.execute(+ sql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(backfill_table),+ sql.Identifier(live_table),+ )+ )++ _mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)++ if is_last:+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (+ mark_primed,+ )++ mark_primed(batch.schema_id, chunks_applied=chunk_count)+ logger.info(+ "duckgres_backfill_swapped",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ table=live_table,+ )++def _duckgres_schema_name(team_id: int) -> str:# Resolves to posthog_data_imports_<table_suffix> when the team has set one# (DuckgresServerTeam.table_suffix — the same suffix that names its@@ -283,25 +418,25 @@ def _table_exists(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_return cursor.fetchone() is not None-def _replace_table(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, s3_path: str) -> None:+def _replace_table(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, paths: list[str]) -> None:conn.execute(- sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM read_parquet(%s)").format(+ sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(sql.Identifier(duckgres_schema),sql.Identifier(duckgres_table),- ),- [s3_path],+ _read_parquet_expr(paths),+ ))def _create_table_from_parquet(- conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, s3_path: str+ conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, paths: list[str]) -> None:conn.execute(- sql.SQL("CREATE TABLE {}.{} AS SELECT * FROM read_parquet(%s)").format(+ sql.SQL("CREATE TABLE {}.{} AS SELECT * FROM {}").format(sql.Identifier(duckgres_schema),sql.Identifier(duckgres_table),- ),- [s3_path],+ _read_parquet_expr(paths),+ ))@@ -386,12 +521,16 @@ def _prune_duckgres_apply_markers(conn: psycopg.Connection[Any], duckgres_schemalogger.exception("duckgres_apply_marker_prune_failed", duckgres_schema=duckgres_schema)-def _read_parquet_columns(conn: psycopg.Connection[Any], s3_path: str) -> list[str]:- return [column.name for column in _read_parquet_schema(conn, s3_path)]+def _read_parquet_columns(conn: psycopg.Connection[Any], paths: list[str]) -> list[str]:+ return [column.name for column in _read_parquet_schema(conn, paths)]-def _read_parquet_schema(conn: psycopg.Connection[Any], s3_path: str) -> list[DuckgresColumn]:- cursor = conn.execute("DESCRIBE SELECT * FROM read_parquet(%s) LIMIT 0", [s3_path])+def _read_parquet_schema(+ conn: psycopg.Connection[Any], paths: list[str], *, union_by_name: bool = False+) -> list[DuckgresColumn]:+ cursor = conn.execute(+ sql.SQL("DESCRIBE SELECT * FROM {} LIMIT 0").format(_read_parquet_expr(paths, union_by_name=union_by_name))+ )rows = cursor.fetchall()if not rows:raise ValueError("Duckgres could not read parquet column metadata")@@ -434,22 +573,22 @@ def _apply_batch_operation(*,duckgres_schema: str,duckgres_table: str,- s3_path: str,+ paths: list[str],columns: list[str],) -> None:if operation.kind == "replace":- _replace_table(conn, duckgres_schema, duckgres_table, s3_path)+ _replace_table(conn, duckgres_schema, duckgres_table, paths)returnif operation.kind == "create":- _create_table_from_parquet(conn, duckgres_schema, duckgres_table, s3_path)+ _create_table_from_parquet(conn, duckgres_schema, duckgres_table, paths)returnif operation.kind == "insert":- _insert_batch(conn, duckgres_schema, duckgres_table, s3_path, columns)+ _insert_batch(conn, duckgres_schema, duckgres_table, paths, columns)returnif operation.kind == "merge":if operation.primary_keys is None:raise ValueError("Duckgres merge operation requires primary keys")- _merge_batch(conn, duckgres_schema, duckgres_table, s3_path, columns, operation.primary_keys)+ _merge_batch(conn, duckgres_schema, duckgres_table, paths, columns, operation.primary_keys)returnraise ValueError(f"Unsupported Duckgres apply operation: {operation.kind}")@@ -458,19 +597,21 @@ def _insert_batch(conn: psycopg.Connection[Any],duckgres_schema: str,duckgres_table: str,- s3_path: str,+ paths: list[str],columns: list[str],+ *,+ union_by_name: bool = False,) -> None:insert_columns = sql.SQL(", ").join(sql.Identifier(column) for column in columns)select_columns = sql.SQL(", ").join(sql.SQL("source.{}").format(sql.Identifier(column)) for column in columns)conn.execute(- sql.SQL("INSERT INTO {}.{} ({}) SELECT {} FROM read_parquet(%s) AS source").format(+ sql.SQL("INSERT INTO {}.{} ({}) SELECT {} FROM {} AS source").format(sql.Identifier(duckgres_schema),sql.Identifier(duckgres_table),insert_columns,select_columns,- ),- [s3_path],+ _read_parquet_expr(paths, union_by_name=union_by_name),+ ))@@ -478,7 +619,7 @@ def _merge_batch(conn: psycopg.Connection[Any],duckgres_schema: str,duckgres_table: str,- s3_path: str,+ paths: list[str],columns: list[str],primary_keys: list[str],) -> None:@@ -505,7 +646,7 @@ def _merge_batch(query = sql.SQL("""MERGE INTO {}.{} AS target- USING read_parquet(%s) AS source+ USING {} AS sourceON {}{}WHEN NOT MATCHED THEN INSERT ({}) VALUES ({})@@ -513,12 +654,13 @@ def _merge_batch().format(sql.Identifier(duckgres_schema),sql.Identifier(duckgres_table),+ _read_parquet_expr(paths),on_clause,matched_clause,insert_columns,insert_values,)- conn.execute(query, [s3_path])+ conn.execute(query)def _primary_keys(batch: PendingBatch) -> list[str]: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.pynew file mode 100644index 000000000000..d7dd10b506f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_backfill.py@@ -0,0 +1,69 @@+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_queue import (+ backfill_run_uuid,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill_snapshot import (+ CHUNK_TARGET_BYTES,+ BackfillChunk,+ _committed_batch_keys,+ _group_files_into_chunks,+)+++class TestChunkGrouping:+ def test_groups_small_files_up_to_target(self):+ files = [(f"s3://b/f{i}.parquet", CHUNK_TARGET_BYTES // 4, 10) for i in range(10)]++ chunks = _group_files_into_chunks(files)++ assert [len(c.paths) for c in chunks] == [4, 4, 2]+ assert [c.index for c in chunks] == [0, 1, 2]+ assert sum(c.row_count for c in chunks) == 100++ def test_oversized_file_gets_its_own_chunk(self):+ files = [+ ("s3://b/small.parquet", 100, 1),+ ("s3://b/huge.parquet", CHUNK_TARGET_BYTES * 3, 1000),+ ("s3://b/small2.parquet", 100, 1),+ ]++ chunks = _group_files_into_chunks(files)++ # huge file closes the first chunk and lands alone; trailing small file follows+ assert len(chunks) == 3+ assert chunks[1].paths == ["s3://b/huge.parquet"]++ def test_empty_input(self):+ assert _group_files_into_chunks([]) == []+++def test_backfill_run_uuid_is_unique_per_planning_attempt():+ # The generation nonce is load-bearing: a replan at an UNADVANCED Delta+ # version must still produce a fresh, claimable run (the old run's batches+ # are terminally failed and would otherwise be reused verbatim).+ a = backfill_run_uuid("abc", 7)+ b = backfill_run_uuid("abc", 7)+ assert a != b+ assert a.startswith("duckgres-backfill-abc-v7-g")+ assert b.startswith("duckgres-backfill-abc-v7-g")+++def test_chunk_dataclass_shape():+ c = BackfillChunk(0, ["s3://b/f"], 1, 2)+ assert (c.index, c.byte_size, c.row_count) == (0, 1, 2)+++def test_committed_batch_keys_filters_to_snapshot_version():+ class FakeDeltaTable:+ def history(self):+ return [+ {"version": 12, "run_uuid": "after-snapshot", "batch_index": "0"},+ {"version": 11, "run_uuid": "flat-layout", "batch_index": "2"},+ {"version": 10, "userMetadata": '{"run_uuid": "nested-layout", "batch_index": "3"}'},+ {"version": 9, "operation": "CREATE TABLE"},+ {"version": 8, "run_uuid": "bad-batch-index", "batch_index": "nan"},+ ]++ assert _committed_batch_keys(FakeDeltaTable(), snapshot_version=11) == [+ ("flat-layout", 2),+ ("nested-layout", 3),+ ]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 4b7fed58cb9a..69eb9e4b120a 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@@ -212,15 +212,56 @@ 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),+ return_value=(0, None, 0, None),) as mock_backlog,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",+ ) as mock_planner,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.compute_blocked_schema_ids",+ return_value=["blocked-schema"],+ ),):await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=30)assert mock_fetch.call_args[1]["team_ids"] == [1, 2]assert mock_fetch.call_args[1]["retry_backoff_base_seconds"] == 30+ assert mock_fetch.call_args[1]["blocked_schema_ids"] == ["blocked-schema"]mock_supersede.assert_called_once()mock_backlog.assert_called_once()+ mock_planner.assert_called_once_with([1, 2])++ @pytest.mark.asyncio+ async def test_fetch_claims_nothing_until_planner_succeeds(self):+ adapter = DuckgresBatchConsumerAdapter()+ adapter._team_ids = [1]+ adapter._team_ids_fetched_at = time.monotonic()+ conn = _make_healthy_conn()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",+ new_callable=AsyncMock,+ ) as mock_fetch,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",+ new_callable=AsyncMock,+ return_value=0,+ ),+ 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),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.run_backfill_planner",+ side_effect=RuntimeError("app DB down"),+ ),+ ):+ batches = await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=0)++ assert batches == []+ mock_fetch.assert_not_called()class TestStuckBatchWatchdog: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 5dd37acec09e..cd2aee6ba2c4 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@@ -352,14 +352,183 @@ class TestDuckgresTeamFilterAndBacklog:@pytest.mark.asyncioasync def test_backlog_stats(self, conn):- batch_id = await _insert_batch(conn)+ 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 = await DuckgresBatchQueue.get_backlog_stats(conn)- assert count == 1+ count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(conn)+ assert (count, blocked) == (1, 0)assert oldest_age is not None and oldest_age >= 0+ assert 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(+ conn, blocked_schema_ids=["schema-1"]+ )+ assert (count, blocked) == (0, 1)+ assert oldest_age is None and blocked_age is not Noneawait _mark_applied_raw(conn, batch_id=batch_id, run_uuid="run-1", batch_index=0)- count, oldest_age = await DuckgresBatchQueue.get_backlog_stats(conn)- assert count == 0- assert oldest_age is None+ count, oldest_age, blocked, blocked_age = await DuckgresBatchQueue.get_backlog_stats(conn)+ assert (count, blocked) == (0, 0)+ assert oldest_age is None and blocked_age is None++[email protected]_db(transaction=True)+class TestBackfillGating:+ @pytest.mark.asyncio+ async def test_blocked_schema_live_batches_are_excluded(self, conn):+ batch_id = await _insert_batch(conn, sync_type="incremental")+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"]) == []+ assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["other"])) == 1++ @pytest.mark.asyncio+ async def test_backfill_batches_pass_the_block(self, conn):+ batch_id = await _insert_batch(+ conn,+ run_uuid="duckgres-backfill-schema-1-v7",+ job_id="duckgres-backfill",+ is_resume=True,+ metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},+ )+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])++ assert [b.run_uuid for b in batches] == ["duckgres-backfill-schema-1-v7"]++ @pytest.mark.asyncio+ async def test_backfill_run_never_plans_as_replace_head(self, conn):+ # is_resume=True keeps the synthetic full_refresh run out of supersede's+ # replace-head set: a backfill must never retire other runs.+ batch_id = await _insert_batch(+ conn,+ run_uuid="duckgres-backfill-schema-1-v7",+ job_id="duckgres-backfill",+ is_resume=True,+ metadata={"duckgres_backfill": True},+ )+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ old = await _insert_batch(conn, run_uuid="run-0", sync_type="incremental")+ await BatchQueue.update_status(conn, batch_id=old, job_state="succeeded", attempt=1)++ assert await DuckgresBatchQueue.supersede_replaced_runs(conn) == 0++[email protected]_db(transaction=True)+class TestBackfillQueueContracts:+ @pytest.mark.asyncio+ async def test_pre_succeeded_synthetic_rows_invisible_to_delta_fetch(self, conn):+ """The load-bearing trick: backfill rows must never be claimed by the+ Delta consumer (it would load them into the Delta table) while being+ immediately eligible for the duckgres fetch."""+ batch_id = await _insert_batch(+ conn,+ run_uuid="duckgres-backfill-schema-1-v1-gdeadbeef",+ job_id="duckgres-backfill",+ is_resume=True,+ metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},+ )+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ assert await BatchQueue.get_unprocessed_and_lock(conn) == []++ duck = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [str(b.id) for b in duck] == [batch_id]++ @pytest.mark.asyncio+ async def test_backfill_chunks_ignore_older_live_runs(self, conn):+ """The cross-run gate exempts backfill chunks from waiting on live+ runs: pre-snapshot runs are retired separately, and post-snapshot+ runs must apply AFTER the swap — neither may deadlock the backfill."""+ live = await _insert_batch(conn, run_uuid="run-old", sync_type="incremental")+ await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)++ chunk = await _insert_batch(+ conn,+ run_uuid="duckgres-backfill-schema-1-v1-gcafe0000",+ job_id="duckgres-backfill",+ is_resume=True,+ metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},+ )+ await BatchQueue.update_status(conn, batch_id=chunk, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ assert [str(b.id) for b in batches] == [chunk]++ @pytest.mark.asyncio+ async def test_live_batches_still_queue_behind_backfill_run(self, conn):+ chunk = await _insert_batch(+ conn,+ run_uuid="duckgres-backfill-schema-1-v1-gcafe0000",+ job_id="duckgres-backfill",+ is_resume=True,+ metadata={"duckgres_backfill": True, "chunk_paths": ["s3://b/c0.parquet"], "chunk_count": 1},+ )+ await BatchQueue.update_status(conn, batch_id=chunk, job_state="succeeded", attempt=1)++ live = await _insert_batch(conn, run_uuid="run-new")+ await BatchQueue.update_status(conn, batch_id=live, job_state="succeeded", attempt=1)++ # Schema primed (not blocked) but the backfill run is older and+ # incomplete: the live batch must wait.+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [str(b.id) for b in batches] == [chunk]++ @pytest.mark.asyncio+ async def test_preapply_covered_batches_uses_snapshot_commit_keys(self, conn, _db_url):+ """Batches committed into the pinned Delta snapshot get pre-applied+ regardless of queue timing; siblings absent from the snapshot key set+ survive, stay eligible, and their run is never poisoned."""+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres import (+ backfill_queue,+ )++ covered_a = await _insert_batch(conn, run_uuid="run-straddling", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=covered_a, job_state="succeeded", attempt=1)+ late_b = await _insert_batch(conn, run_uuid="run-straddling", batch_index=1)+ await BatchQueue.update_status(conn, batch_id=late_b, job_state="succeeded", attempt=1)++ with psycopg.Connection.connect(_db_url, autocommit=True) as sync_conn:+ preapplied = backfill_queue.preapply_covered_batches(+ sync_conn,+ team_id=1,+ schema_id="schema-1",+ covered_batches=[("run-straddling", 0)],+ reason="covered v1",+ )+ preapplied_again = backfill_queue.preapply_covered_batches(+ sync_conn,+ team_id=1,+ schema_id="schema-1",+ covered_batches=[("run-straddling", 0)],+ reason="covered v1",+ )++ assert preapplied == 1 # covered_a only+ assert preapplied_again == 0 # idempotent; late_b is absent from the snapshot key set++ # The straddling sibling is NOT lost: its head-of-line prev is satisfied+ # by the pre-apply marker, the run is not failed, and it remains the+ # schema's claimable work (post-swap it applies as a live batch).+ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [str(b.id) for b in batches] == [late_b]++ @pytest.mark.asyncio+ async def test_replace_head_runs_bypass_the_blocked_gate(self, conn):+ """A full-refresh replace run rebuilds the table from scratch, so it is+ safe (and required — it is the NEEDS_RESYNC healing path) even while+ the schema is not primed. Non-head live runs stay blocked."""+ plain = await _insert_batch(conn, run_uuid="run-plain", sync_type="incremental")+ await BatchQueue.update_status(conn, batch_id=plain, job_state="succeeded", attempt=1)++ head = await _insert_batch(conn, run_uuid="run-refresh", sync_type="full_refresh", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=head, job_state="succeeded", attempt=1)++ # Retire the plain run first so the cross-run gate isn't what hides it.+ await DuckgresBatchQueue.update_status(conn, batch_id=plain, job_state="failed", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, blocked_schema_ids=["schema-1"])+ assert [str(b.id) for b in batches] == [head]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.pyindex f7673df38d43..0eb6ef5c5c2e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py@@ -8,6 +8,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_ensure_duckgres_apply_table,_insert_batch,_mark_duckgres_batch_applied,+ _process_backfill_batch,_process_batch,)from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (@@ -354,11 +355,11 @@ def test_missing_table_is_created_from_parquet() -> None:def test_insert_batch_uses_explicit_column_projection() -> None:conn = _make_conn()- _insert_batch(conn, "warehouse", "customers", "s3://bucket/path", ["id", "email"])+ _insert_batch(conn, "warehouse", "customers", ["s3://bucket/path"], ["id", "email"])query = conn.execute.call_args.args[0]assert "SELECT *" not in repr(query)- assert conn.execute.call_args.args[1] == ["s3://bucket/path"]+ assert "s3://bucket/path" in repr(query) # path is inlined as a literal nowdef test_already_applied_batch_skips_duckgres_mutation() -> None:@@ -449,3 +450,108 @@ def test_duckgres_apply_marker_is_scoped_by_schema_id() -> None:2,"00000000-0000-0000-0000-000000000001",]+++def _make_backfill_batch(**overrides: Any) -> PendingBatch:+ md = {+ "duckgres_backfill": True,+ "chunk_paths": ["s3://bucket/chunk_0.parquet"],+ "chunk_count": 3,+ }+ md.update(overrides.pop("metadata", {}))+ return _make_batch(+ job_id="duckgres-backfill",+ run_uuid="duckgres-backfill-schema-1-v7",+ sync_type="full_refresh",+ is_resume=True,+ metadata=md,+ **overrides,+ )+++class TestBackfillProcessing:+ def test_first_chunk_creates_backfill_table_without_swap(self) -> None:+ conn = _make_conn()+ batch = _make_backfill_batch(batch_index=0)++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied"+ ) as mark,+ ):+ _process_backfill_batch(conn, batch, _make_schema())++ executed = " ".join(repr(c.args[0]) for c in conn.execute.call_args_list)+ assert "stripe_customers__bf_schema1" in executed+ assert "CREATE OR REPLACE TABLE" in executed+ assert "RENAME TO" not in executed+ mark.assert_called_once()++ def test_last_chunk_swaps_and_marks_primed(self) -> None:+ conn = _make_conn()+ batch = _make_backfill_batch(batch_index=2, metadata={"chunk_paths": ["s3://bucket/chunk_2.parquet"]})++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"+ ) as insert,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill.mark_primed"+ ) as primed,+ ):+ _process_backfill_batch(conn, batch, _make_schema())++ executed = " ".join(repr(c.args[0]) for c in conn.execute.call_args_list)+ assert "DROP TABLE IF EXISTS" in executed+ assert "Identifier('stripe_customers')" in executed+ assert "RENAME TO" in executed+ insert.assert_called_once()+ primed.assert_called_once_with("schema-1", chunks_applied=3)++ def test_already_applied_chunk_is_a_noop(self) -> None:+ conn = _make_conn()+ batch = _make_backfill_batch(batch_index=1)++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=True,+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch"+ ) as insert,+ ):+ _process_backfill_batch(conn, batch, _make_schema())++ insert.assert_not_called()