: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): add duckgres v3 consumer (#59251)
Eric Duong5e94571568cb
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 421525ea398d..85124478cc60 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -323,6 +323,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"SessionRecordingExternalReference", # via SessionRecording"SessionRecordingPlaylistItem", # via Playlist"SharePassword", # via SharingConfiguration+ "SourceBatchDuckgresStatus", # via SourceBatch"SourceBatchStatus", # via SourceBatch"StreamlitAppSandbox", # via StreamlitApp"TaggedItem", # via Tag/Dashboard/Insightdiff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 8ded4a8fe200..46c6dc2e2cc1 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -905,6 +905,36 @@ jobs:"timestamp": "${{ github.event.head_commit.timestamp }}"}+ - name: Check for changes that affect warehouse-sources-duckgres-load+ id: check_changes_warehouse_sources_duckgres_load+ run: |+ if git diff --name-only HEAD^ HEAD | grep -qE '^posthog/temporal/data_imports/pipelines/pipeline_v3/|^posthog/temporal/data_imports/pipelines/pipeline/|^posthog/management/commands/run_warehouse_sources_duckgres_load\.py$|^posthog/warehouse/|^posthog/ducklake/|^products/data_warehouse/backend/|^products/warehouse_sources/backend/|^products/warehouse_sources_queue/backend/|^pyproject\.toml$|^Dockerfile$|^posthog/clickhouse/migrations/'; then+ echo "changed=true" >> $GITHUB_OUTPUT+ else+ echo "changed=false" >> $GITHUB_OUTPUT+ fi++ - name: Trigger Warehouse Sources Duckgres Load Cloud deployment+ if: steps.check_changes_warehouse_sources_duckgres_load.outputs.changed == 'true'+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1+ with:+ token: ${{ steps.deployer.outputs.token }}+ repository: PostHog/charts+ event-type: commit_state_update+ client-payload: |+ {+ "values": {+ "image": {+ "sha": "${{ github.sha }}@${{ steps.build_retry.outputs.digest || steps.build.outputs.digest }}"+ }+ },+ "release": "warehouse-sources-duckgres-load",+ "commit": ${{ toJson(github.event.head_commit) }},+ "repository": ${{ toJson(github.repository) }},+ "labels": ${{ steps.labels.outputs.labels }},+ "timestamp": "${{ github.event.head_commit.timestamp }}"+ }+- name: Trigger Data Warehouse CDP Producer Temporal Worker Cloud deploymentif: steps.check_changes_data_warehouse_temporal_worker.outputs.changed == 'true'uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 843bb96bce9e..5c3b0f5963f8 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -225,6 +225,7 @@ rules:|SingleSessionSummary|SlackThreadTaskMapping|SourceBatch+ |SourceBatchDuckgresApply|StreamlitApp|Subscription|SubscriptionDelivery@@ -481,6 +482,7 @@ rules:|SingleSessionSummary|SlackThreadTaskMapping|SourceBatch+ |SourceBatchDuckgresApply|StreamlitApp|Subscription|SubscriptionDeliverydiff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 9a097043828b..3a311bb83828 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -645,6 +645,17 @@ procs:tech: Python# no capability - manual start+ warehouse-sources-duckgres-load:+ shell: |-+ bin/wait-for-docker && \+ python manage.py run_warehouse_sources_duckgres_load --health-port 8092+ autostart: false+ ready_pattern: 'duckgres_batch_consumer_started'+ groups:+ layer: Tools+ tech: Python+ # no capability - manual start+group_order:layer: [Application, Processing, Ingestion pipeline, Infrastructure, Product services, Tools]tech: [Python, Frontend, Node, Rust, Docker, Migrations, Other]diff --git a/posthog/ducklake/storage.py b/posthog/ducklake/storage.pyindex afb80d885b7f..7361532e4ad4 100644--- a/posthog/ducklake/storage.py+++ b/posthog/ducklake/storage.py@@ -654,9 +654,17 @@ def cleanup_staged_files(s3.delete_objects(Bucket=bucket, Delete={"Objects": objects}) # type: ignore[typeddict-item]-def setup_duckgres_session(conn: psycopg.Connection) -> None:- """Install and load required extensions on a duckgres connection."""- for ext in ("ducklake", "httpfs", "delta"):+def setup_duckgres_session(+ conn: psycopg.Connection,+ extensions: tuple[str, ...] = ("ducklake", "httpfs", "delta"),+) -> None:+ """Install and load required extensions on a duckgres connection.++ Callers should request only what they use: extensions bundled in the duckgres+ worker image (httpfs, ducklake) make INSTALL a local no-op, but anything else+ triggers a CDN download that egress-restricted workers silently drop.+ """+ for ext in extensions:conn.execute(f"INSTALL {ext}")conn.execute(f"LOAD {ext}")diff --git a/posthog/management/commands/reset_duckgres_failed_runs.py b/posthog/management/commands/reset_duckgres_failed_runs.pynew file mode 100644index 000000000000..ef9a822dbb1e--- /dev/null+++ b/posthog/management/commands/reset_duckgres_failed_runs.py@@ -0,0 +1,92 @@+from django.core.management.base import BaseCommand, CommandError++import psycopg+import structlog++from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (+ DUCKGRES_STATUS_TABLE,+ DUCKGRES_STATUS_VIEW,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ PARTITION_PRUNING_INTERVAL,+)++logger = structlog.get_logger(__name__)+++class Command(BaseCommand):+ help = (+ "Un-stick a permanently failed Duckgres sink run: writes fresh 'waiting_retry' "+ "status rows (attempt reset to 0) for its failed batches so the consumer picks "+ "them up again. Only works while the batches are inside the queue retention "+ "window — after that, heal via a full resync of the schema."+ )++ def add_arguments(self, parser):+ parser.add_argument("--run-uuid", type=str, help="Reset all failed duckgres batches of this run")+ 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")++ def handle(self, *args, **options):+ run_uuid = options.get("run_uuid")+ team_id = options.get("team_id")+ schema_id = options.get("schema_id")+ dry_run = options.get("dry_run", False)++ if not run_uuid and not (team_id and schema_id):+ raise CommandError("Provide --run-uuid, or both --team-id and --schema-id")++ filters = ["dgs.job_state = 'failed'", f"b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'"]+ params: dict = {}+ if run_uuid:+ filters.append("b.run_uuid = %(run_uuid)s")+ params["run_uuid"] = run_uuid+ if team_id:+ filters.append("b.team_id = %(team_id)s")+ params["team_id"] = team_id+ if schema_id:+ filters.append("b.schema_id = %(schema_id)s")+ params["schema_id"] = schema_id++ where = " AND ".join(filters)+ select_sql = f"""+ SELECT dgs.batch_id, b.run_uuid, b.batch_index, b.s3_path+ FROM {DUCKGRES_STATUS_VIEW} dgs+ JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id+ WHERE {where}+ ORDER BY b.run_uuid, b.batch_index+ """++ with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:+ rows = conn.execute(select_sql, params).fetchall()+ if not rows:+ self.stdout.write("No failed duckgres batches match — nothing to reset.")+ return++ self.stdout.write(f"{len(rows)} failed duckgres batch(es) across {len({r[1] for r in rows})} run(s):")+ for batch_id, r_uuid, batch_index, s3_path in rows:+ self.stdout.write(f" run={r_uuid} batch_index={batch_index} batch_id={batch_id} s3={s3_path}")++ if dry_run:+ self.stdout.write("Dry run — no changes written.")+ return++ cursor = conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, error_response)+ SELECT dgs.batch_id, 'waiting_retry', 0,+ jsonb_build_object('error', 'manually reset via reset_duckgres_failed_runs')+ FROM {DUCKGRES_STATUS_VIEW} dgs+ JOIN {BATCH_TABLE} b ON b.id = dgs.batch_id+ WHERE {where}+ """,+ params,+ )+ self.stdout.write(self.style.SUCCESS(f"Reset {cursor.rowcount} batch(es) to waiting_retry (attempt 0)."))+ self.stdout.write(+ "Note: if any batch's S3 extract has already been pruned, its retry will fail again — "+ "heal those schemas with a full resync instead."+ )diff --git a/posthog/management/commands/run_warehouse_sources_duckgres_load.py b/posthog/management/commands/run_warehouse_sources_duckgres_load.pynew file mode 100644index 000000000000..cbd466385b99--- /dev/null+++ b/posthog/management/commands/run_warehouse_sources_duckgres_load.py@@ -0,0 +1,133 @@+import asyncio++from django.core.management.base import BaseCommand++import structlog++from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL+from posthog.temporal.common.logger import configure_logger+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (+ DuckgresBatchConsumer,+ DuckgresConsumerConfig,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.load import process_batch+from posthog.temporal.data_imports.pipelines.pipeline_v3.load.health import HealthState, start_health_server++logger = structlog.get_logger(__name__)++# The sink exists to survive duckgres maintenance windows: defaults give ~3h of+# retry coverage (8 attempts, 300s * attempt backoff) instead of the engine's+# <2min, because a max-attempts failure permanently gaps incremental tables.+DEFAULT_MAX_ATTEMPTS = 8+DEFAULT_RETRY_BACKOFF_SECONDS = 300+# A duckgres MERGE can legitimately run for minutes; recovery must not hand the+# batch to another pod while the first is still writing.+DEFAULT_RECOVERY_GRACE_SECONDS = 900+# A single batch wedged longer than this fails liveness so the pod restarts and+# the recovery sweep reassigns the batch.+DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS = 1800.0+++class Command(BaseCommand):+ help = "Run the warehouse sources Duckgres batch consumer"++ def add_arguments(self, parser):+ parser.add_argument(+ "--max-concurrency",+ type=int,+ default=16,+ help="Maximum number of (team_id, schema_id) groups processed concurrently (default: 16)",+ )+ parser.add_argument(+ "--poll-interval",+ type=float,+ default=2.0,+ help="Seconds between poll cycles when idle (default: 2.0)",+ )+ parser.add_argument(+ "--poll-limit",+ type=int,+ default=50,+ help="Maximum batches fetched per poll cycle (default: 50)",+ )+ parser.add_argument(+ "--max-attempts",+ type=int,+ default=DEFAULT_MAX_ATTEMPTS,+ help=f"Maximum processing attempts per batch before failing the Duckgres run (default: {DEFAULT_MAX_ATTEMPTS})",+ )+ parser.add_argument(+ "--retry-backoff",+ type=int,+ default=DEFAULT_RETRY_BACKOFF_SECONDS,+ help=f"Base seconds of retry backoff, multiplied by attempt (default: {DEFAULT_RETRY_BACKOFF_SECONDS})",+ )+ parser.add_argument(+ "--recovery-grace",+ type=int,+ default=DEFAULT_RECOVERY_GRACE_SECONDS,+ help=f"Seconds an 'executing' batch must be stale before recovery reassigns it (default: {DEFAULT_RECOVERY_GRACE_SECONDS})",+ )+ parser.add_argument(+ "--stuck-batch-timeout",+ type=float,+ default=DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS,+ help=f"Seconds a single batch may run before the pod stops reporting healthy (default: {DEFAULT_STUCK_BATCH_TIMEOUT_SECONDS})",+ )+ parser.add_argument(+ "--health-port",+ type=int,+ default=8080,+ help="Port for the health check HTTP server (default: 8080)",+ )+ parser.add_argument(+ "--health-timeout",+ type=float,+ default=60.0,+ help="Health check timeout in seconds (default: 60.0)",+ )++ def handle(self, *args, **options):+ health_port = options["health_port"]+ health_timeout = options["health_timeout"]++ config = DuckgresConsumerConfig(+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,+ max_concurrency=options["max_concurrency"],+ poll_interval_seconds=options["poll_interval"],+ poll_limit=options["poll_limit"],+ max_attempts=options["max_attempts"],+ retry_backoff_base_seconds=options["retry_backoff"],+ recovery_grace_seconds=options["recovery_grace"],+ stuck_batch_timeout_seconds=options["stuck_batch_timeout"],+ health_port=health_port,+ health_timeout_seconds=health_timeout,+ )++ logger.info(+ "warehouse_sources_duckgres_load_starting",+ max_concurrency=config.max_concurrency,+ poll_interval=config.poll_interval_seconds,+ poll_limit=config.poll_limit,+ max_attempts=config.max_attempts,+ retry_backoff_base_seconds=config.retry_backoff_base_seconds,+ recovery_grace_seconds=config.recovery_grace_seconds,+ stuck_batch_timeout_seconds=config.stuck_batch_timeout_seconds,+ health_port=health_port,+ )++ health_state = HealthState(timeout_seconds=health_timeout)+ start_health_server(port=health_port, health_state=health_state)++ consumer = DuckgresBatchConsumer(+ config=config, process_batch=process_batch, health_reporter=health_state.report_healthy+ )+ asyncio.run(_run_consumer(consumer))+++async def _run_consumer(consumer: DuckgresBatchConsumer) -> None:+ # Route structlog through the Kafka -> ClickHouse log_entries pipeline so the+ # per-batch contextvars the engine binds are user-visible, mirroring the Delta+ # consumer's entrypoint.+ configure_logger(loop=asyncio.get_running_loop())+ await consumer.run()diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.pyindex 5c41f3730b49..a67d13ebd206 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/batch_consumer.py@@ -14,14 +14,8 @@ import structlogfrom posthog.exceptions_capture import capture_exceptionfrom posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatchfrom posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import (- ACTIVE_GROUPS,- BATCH_PROCESSING_DURATION_SECONDS,- BATCH_RETRY_TOTAL,- BATCHES_PROCESSED_TOTAL,- POLL_BATCHES_FETCHED,- POLL_DURATION_SECONDS,- RECOVERY_SWEEPS_TOTAL,- RUNS_FAILED_TOTAL,+ DELTA_CONSUMER_METRICS,+ ConsumerMetrics,)logger = structlog.get_logger(__name__)@@ -57,6 +51,10 @@ class BatchConsumerConfig:reconcile_grace_seconds: int = RECONCILE_GRACE_SECONDSreconcile_lookback_seconds: int = RECONCILE_LOOKBACK_SECONDSreconcile_limit: int = 100+ # When set, the consumer stops reporting itself healthy once any single batch+ # has been executing longer than this, so a wedged sink connection turns into+ # a liveness-probe restart instead of an indefinite, invisible stall.+ stuck_batch_timeout_seconds: float | None = Nonedef __post_init__(self) -> None:if self.recovery_grace_seconds is None:@@ -64,6 +62,15 @@ class BatchConsumerConfig:class BatchConsumerAdapter(Protocol):+ """Sink-specific queue operations the shared engine drives.++ Contract notes:+ - ``fail_run`` MUST NOT raise: the engine calls it from error paths that must+ not crash the consumer. Isolate each internal step (queue write, app-DB+ write, lock release) and swallow-with-capture failures.+ - All other methods may raise; the engine isolates them per group/batch.+ """+log_prefix: strexecuting_state: strsucceeded_state: str@@ -140,11 +147,13 @@ class BatchConsumer:process_batch: ProcessBatchFn,adapter: BatchConsumerAdapter,health_reporter: Callable[[], None] | None = None,+ metrics: ConsumerMetrics | None = None,) -> None:self._config = configself._process_batch = process_batchself._adapter = adapterself._health_reporter = health_reporter+ self._metrics = metrics or DELTA_CONSUMER_METRICSself._semaphore = asyncio.Semaphore(config.max_concurrency)self._shutdown = asyncio.Event()self._conn: psycopg.AsyncConnection[Any] | None = None@@ -156,6 +165,9 @@ class BatchConsumer:self._heartbeat_task: asyncio.Task[None] | None = None# Monotonic stamp of the last reconcile sweep; runs inside the recovery loop so both share one connection.self._last_reconcile_monotonic = 0.0+ # batch_id -> monotonic start, for the stuck-batch watchdog.+ self._inflight_started: dict[str, float] = {}+ self._last_stuck_log_monotonic = 0.0async def _connect(self) -> psycopg.AsyncConnection[Any]:return await psycopg.AsyncConnection.connect(@@ -209,8 +221,7 @@ class BatchConsumer:self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())while not self._shutdown.is_set():- if self._health_reporter:- self._health_reporter()+ self._report_health()poll_start = time.monotonic()try:@@ -226,8 +237,8 @@ class BatchConsumer:capture_exception(e)await self._wait_or_shutdown(self._config.poll_interval_seconds)continue- POLL_DURATION_SECONDS.observe(time.monotonic() - poll_start)- POLL_BATCHES_FETCHED.observe(len(batches))+ self._metrics.poll_duration_seconds.observe(time.monotonic() - poll_start)+ self._metrics.poll_batches_fetched.observe(len(batches))if not batches:await self._wait_or_shutdown(self._config.poll_interval_seconds)@@ -241,13 +252,13 @@ class BatchConsumer:group_count=len(groups),)- ACTIVE_GROUPS.inc(len(groups))+ self._metrics.active_groups.inc(len(groups))try:await asyncio.gather(*[self._process_group(key, group_batches) for key, group_batches in groups.items()])finally:- ACTIVE_GROUPS.dec(len(groups))+ self._metrics.active_groups.dec(len(groups))finally:await self._close()@@ -349,9 +360,11 @@ class BatchConsumer:log_source_id=batch.schema_id,attempt=attempt,)+ self._inflight_started[batch.id] = time.monotonic()try:return await self._process_single_inner(batch, attempt, team_id, schema_id)finally:+ self._inflight_started.pop(batch.id, None)# Unbind only the keys we set so ambient context (parent logger, test setup) survives.structlog.contextvars.unbind_contextvars(*bound_keys)@@ -367,6 +380,16 @@ class BatchConsumer:await self._fail_run(batch, reason=f"max retries exceeded (attempt {attempt})")return False+ logger.info(+ self._event("batch_picked_up"),+ batch_id=batch.id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ is_final_batch=batch.is_final_batch,+ attempt=attempt,+ resource_name=batch.resource_name,+ )+# Pre-increment: if we OOM here, recovery sees attempt=N+1# and knows this attempt was consumed.await self._adapter.update_status(@@ -383,8 +406,9 @@ class BatchConsumer:await self._process_batch(batch)await self._adapter.after_batch_processed(await self._ensure_main_conn(), batch=batch)- BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).observe(- time.monotonic() - start+ duration = time.monotonic() - start+ self._metrics.batch_processing_duration_seconds.labels(team_id=team_id, schema_id=schema_id).observe(+ duration)await self._adapter.update_status(@@ -393,11 +417,19 @@ class BatchConsumer:job_state=self._adapter.succeeded_state,attempt=attempt,)- BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="success").inc()+ self._metrics.batches_processed_total.labels(team_id=team_id, schema_id=schema_id, status="success").inc()+ logger.info(+ self._event("batch_processed_ok"),+ batch_id=batch.id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ is_final_batch=batch.is_final_batch,+ duration_seconds=round(duration, 3),+ )return Trueexcept Exception as err:- BATCHES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="error").inc()- BATCH_RETRY_TOTAL.labels(attempt=str(attempt), error_type=type(err).__name__).inc()+ self._metrics.batches_processed_total.labels(team_id=team_id, schema_id=schema_id, status="error").inc()+ self._metrics.batch_retry_total.labels(attempt=str(attempt), error_type=type(err).__name__).inc()if attempt >= self._config.max_attempts:logger.exception(@@ -433,8 +465,14 @@ class BatchConsumer:"""Fail the run via the adapter; the adapter isolates each step so a failure can't crash the consumer."""conn = conn or await self._ensure_main_conn()- await self._adapter.fail_run(conn, batch=batch, reason=reason)- RUNS_FAILED_TOTAL.inc()+ try:+ await self._adapter.fail_run(conn, batch=batch, reason=reason)+ except Exception as e:+ # Adapters are documented no-raise; this is the engine's backstop so a+ # buggy adapter cannot crash _recovery_sweep or _process_single_inner.+ logger.exception(self._event("adapter_fail_run_raised"), batch_id=batch.id, run_uuid=batch.run_uuid)+ capture_exception(e)+ self._metrics.runs_failed_total.inc()async def _recovery_loop(self) -> None:while not self._shutdown.is_set():@@ -472,6 +510,32 @@ class BatchConsumer:limit=self._config.reconcile_limit,)+ def _report_health(self) -> None:+ """Report liveness, unless the stuck-batch watchdog has tripped.++ Withholding the report makes the health server's timeout fail the liveness+ probe, so Kubernetes restarts the pod and the recovery sweep reassigns the+ wedged batch — a sync thread blocked on a dead sink connection cannot be+ cancelled from the event loop, so a restart is the only real remedy.+ """+ if self._health_reporter is None:+ return+ timeout = self._config.stuck_batch_timeout_seconds+ if timeout is not None and self._inflight_started:+ now = time.monotonic()+ oldest_id, oldest_started = min(self._inflight_started.items(), key=lambda kv: kv[1])+ if now - oldest_started > timeout:+ if now - self._last_stuck_log_monotonic > 60:+ self._last_stuck_log_monotonic = now+ logger.error(+ self._event("stuck_batch_watchdog_tripped"),+ batch_id=oldest_id,+ running_seconds=round(now - oldest_started, 1),+ timeout_seconds=timeout,+ )+ return+ self._health_reporter()+async def _heartbeat_loop(self) -> None:"""Report liveness on a fixed cadence, independent of batch processing.@@ -479,8 +543,7 @@ class BatchConsumer:compaction), so the main loop's per-poll health report is not enough on its own."""while not self._shutdown.is_set():- if self._health_reporter:- self._health_reporter()+ self._report_health()try:await asyncio.wait_for(self._shutdown.wait(), timeout=self._config.heartbeat_interval_seconds)except TimeoutError:@@ -493,10 +556,10 @@ class BatchConsumer:assert grace_seconds is not Nonestale = await self._adapter.get_stale_executing(conn, grace_seconds=grace_seconds)if not stale:- RECOVERY_SWEEPS_TOTAL.labels(outcome="clean").inc()+ self._metrics.recovery_sweeps_total.labels(outcome="clean").inc()return- RECOVERY_SWEEPS_TOTAL.labels(outcome="orphans_found").inc()+ self._metrics.recovery_sweeps_total.labels(outcome="orphans_found").inc()logger.info(self._event("recovery_sweep_found_stale_batches"), count=len(stale))recovery_bound_keys = (diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.pynew file mode 100644index 000000000000..940fac300a70--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/__init__.py@@ -0,0 +1,6 @@+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (+ DuckgresBatchConsumer,+ DuckgresConsumerConfig,+)++__all__ = ["DuckgresBatchConsumer", "DuckgresConsumerConfig"]diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.pynew file mode 100644index 000000000000..b72154a94171--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/consumer.py@@ -0,0 +1,231 @@+from __future__ import annotations++import time+from collections.abc import Callable+from typing import Any++import psycopg+import structlog+from asgiref.sync import sync_to_async+from prometheus_client import Gauge++from posthog.exceptions_capture import capture_exception+from posthog.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (+ MAX_ATTEMPTS,+ POLL_INTERVAL_SECONDS,+ RECOVERY_INTERVAL_SECONDS,+ BatchConsumer as SharedBatchConsumer,+ BatchConsumerConfig,+ ProcessBatchFn,+ _group_by_key,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import duckgres_sink_team_ids+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import DuckgresBatchQueue+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.metrics import make_consumer_metrics++from products.warehouse_sources_queue.backend.models import SourceBatchDuckgresStatus++logger = structlog.get_logger(__name__)++DuckgresConsumerConfig = BatchConsumerConfig++# How often the fetch path refreshes the enabled-team set and runs the+# supersede sweep + backlog gauges (the poll loop itself runs every ~2s).+ENABLEMENT_REFRESH_SECONDS = 60.0+MAINTENANCE_INTERVAL_SECONDS = 30.0++SINK_ELIGIBLE_BACKLOG = Gauge(+ "duckgres_sink_eligible_backlog",+ "Delta-succeeded data batches not yet applied to Duckgres (non-failed runs)",+ multiprocess_mode="livemax",+)+SINK_OLDEST_ELIGIBLE_AGE_SECONDS = Gauge(+ "duckgres_sink_oldest_eligible_age_seconds",+ "Age of the oldest delta-succeeded batch the Duckgres sink has not applied. "+ "Queue retention permanently drops batches after RETENTION_DAYS — alert well before that.",+ 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)",+ multiprocess_mode="livemax",+)+++class DuckgresBatchConsumerAdapter:+ log_prefix: str = "duckgres"+ executing_state: str = SourceBatchDuckgresStatus.State.EXECUTING.value+ succeeded_state: str = SourceBatchDuckgresStatus.State.SUCCEEDED.value+ waiting_retry_state: str = SourceBatchDuckgresStatus.State.WAITING_RETRY.value++ def __init__(self) -> None:+ self._team_ids: list[int] | None = None+ self._team_ids_fetched_at: float | None = None+ self._last_maintenance_at = 0.0++ async def _enabled_team_ids(self) -> list[int] | None:+ """Cached duckgres-enabled team set; keeps the previous set on app-DB errors."""+ now = time.monotonic()+ if self._team_ids_fetched_at is not None and now - self._team_ids_fetched_at < ENABLEMENT_REFRESH_SECONDS:+ return self._team_ids+ try:+ self._team_ids = await sync_to_async(duckgres_sink_team_ids, thread_sensitive=False)()+ self._team_ids_fetched_at = now+ except Exception as e:+ logger.exception("duckgres_sink_enablement_refresh_failed")+ capture_exception(e)+ if self._team_ids_fetched_at is None:+ # Never had a set: claim nothing rather than everything.+ self._team_ids = []+ self._team_ids_fetched_at = now+ return self._team_ids++ async def _run_maintenance(self, conn: psycopg.AsyncConnection[Any], team_ids: list[int] | None) -> None:+ """Supersede obsolete runs and refresh the sink lag gauges (every ~30s)."""+ now = time.monotonic()+ if now - self._last_maintenance_at < MAINTENANCE_INTERVAL_SECONDS:+ return+ self._last_maintenance_at = now++ 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 = await DuckgresBatchQueue.get_backlog_stats(conn, team_ids=team_ids)+ SINK_ELIGIBLE_BACKLOG.set(backlog)+ SINK_OLDEST_ELIGIBLE_AGE_SECONDS.set(oldest_age or 0.0)++ async def fetch_and_lock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ limit: int,+ retry_backoff_base_seconds: int,+ ) -> list[PendingBatch]:+ team_ids = await self._enabled_team_ids()+ if team_ids is not None and not team_ids:+ return []++ await self._run_maintenance(conn, team_ids)++ return await DuckgresBatchQueue.get_delta_succeeded_and_lock(+ conn,+ limit=limit,+ retry_backoff_base_seconds=retry_backoff_base_seconds,+ team_ids=team_ids,+ )++ async def unlock(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batches: list[PendingBatch],+ ) -> None:+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches)++ async def update_status(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ job_state: str,+ attempt: int,+ error_response: dict[str, Any] | None = None,+ ) -> None:+ await DuckgresBatchQueue.update_status(+ conn,+ batch_id=batch_id,+ job_state=job_state,+ attempt=attempt,+ error_response=error_response,+ )++ async def fail_run(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ reason: str,+ ) -> None:+ # Contract: fail_run must not raise (see BatchConsumerAdapter docstring).+ try:+ await DuckgresBatchQueue.fail_run(conn, run_uuid=batch.run_uuid, reason=reason)+ except Exception as e:+ logger.exception(+ "duckgres_fail_run_queue_update_failed",+ batch_id=batch.id,+ run_uuid=batch.run_uuid,+ )+ capture_exception(e)++ async def get_stale_executing(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ grace_seconds: int,+ ) -> list[PendingBatch]:+ return await DuckgresBatchQueue.get_stale_executing(conn, grace_seconds=grace_seconds)++ async def reconcile_failed_runs(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ grace_seconds: int,+ lookback_seconds: int,+ limit: int,+ ) -> None:+ # The Duckgres sink owns no ExternalDataJob lifecycle: a failed Duckgres run+ # must not mark the import job failed (Delta already succeeded), so there is+ # nothing to reconcile here.+ return None++ async def should_process_batch(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ ) -> bool:+ already_applied = await DuckgresBatchQueue.has_applied(conn, batch=batch)+ if batch.is_final_batch:+ if not already_applied:+ raise RuntimeError(f"Final Duckgres marker received before batch {batch.batch_index} was applied")+ return False+ return not already_applied++ async def after_batch_processed(+ self,+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ ) -> None:+ if not batch.is_final_batch:+ await DuckgresBatchQueue.mark_applied(conn, batch=batch)+++class DuckgresBatchConsumer(SharedBatchConsumer):+ def __init__(+ self,+ config: DuckgresConsumerConfig,+ process_batch: ProcessBatchFn,+ health_reporter: Callable[[], None] | None = None,+ ) -> None:+ super().__init__(+ config=config,+ process_batch=process_batch,+ adapter=DuckgresBatchConsumerAdapter(),+ health_reporter=health_reporter,+ metrics=make_consumer_metrics("duckgres"),+ )+++__all__ = [+ "DuckgresBatchConsumer",+ "DuckgresBatchConsumerAdapter",+ "DuckgresConsumerConfig",+ "MAX_ATTEMPTS",+ "POLL_INTERVAL_SECONDS",+ "RECOVERY_INTERVAL_SECONDS",+ "_group_by_key",+]diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.pynew file mode 100644index 000000000000..a3c501451b3d--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/enablement.py@@ -0,0 +1,63 @@+"""Which teams the Duckgres batch sink is enabled for.++The sink must only claim batches for teams that (a) belong to an org with a+provisioned DuckgresServer and (b) have the rollout feature flag on. Claiming+anything else burns retries, fails sink runs, and floods Sentry for orgs that+have no Duckgres to write to.++The flag also provides mutual exclusion with the legacy+DuckLakeCopyDataImportsWorkflow (full-table copy after each import job): that+workflow skips teams where this flag is enabled, so a table never has two+uncoordinated duckgres writers.+"""++from __future__ import annotations++import structlog+import posthoganalytics++from posthog.ducklake.common import is_dev_mode+from posthog.exceptions_capture import capture_exception++logger = structlog.get_logger(__name__)++DUCKGRES_BATCH_SINK_FLAG = "duckgres-batch-sink"+++def duckgres_sink_team_ids() -> list[int] | None:+ """Team ids the sink may process, or None for "no filter" (dev mode).++ Runs sync (Django ORM + flag evaluation); call via sync_to_async from the+ consumer. Raises on app-DB errors — the caller keeps its previous cached+ set so a transient app-DB blip doesn't blind the sink.+ """+ if is_dev_mode():+ return None++ from posthog.ducklake.models import DuckgresServer+ from posthog.models import Team++ org_ids = list(+ DuckgresServer.objects.filter(organization_id__isnull=False).values_list("organization_id", flat=True)+ )+ if not org_ids:+ return []++ enabled: list[int] = []+ for team_id, team_uuid, org_id in Team.objects.filter(organization_id__in=org_ids).values_list(+ "id", "uuid", "organization_id"+ ):+ try:+ if posthoganalytics.feature_enabled(+ DUCKGRES_BATCH_SINK_FLAG,+ str(team_uuid),+ groups={"organization": str(org_id), "project": str(team_id)},+ send_feature_flag_events=False,+ ):+ enabled.append(team_id)+ except Exception as e:+ # Flag evaluation failing for one team must not blind the whole sink;+ # treat as disabled (safe direction: we skip, never wrongly claim).+ logger.exception("duckgres_sink_flag_evaluation_failed", team_id=team_id)+ capture_exception(e)+ return enableddiff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.pynew file mode 100644index 000000000000..65c9ddcac31c--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py@@ -0,0 +1,455 @@+from __future__ import annotations++import json+from typing import Any++import psycopg+from psycopg.rows import dict_row++from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ PARTITION_PRUNING_INTERVAL,+ STATUS_VIEW as DELTA_STATUS_VIEW,+ PendingBatch,+ pending_batch_select_columns,+ unlock_advisory_locks,+)++DUCKGRES_STATUS_TABLE = "sourcebatchduckgresstatus"+DUCKGRES_STATUS_VIEW = "v_latest_source_batch_duckgres_status"+DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"++DUCKGRES_ADVISORY_LOCK_NAMESPACE = 0x44475300 # "DGS\0" in hex++# 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).+#+# - run_starts: per-run start time, the total order used for cross-run gating+# (run_uuid tiebreak makes it total even for identical timestamps).+# - failed_runs: runs terminally excluded from the sink — Delta-failed or+# Duckgres-failed (including superseded).+# - incomplete_runs: non-failed runs that still owe unapplied data batches;+# these block newer runs of the same schema (cross-run head-of-line).+ELIGIBILITY_CTES = f"""run_starts AS MATERIALIZED (+ SELECT b_rs.run_uuid, min(b_rs.created_at) AS started_at+ FROM {BATCH_TABLE} b_rs+ WHERE b_rs.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR b_rs.team_id = ANY(%(team_ids)s))+ GROUP BY b_rs.run_uuid+ ),+ failed_runs AS MATERIALIZED (+ SELECT DISTINCT b2.run_uuid+ FROM {BATCH_TABLE} b2+ JOIN {DELTA_STATUS_VIEW} ds2 ON b2.id = ds2.batch_id+ WHERE b2.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR b2.team_id = ANY(%(team_ids)s))+ AND ds2.job_state = 'failed'+ UNION+ SELECT DISTINCT b3.run_uuid+ FROM {BATCH_TABLE} b3+ JOIN {DUCKGRES_STATUS_VIEW} dgs3 ON b3.id = dgs3.batch_id+ WHERE b3.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR b3.team_id = ANY(%(team_ids)s))+ AND dgs3.job_state = 'failed'+ ),+ incomplete_runs AS MATERIALIZED (+ SELECT old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at+ FROM {BATCH_TABLE} old+ JOIN {DELTA_STATUS_VIEW} ods ON old.id = ods.batch_id+ JOIN run_starts rs_ir ON rs_ir.run_uuid = old.run_uuid+ LEFT JOIN {DUCKGRES_APPLY_TABLE} oa+ ON oa.team_id = old.team_id+ AND oa.schema_id = old.schema_id+ AND oa.run_uuid = old.run_uuid+ AND oa.batch_index = old.batch_index+ WHERE old.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR old.team_id = ANY(%(team_ids)s))+ AND ods.job_state = 'succeeded'+ AND old.is_final_batch = false+ AND oa.id IS NULL+ AND old.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)+ GROUP BY old.team_id, old.schema_id, old.run_uuid, rs_ir.started_at+ ),"""+++class DuckgresBatchQueue:+ @staticmethod+ async def get_delta_succeeded_and_lock(+ conn: psycopg.AsyncConnection[Any],+ *,+ limit: int = 50,+ retry_backoff_base_seconds: int = 0,+ team_ids: list[int] | None = None,+ ) -> list[PendingBatch]:+ """Fetch Duckgres-eligible batches whose Delta load has succeeded.++ Duckgres has its own sink state. A source batch is eligible only after the+ Delta consumer marks that exact batch row as succeeded.++ ``retry_backoff_base_seconds`` gates the ``waiting_retry`` branch on the age+ of the latest Duckgres status row, mirroring the Delta queue's backoff.++ ``team_ids`` restricts eligibility to duckgres-enabled teams (None = no+ filter, for tests/dev). The sink must never claim batches for orgs without+ a Duckgres deployment — they would burn retries and fail runs for nothing.++ Cross-run head-of-line: a batch is ineligible while an older run (by run+ start time) of the same (team_id, schema_id) still has unapplied,+ non-failed data batches. Without this, a newer run's batch-0+ CREATE OR REPLACE could interleave with an older run's remaining+ inserts/merges and permanently mix two runs' rows in the Duckgres table.+ Liveness: older runs either complete, fail (max attempts), or are+ superseded by ``supersede_replaced_runs`` — all three unblock the gate.+ """+ async with conn.cursor(row_factory=dict_row) as cur:+ await cur.execute(+ f"""+ WITH {ELIGIBILITY_CTES}+ candidates AS MATERIALIZED (+ SELECT+ {pending_batch_select_columns("dgs")}+ FROM {BATCH_TABLE} b+ JOIN {DELTA_STATUS_VIEW} ds ON b.id = ds.batch_id+ JOIN run_starts rs_b ON rs_b.run_uuid = b.run_uuid+ LEFT JOIN {DUCKGRES_STATUS_VIEW} dgs ON b.id = dgs.batch_id+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ AND ds.job_state = 'succeeded'+ AND (+ dgs.batch_id IS NULL+ OR (+ dgs.job_state = 'waiting_retry'+ AND dgs.created_at <= now() - make_interval(+ secs => %(backoff)s * GREATEST(COALESCE(dgs.attempt, 1), 1)+ )+ )+ )+ AND (+ -- Self-apply exclusion, scoped to statusless batches: an+ -- applied batch with no duckgres status row must not be+ -- re-claimed. A batch stranded in waiting_retry AFTER its+ -- apply marker landed (crash between mark_applied and the+ -- 'succeeded' write) stays claimable on purpose: its no-op+ -- pass converges the status to 'succeeded'.+ b.is_final_batch = true+ OR dgs.batch_id IS NOT NULL+ OR NOT EXISTS (+ SELECT 1+ FROM {DUCKGRES_APPLY_TABLE} current_apply+ WHERE current_apply.team_id = b.team_id+ AND current_apply.schema_id = b.schema_id+ AND current_apply.run_uuid = b.run_uuid+ AND current_apply.batch_index = b.batch_index+ )+ )+ AND b.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)+ AND NOT EXISTS (+ SELECT 1+ FROM {BATCH_TABLE} prev+ LEFT JOIN {DUCKGRES_APPLY_TABLE} a+ ON a.team_id = prev.team_id+ AND a.schema_id = prev.schema_id+ AND a.run_uuid = prev.run_uuid+ AND a.batch_index = prev.batch_index+ WHERE prev.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND prev.team_id = b.team_id+ AND prev.schema_id = b.schema_id+ AND prev.run_uuid = b.run_uuid+ AND prev.is_final_batch = false+ AND (+ prev.batch_index < b.batch_index+ OR (b.is_final_batch = true AND prev.batch_index <= b.batch_index)+ )+ AND a.id IS NULL+ )+ AND NOT EXISTS (+ -- 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)+ )+ ORDER BY b.created_at ASC, b.batch_index ASC, b.is_final_batch ASC+ LIMIT %(limit)s+ )+ SELECT c.*+ FROM candidates c+ WHERE pg_try_advisory_lock(+ {DUCKGRES_ADVISORY_LOCK_NAMESPACE},+ hashtext(c.team_id::text || ':' || c.schema_id)+ )+ 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},+ )+ rows = await cur.fetchall()+ return [PendingBatch(**row) for row in rows]++ @staticmethod+ async def supersede_replaced_runs(+ conn: psycopg.AsyncConnection[Any],+ *,+ team_ids: list[int] | None = None,+ ) -> int:+ """Fail older runs' pending duckgres work once a newer replace-run is ready.++ When a newer run whose batch 0 will CREATE OR REPLACE the table (full+ refresh, or first-ever incremental) is delta-succeeded and not yet+ applied, any older run's remaining unapplied duckgres work is worthless —+ applying it after the replace would mix stale rows into the new table.+ Mark those batches 'failed' (reason: superseded) so the failed-run+ exclusion retires them and the cross-run gate opens for the new run.++ Skips batches currently 'executing' (their attempt resolves on its own)+ and anything already terminal. Returns the number of batches superseded.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ WITH {ELIGIBILITY_CTES}+ replace_heads AS MATERIALIZED (+ SELECT nb.team_id, nb.schema_id, nb.run_uuid, rs.started_at+ FROM {BATCH_TABLE} nb+ JOIN {DELTA_STATUS_VIEW} nds ON nb.id = nds.batch_id+ JOIN run_starts rs ON rs.run_uuid = nb.run_uuid+ LEFT JOIN {DUCKGRES_APPLY_TABLE} na+ ON na.team_id = nb.team_id+ AND na.schema_id = nb.schema_id+ AND na.run_uuid = nb.run_uuid+ AND na.batch_index = nb.batch_index+ WHERE nb.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR nb.team_id = ANY(%(team_ids)s))+ AND nds.job_state = 'succeeded'+ AND nb.batch_index = 0+ AND nb.is_final_batch = false+ AND nb.is_resume = false+ AND (+ nb.sync_type = 'full_refresh'+ OR (nb.sync_type = 'incremental' AND nb.is_first_ever_sync)+ )+ AND na.id IS NULL+ AND nb.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)+ ),+ victims AS (+ SELECT DISTINCT ON (old.id) old.id AS batch_id, rh.run_uuid AS superseded_by+ FROM {BATCH_TABLE} old+ JOIN replace_heads rh+ ON rh.team_id = old.team_id AND rh.schema_id = old.schema_id+ JOIN run_starts ors ON ors.run_uuid = old.run_uuid+ JOIN {DELTA_STATUS_VIEW} ods ON old.id = ods.batch_id+ LEFT JOIN {DUCKGRES_STATUS_VIEW} odgs ON old.id = odgs.batch_id+ LEFT JOIN {DUCKGRES_APPLY_TABLE} oa+ ON oa.team_id = old.team_id+ AND oa.schema_id = old.schema_id+ AND oa.run_uuid = old.run_uuid+ AND oa.batch_index = old.batch_index+ WHERE old.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND old.run_uuid <> rh.run_uuid+ AND (ors.started_at, old.run_uuid) < (rh.started_at, rh.run_uuid)+ AND ods.job_state = 'succeeded'+ AND old.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)+ AND (old.is_final_batch = true OR oa.id IS NULL)+ AND (odgs.batch_id IS NULL OR odgs.job_state = 'waiting_retry')+ ORDER BY old.id, rh.started_at DESC, rh.run_uuid DESC+ )+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, error_response)+ SELECT+ v.batch_id,+ 'failed',+ 0,+ jsonb_build_object('error', 'superseded by newer replace run ' || v.superseded_by)+ FROM victims v+ """,+ {"team_ids": team_ids},+ )+ return cur.rowcount or 0++ @staticmethod+ async def get_backlog_stats(+ 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.++ 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.+ """+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ WITH {ELIGIBILITY_CTES}+ backlog AS (+ SELECT b.created_at+ FROM {BATCH_TABLE} b+ JOIN {DELTA_STATUS_VIEW} ds ON b.id = ds.batch_id+ LEFT JOIN {DUCKGRES_APPLY_TABLE} 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.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND (%(team_ids)s::bigint[] IS NULL OR b.team_id = ANY(%(team_ids)s))+ AND ds.job_state = 'succeeded'+ AND b.is_final_batch = false+ AND a.id IS NULL+ AND b.run_uuid NOT IN (SELECT run_uuid FROM failed_runs)+ )+ SELECT count(*), EXTRACT(EPOCH FROM now() - min(created_at))+ FROM backlog+ """,+ {"team_ids": team_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++ @staticmethod+ async def update_status(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ job_state: str,+ attempt: int = 0,+ error_response: dict[str, Any] | None = None,+ ) -> None:+ await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ VALUES (%(batch_id)s, %(job_state)s, %(attempt)s, now(), %(error_response)s, now())+ """,+ {+ "batch_id": batch_id,+ "job_state": job_state,+ "attempt": attempt,+ "error_response": json.dumps(error_response) if error_response else None,+ },+ )++ @staticmethod+ async def mark_applied(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ ) -> None:+ await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_APPLY_TABLE} (+ team_id, schema_id, run_uuid, batch_index, batch_id, row_count, created_at+ ) VALUES (+ %(team_id)s, %(schema_id)s, %(run_uuid)s, %(batch_index)s, %(batch_id)s, %(row_count)s, now()+ )+ ON CONFLICT (team_id, schema_id, run_uuid, batch_index) DO NOTHING+ """,+ {+ "team_id": batch.team_id,+ "schema_id": batch.schema_id,+ "run_uuid": batch.run_uuid,+ "batch_index": batch.batch_index,+ "batch_id": batch.id,+ "row_count": batch.row_count,+ },+ )++ @staticmethod+ async def has_applied(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch: PendingBatch,+ ) -> bool:+ row = await conn.execute(+ f"""+ SELECT 1+ FROM {DUCKGRES_APPLY_TABLE}+ WHERE team_id = %(team_id)s+ AND schema_id = %(schema_id)s+ AND run_uuid = %(run_uuid)s+ AND batch_index = %(batch_index)s+ LIMIT 1+ """,+ {+ "team_id": batch.team_id,+ "schema_id": batch.schema_id,+ "run_uuid": batch.run_uuid,+ "batch_index": batch.batch_index,+ },+ )+ return await row.fetchone() is not None++ @staticmethod+ async def fail_run(+ conn: psycopg.AsyncConnection[Any],+ *,+ run_uuid: str,+ reason: str,+ ) -> int:+ cursor = await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)+ SELECT b.id, 'failed', 0, now(), %(error_response)s, now()+ FROM {BATCH_TABLE} b+ JOIN {DELTA_STATUS_VIEW} ds ON b.id = ds.batch_id+ LEFT JOIN {DUCKGRES_STATUS_VIEW} dgs ON b.id = dgs.batch_id+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND b.run_uuid = %(run_uuid)s+ AND ds.job_state = 'succeeded'+ AND (dgs.batch_id IS NULL OR dgs.job_state IN ('waiting_retry', 'executing'))+ """,+ {+ "run_uuid": run_uuid,+ "error_response": json.dumps({"error": reason}),+ },+ )+ return cursor.rowcount or 0++ @staticmethod+ async def get_stale_executing(+ conn: psycopg.AsyncConnection[Any],+ *,+ grace_seconds: int = 0,+ ) -> list[PendingBatch]:+ async with conn.cursor(row_factory=dict_row) as cur:+ await cur.execute(+ f"""+ WITH candidates AS MATERIALIZED (+ SELECT+ {pending_batch_select_columns("dgs")}+ FROM {BATCH_TABLE} b+ JOIN {DUCKGRES_STATUS_VIEW} dgs ON b.id = dgs.batch_id+ WHERE+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'+ AND dgs.job_state = 'executing'+ AND dgs.created_at <= now() - make_interval(secs => %(grace)s)+ ORDER BY b.created_at ASC, b.batch_index ASC+ )+ SELECT c.*+ FROM candidates c+ WHERE pg_try_advisory_lock(+ {DUCKGRES_ADVISORY_LOCK_NAMESPACE},+ hashtext(c.team_id::text || ':' || c.schema_id)+ )+ ORDER BY c.created_at ASC, c.batch_index ASC+ """,+ {"grace": grace_seconds},+ )+ rows = await cur.fetchall()++ result = [PendingBatch(**row) for row in rows]+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=result)+ return result++ @staticmethod+ async def unlock_for_batches(+ conn: psycopg.AsyncConnection[Any],+ *,+ batches: list[PendingBatch],+ ) -> None:+ await unlock_advisory_locks(conn, batches=batches, namespace=DUCKGRES_ADVISORY_LOCK_NAMESPACE)diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.pynew file mode 100644index 000000000000..73459a5d9ab3--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/load.py@@ -0,0 +1,15 @@+from __future__ import annotations++from asgiref.sync import sync_to_async++from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor import process_batch as process_sync+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch+++async def process_batch(batch: PendingBatch) -> None:+ # thread_sensitive=False: the default would funnel every batch through+ # asgiref's process-global single-thread executor, reducing the consumer's+ # real parallelism to 1 regardless of max_concurrency. Each batch is+ # self-contained (own Django reads after close_old_connections, own duckgres+ # connection), so cross-thread execution is safe.+ await sync_to_async(process_sync, thread_sensitive=False)(batch)diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pynew file mode 100644index 000000000000..7abb16446b45--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py@@ -0,0 +1,520 @@+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++from django.conf import settings+from django.db import close_old_connections++import psycopg+import structlog+from psycopg import sql++from posthog.ducklake.common import get_duckgres_config_for_org+from posthog.ducklake.storage import setup_duckgres_session+from posthog.models import Team+from posthog.temporal.data_imports.naming_convention import NamingConvention+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch++from products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchema++logger = structlog.get_logger(__name__)++DUCKGRES_APPLY_TABLE = "_posthog_source_batch_duckgres_apply"++# Duckgres-side apply markers older than this are pruned opportunistically at the+# start of each run. Must comfortably exceed the queue's eligibility window+# (PARTITION_PRUNING_INTERVAL, 14d) — the ordering gate and has_applied read them.+APPLY_MARKER_RETENTION_DAYS = 30++EXTRACT_READ_SECRET_NAME = "posthog_extract_read"+++class DuckgresBatchAlreadyAppliedError(Exception):+ """A concurrent processor applied this batch first; our write was rolled back."""+++@dataclass(frozen=True)+class DuckgresColumn:+ name: str+ type_sql: str+++@dataclass(frozen=True)+class BatchApplyOperation:+ kind: Literal["replace", "create", "insert", "merge"]+ ensure_target_columns: bool = False+ primary_keys: list[str] | None = None+++def process_batch(batch: PendingBatch) -> None:+ # Threads are reused across batches; drop stale app-DB connections so the ORM+ # 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")++ with _connect_to_duckgres(batch.team_id) as conn:+ # The sink only reads parquet over S3; httpfs is bundled in the duckgres+ # worker image so INSTALL is a local no-op. Do NOT add extensions that are+ # not bundled (e.g. delta): egress-restricted workers silently drop the+ # CDN download and the statement hangs.+ setup_duckgres_session(conn, extensions=("httpfs",))+ _create_extract_read_secret(conn)+ try:+ _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+ # ours rolled back. Treat as applied.+ logger.info(+ "duckgres_batch_applied_by_concurrent_processor",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ )+++def _connect_to_duckgres(team_id: int) -> psycopg.Connection[Any]:+ team = Team.objects.only("organization_id").get(id=team_id)+ config = get_duckgres_config_for_org(str(team.organization_id))+ return psycopg.connect(+ host=config["DUCKGRES_HOST"],+ port=config["DUCKGRES_PORT"],+ dbname=config["DUCKGRES_DATABASE"],+ user=config["DUCKGRES_USERNAME"],+ password=config["DUCKGRES_PASSWORD"],+ autocommit=True,+ # A half-open connection to a dead worker would otherwise block the sync+ # thread for the OS TCP timeout (hours). Keepalives bound it to ~2 minutes;+ # the consumer's stuck-batch watchdog is the backstop above that.+ connect_timeout=30,+ keepalives=1,+ keepalives_idle=60,+ keepalives_interval=15,+ keepalives_count=4,+ )+++def _create_extract_read_secret(conn: psycopg.Connection[Any]) -> None:+ """Grant this duckgres session read access to PostHog's extract bucket.++ read_parquet() executes on the duckgres worker, whose ambient credentials are+ org-scoped to the org's own lake bucket — they cannot read the internal+ DATAWAREHOUSE_BUCKET where v3 batches live. Mint short-lived credentials from+ the consumer's own identity and inject them as a session secret SCOPEd to the+ extract bucket, so it wins prefix resolution there and nowhere else.+ """+ bucket = settings.DATAWAREHOUSE_BUCKET+ scope = f"s3://{bucket}"++ if settings.USE_LOCAL_SETUP:+ parts = [+ "TYPE S3",+ f"KEY_ID {_sql_str(settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY)}",+ f"SECRET {_sql_str(settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET)}",+ f"ENDPOINT {_sql_str(settings.OBJECT_STORAGE_ENDPOINT.replace('http://', '').replace('https://', ''))}",+ "URL_STYLE 'path'",+ "USE_SSL false",+ f"SCOPE {_sql_str(scope)}",+ ]+ else:+ import boto3++ session = boto3.Session()+ creds = session.get_credentials()+ if creds is None:+ raise RuntimeError("No AWS credentials available to read the extract bucket from duckgres")+ frozen = creds.get_frozen_credentials()+ if not frozen.access_key or not frozen.secret_key:+ raise RuntimeError("AWS credential chain resolved without an access key pair")+ parts = [+ "TYPE S3",+ f"KEY_ID {_sql_str(frozen.access_key)}",+ f"SECRET {_sql_str(frozen.secret_key)}",+ f"REGION {_sql_str(session.region_name or 'us-east-1')}",+ f"SCOPE {_sql_str(scope)}",+ ]+ if frozen.token:+ parts.insert(3, f"SESSION_TOKEN {_sql_str(frozen.token)}")++ conn.execute(+ f"CREATE OR REPLACE SECRET {EXTRACT_READ_SECRET_NAME} ({', '.join(parts)})" # noqa: S608+ )+++def _sql_str(value: str) -> str:+ return "'" + str(value).replace("'", "''") + "'"+++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)++ conn.execute(+ sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(duckgres_schema)),+ )++ if batch.sync_type == "cdc":+ raise ValueError("Duckgres batch sink does not support CDC batches yet")++ _ensure_duckgres_apply_table(conn, duckgres_schema)+ if batch.batch_index == 0 and not batch.is_final_batch:+ _prune_duckgres_apply_markers(conn, duckgres_schema)+ if _has_duckgres_batch_applied(conn, duckgres_schema, batch=batch):+ logger.info(+ "duckgres_batch_already_applied",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ )+ return++ parquet_schema = _read_parquet_schema(conn, batch.s3_path)+ columns = [column.name for column in parquet_schema]+ operation = _plan_batch_operation(+ conn,+ batch,+ duckgres_schema=duckgres_schema,+ duckgres_table=duckgres_table,+ )++ if operation.kind == "replace":+ logger.info(+ "duckgres_replacing_table_from_batch",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ batch_index=batch.batch_index,+ table=duckgres_table,+ )++ with conn.transaction():+ if operation.ensure_target_columns:+ _ensure_target_columns(conn, duckgres_schema, duckgres_table, parquet_schema)+ _apply_batch_operation(+ conn,+ operation,+ duckgres_schema=duckgres_schema,+ duckgres_table=duckgres_table,+ s3_path=batch.s3_path,+ columns=columns,+ )+ _mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)+ return+++def _duckgres_schema_name(team_id: int) -> str:+ return f"posthog_data_imports_team_{team_id}"+++def _duckgres_table_name(schema: ExternalDataSchema) -> str:+ source_type = schema.source.source_type+ normalized_name = schema.normalized_name+ raw_name = (+ f"{source_type}_{schema.source.prefix}_{normalized_name}"+ if schema.source.prefix+ else f"{source_type}_{normalized_name}"+ )+ return NamingConvention.normalize_identifier(raw_name, max_length=63)+++def _should_replace_table(batch: PendingBatch) -> bool:+ if batch.batch_index != 0 or batch.is_resume:+ return False+ if batch.sync_type == "full_refresh":+ return True+ if batch.sync_type == "incremental":+ return batch.is_first_ever_sync+ return False+++def _plan_batch_operation(+ conn: psycopg.Connection[Any],+ batch: PendingBatch,+ *,+ duckgres_schema: str,+ duckgres_table: str,+) -> BatchApplyOperation:+ if _should_replace_table(batch):+ return BatchApplyOperation(kind="replace")++ if not _table_exists(conn, duckgres_schema, duckgres_table):+ return BatchApplyOperation(kind="create")++ if batch.sync_type == "incremental":+ if batch.is_first_ever_sync:+ return BatchApplyOperation(kind="insert", ensure_target_columns=True)++ primary_keys = _primary_keys(batch)+ if not primary_keys:+ raise ValueError("Duckgres incremental batches require primary keys")+ return BatchApplyOperation(kind="merge", ensure_target_columns=True, primary_keys=primary_keys)++ if batch.sync_type in ("full_refresh", "append"):+ return BatchApplyOperation(kind="insert", ensure_target_columns=True)++ raise ValueError(f"Unsupported Duckgres sync type: {batch.sync_type}")+++def _table_exists(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str) -> bool:+ cursor = conn.execute(+ """+ SELECT 1+ FROM information_schema.tables+ WHERE table_schema = %s+ AND table_name = %s+ LIMIT 1+ """,+ [duckgres_schema, duckgres_table],+ )+ return cursor.fetchone() is not None+++def _replace_table(conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, s3_path: str) -> None:+ conn.execute(+ sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM read_parquet(%s)").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(duckgres_table),+ ),+ [s3_path],+ )+++def _create_table_from_parquet(+ conn: psycopg.Connection[Any], duckgres_schema: str, duckgres_table: str, s3_path: str+) -> None:+ conn.execute(+ sql.SQL("CREATE TABLE {}.{} AS SELECT * FROM read_parquet(%s)").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(duckgres_table),+ ),+ [s3_path],+ )+++def _ensure_duckgres_apply_table(conn: psycopg.Connection[Any], duckgres_schema: str) -> None:+ conn.execute(+ sql.SQL(+ """+ CREATE TABLE IF NOT EXISTS {}.{} (+ schema_id VARCHAR NOT NULL,+ run_uuid VARCHAR NOT NULL,+ batch_index BIGINT NOT NULL,+ batch_id VARCHAR NOT NULL,+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (schema_id, run_uuid, batch_index)+ )+ """+ ).format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(DUCKGRES_APPLY_TABLE),+ )+ )+++def _has_duckgres_batch_applied(conn: psycopg.Connection[Any], duckgres_schema: str, *, batch: PendingBatch) -> bool:+ cursor = conn.execute(+ sql.SQL(+ """+ SELECT 1+ FROM {}.{}+ WHERE schema_id = %s+ AND run_uuid = %s+ AND batch_index = %s+ LIMIT 1+ """+ ).format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(DUCKGRES_APPLY_TABLE),+ ),+ [batch.schema_id, batch.run_uuid, batch.batch_index],+ )+ return cursor.fetchone() is not None+++def _mark_duckgres_batch_applied(conn: psycopg.Connection[Any], duckgres_schema: str, *, batch: PendingBatch) -> None:+ cursor = conn.execute(+ sql.SQL(+ """+ INSERT INTO {}.{} (schema_id, run_uuid, batch_index, batch_id)+ VALUES (%s, %s, %s, %s)+ ON CONFLICT (schema_id, run_uuid, batch_index) DO NOTHING+ """+ ).format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(DUCKGRES_APPLY_TABLE),+ ),+ [batch.schema_id, batch.run_uuid, batch.batch_index, batch.id],+ )+ if not cursor.rowcount:+ # The marker insert shares the data write's transaction, so raising here+ # rolls the data write back: the marker table is the arbiter that makes+ # concurrent double-apply impossible regardless of advisory-lock state.+ raise DuckgresBatchAlreadyAppliedError(+ f"batch {batch.schema_id}/{batch.run_uuid}/{batch.batch_index} already applied"+ )+++def _prune_duckgres_apply_markers(conn: psycopg.Connection[Any], duckgres_schema: str) -> None:+ """Opportunistic retention for the duckgres-side marker table (runs at batch 0)."""+ try:+ conn.execute(+ sql.SQL("DELETE FROM {}.{} WHERE applied_at < now() - INTERVAL {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(DUCKGRES_APPLY_TABLE),+ sql.Literal(f"{APPLY_MARKER_RETENTION_DAYS} days"),+ )+ )+ except Exception:+ # Retention is best-effort; never fail a batch over it.+ logger.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_schema(conn: psycopg.Connection[Any], s3_path: str) -> list[DuckgresColumn]:+ cursor = conn.execute("DESCRIBE SELECT * FROM read_parquet(%s) LIMIT 0", [s3_path])+ rows = cursor.fetchall()+ if not rows:+ raise ValueError("Duckgres could not read parquet column metadata")+ return [DuckgresColumn(name=str(row[0]), type_sql=str(row[1])) for row in rows]+++def _ensure_target_columns(+ conn: psycopg.Connection[Any],+ duckgres_schema: str,+ duckgres_table: str,+ parquet_schema: list[DuckgresColumn],+) -> None:+ cursor = conn.execute(+ """+ SELECT column_name+ FROM information_schema.columns+ WHERE table_schema = %s+ AND table_name = %s+ """,+ [duckgres_schema, duckgres_table],+ )+ existing_columns = {str(row[0]) for row in cursor.fetchall()}++ for column in parquet_schema:+ if column.name in existing_columns:+ continue+ conn.execute(+ sql.SQL("ALTER TABLE {}.{} ADD COLUMN {} {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(duckgres_table),+ sql.Identifier(column.name),+ sql.SQL(column.type_sql),+ )+ )+++def _apply_batch_operation(+ conn: psycopg.Connection[Any],+ operation: BatchApplyOperation,+ *,+ duckgres_schema: str,+ duckgres_table: str,+ s3_path: str,+ columns: list[str],+) -> None:+ if operation.kind == "replace":+ _replace_table(conn, duckgres_schema, duckgres_table, s3_path)+ return+ if operation.kind == "create":+ _create_table_from_parquet(conn, duckgres_schema, duckgres_table, s3_path)+ return+ if operation.kind == "insert":+ _insert_batch(conn, duckgres_schema, duckgres_table, s3_path, columns)+ return+ if 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)+ return+ raise ValueError(f"Unsupported Duckgres apply operation: {operation.kind}")+++def _insert_batch(+ conn: psycopg.Connection[Any],+ duckgres_schema: str,+ duckgres_table: str,+ s3_path: str,+ columns: list[str],+) -> 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.Identifier(duckgres_schema),+ sql.Identifier(duckgres_table),+ insert_columns,+ select_columns,+ ),+ [s3_path],+ )+++def _merge_batch(+ conn: psycopg.Connection[Any],+ duckgres_schema: str,+ duckgres_table: str,+ s3_path: str,+ columns: list[str],+ primary_keys: list[str],+) -> None:+ normalized_primary_keys = [NamingConvention.normalize_identifier(key) for key in primary_keys]+ missing_keys = [key for key in normalized_primary_keys if key not in columns]+ if missing_keys:+ raise ValueError(f"Duckgres incremental batch missing primary keys: {missing_keys}")++ update_columns = [column for column in columns if column not in normalized_primary_keys]+ if not update_columns:+ update_columns = [normalized_primary_keys[0]]+ on_clause = sql.SQL(" AND ").join(+ sql.SQL("source.{} = target.{}").format(sql.Identifier(key), sql.Identifier(key))+ for key in normalized_primary_keys+ )+ update_clause = sql.SQL(", ").join(+ sql.SQL("{} = source.{}").format(sql.Identifier(column), sql.Identifier(column)) for column in update_columns+ )+ insert_columns = sql.SQL(", ").join(sql.Identifier(column) for column in columns)+ insert_values = sql.SQL(", ").join(sql.SQL("source.{}").format(sql.Identifier(column)) for column in columns)++ matched_clause = sql.SQL("WHEN MATCHED THEN UPDATE SET {}").format(update_clause)++ query = sql.SQL(+ """+ MERGE INTO {}.{} AS target+ USING read_parquet(%s) AS source+ ON {}+ {}+ WHEN NOT MATCHED THEN INSERT ({}) VALUES ({})+ """+ ).format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(duckgres_table),+ on_clause,+ matched_clause,+ insert_columns,+ insert_values,+ )+ conn.execute(query, [s3_path])+++def _primary_keys(batch: PendingBatch) -> list[str]:+ raw = batch.metadata.get("primary_keys")+ if not isinstance(raw, list):+ return []+ return [str(key) for key in raw]diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.pynew file mode 100644index 000000000000..5f17d9deefcf--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_consumer.py@@ -0,0 +1,247 @@+import time+from typing import Any++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer import (+ DuckgresBatchConsumer,+ DuckgresBatchConsumerAdapter,+ DuckgresConsumerConfig,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch++from products.warehouse_sources_queue.backend.models import SourceBatchDuckgresStatus+++def _make_batch(**overrides: Any) -> PendingBatch:+ defaults: dict[str, Any] = {+ "id": "00000000-0000-0000-0000-000000000001",+ "team_id": 1,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "job_id": "job-1",+ "run_uuid": "run-1",+ "batch_index": 0,+ "s3_path": "s3://bucket/path",+ "row_count": 100,+ "byte_size": 1024,+ "is_final_batch": False,+ "total_batches": None,+ "total_rows": None,+ "sync_type": "full_refresh",+ "cumulative_row_count": 0,+ "resource_name": "test_resource",+ "is_resume": False,+ "is_first_ever_sync": False,+ "metadata": {},+ "latest_attempt": 0,+ }+ defaults.update(overrides)+ return PendingBatch(**defaults)+++def _make_consumer(max_attempts: int = 3, **kwargs) -> DuckgresBatchConsumer:+ config = DuckgresConsumerConfig(+ database_url="postgres://unused:unused@localhost/unused",+ max_attempts=max_attempts,+ **kwargs,+ )+ consumer = DuckgresBatchConsumer(config=config, process_batch=AsyncMock())+ consumer._conn = _make_healthy_conn()+ consumer._recovery_conn = _make_healthy_conn()+ return consumer+++def _make_healthy_conn(closed: bool = False, broken: bool = False) -> AsyncMock:+ # closed/broken must be real booleans, otherwise _ensure_*_conn sees a dead conn and dials the fake database_url.+ conn = AsyncMock()+ conn.closed = closed+ conn.broken = broken+ return conn+++class TestDuckgresProcessSingle:+ @pytest.mark.asyncio+ async def test_adapter_forwards_empty_error_response_explicitly(self):+ consumer = _make_consumer()+ update_status_calls: list[dict[str, Any]] = []++ async def track_status(conn, **kwargs):+ update_status_calls.append(kwargs)++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",+ side_effect=track_status,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",+ new_callable=AsyncMock,+ return_value=True,+ ),+ ):+ await consumer._process_single(_make_batch(is_final_batch=True))++ assert update_status_calls[0]["error_response"] is None+ assert update_status_calls[1]["error_response"] is None++ @pytest.mark.asyncio+ async def test_success_updates_status_and_marks_applied(self):+ consumer = _make_consumer()+ states: list[str] = []++ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):+ states.append(job_state)++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",+ side_effect=track_status,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",+ new_callable=AsyncMock,+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",+ new_callable=AsyncMock,+ ) as mock_mark,+ ):+ await consumer._process_single(_make_batch())++ assert states == [SourceBatchDuckgresStatus.State.EXECUTING, SourceBatchDuckgresStatus.State.SUCCEEDED]+ mock_mark.assert_called_once()++ @pytest.mark.asyncio+ async def test_final_marker_requires_existing_apply_and_does_not_process(self):+ consumer = _make_consumer()+ consumer._process_batch = AsyncMock()++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",+ new_callable=AsyncMock,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.mark_applied",+ new_callable=AsyncMock,+ ) as mock_mark,+ ):+ await consumer._process_single(_make_batch(is_final_batch=True))++ consumer._process_batch.assert_not_called()+ mock_mark.assert_not_called()++ @pytest.mark.asyncio+ async def test_error_sets_waiting_retry(self):+ consumer = _make_consumer(max_attempts=3)+ consumer._process_batch = AsyncMock(side_effect=ValueError("boom"))+ states: list[str] = []++ async def track_status(conn, *, batch_id, job_state, attempt, error_response=None):+ states.append(job_state)++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.update_status",+ side_effect=track_status,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.has_applied",+ new_callable=AsyncMock,+ return_value=False,+ ),+ ):+ await consumer._process_single(_make_batch())++ assert states == [SourceBatchDuckgresStatus.State.EXECUTING, SourceBatchDuckgresStatus.State.WAITING_RETRY]++ @pytest.mark.asyncio+ async def test_max_attempts_exceeded_fails_duckgres_run_only(self):+ consumer = _make_consumer(max_attempts=3)++ with patch.object(consumer, "_fail_run", new_callable=AsyncMock) as mock_fail:+ await consumer._process_single(_make_batch(latest_attempt=3))++ mock_fail.assert_called_once()+++class TestDuckgresEnablementGating:+ @pytest.mark.asyncio+ async def test_fetch_returns_empty_without_querying_when_no_teams_enabled(self):+ adapter = DuckgresBatchConsumerAdapter()+ adapter._team_ids = []+ adapter._team_ids_fetched_at = time.monotonic()+ conn = _make_healthy_conn()++ with patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",+ new_callable=AsyncMock,+ ) as mock_fetch:+ batches = await adapter.fetch_and_lock(conn, limit=50, retry_backoff_base_seconds=0)++ assert batches == []+ mock_fetch.assert_not_called()++ @pytest.mark.asyncio+ async def test_fetch_passes_team_ids_and_runs_maintenance(self):+ adapter = DuckgresBatchConsumerAdapter()+ adapter._team_ids = [1, 2]+ adapter._team_ids_fetched_at = time.monotonic()+ conn = _make_healthy_conn()++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_delta_succeeded_and_lock",+ new_callable=AsyncMock,+ return_value=[],+ ) as mock_fetch,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.supersede_replaced_runs",+ new_callable=AsyncMock,+ return_value=0,+ ) as mock_supersede,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.consumer.DuckgresBatchQueue.get_backlog_stats",+ new_callable=AsyncMock,+ return_value=(0, None),+ ) as mock_backlog,+ ):+ 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+ mock_supersede.assert_called_once()+ mock_backlog.assert_called_once()+++class TestStuckBatchWatchdog:+ @pytest.mark.asyncio+ async def test_health_withheld_while_a_batch_is_stuck(self):+ reporter = MagicMock()+ consumer = _make_consumer(stuck_batch_timeout_seconds=10.0)+ consumer._health_reporter = reporter+ consumer._inflight_started = {"batch-1": time.monotonic() - 60}++ consumer._report_health()++ reporter.assert_not_called()++ @pytest.mark.asyncio+ async def test_health_reported_when_batches_are_fresh_or_absent(self):+ reporter = MagicMock()+ consumer = _make_consumer(stuck_batch_timeout_seconds=10.0)+ consumer._health_reporter = reporter++ consumer._report_health()+ consumer._inflight_started = {"batch-1": time.monotonic()}+ consumer._report_health()++ assert reporter.call_count == 2diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.pynew file mode 100644index 000000000000..65aa2cda78da--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_jobs_db.py@@ -0,0 +1,365 @@+from typing import Any++import pytest++import psycopg++from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.jobs_db import (+ DUCKGRES_APPLY_TABLE,+ DUCKGRES_STATUS_TABLE,+ DUCKGRES_STATUS_VIEW,+ DuckgresBatchQueue,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (+ BATCH_TABLE,+ STATUS_TABLE,+ STATUS_VIEW,+ BatchQueue,+)+++def _get_test_database_url() -> str:+ from django.db import connection++ settings = connection.settings_dict+ host = settings.get("HOST", "localhost") or "localhost"+ port = settings.get("PORT", "5432") or "5432"+ return f"postgres://{settings['USER']}:{settings['PASSWORD']}@{host}:{port}/{settings['NAME']}"+++def _ensure_tables(conn: psycopg.Connection[Any]) -> None:+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {BATCH_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ team_id BIGINT NOT NULL,+ schema_id VARCHAR(200) NOT NULL,+ source_id VARCHAR(200) NOT NULL,+ job_id VARCHAR(200) NOT NULL,+ run_uuid VARCHAR(200) NOT NULL,+ batch_index INT NOT NULL,+ s3_path TEXT NOT NULL,+ row_count INT NOT NULL,+ byte_size BIGINT NOT NULL,+ is_final_batch BOOLEAN NOT NULL,+ total_batches INT,+ total_rows BIGINT,+ sync_type VARCHAR(32) NOT NULL,+ cumulative_row_count BIGINT NOT NULL DEFAULT 0,+ resource_name VARCHAR(400) NOT NULL,+ is_resume BOOLEAN NOT NULL DEFAULT FALSE,+ is_first_ever_sync BOOLEAN NOT NULL DEFAULT FALSE,+ metadata JSONB NOT NULL DEFAULT '{{}}'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """)+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {STATUS_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,+ job_state VARCHAR(32) NOT NULL,+ attempt SMALLINT NOT NULL DEFAULT 0,+ exec_time TIMESTAMPTZ,+ error_response JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """)+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {DUCKGRES_STATUS_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,+ job_state VARCHAR(32) NOT NULL,+ attempt SMALLINT NOT NULL DEFAULT 0,+ exec_time TIMESTAMPTZ,+ error_response JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+ )+ """)+ conn.execute(f"""+ CREATE TABLE IF NOT EXISTS {DUCKGRES_APPLY_TABLE} (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ team_id BIGINT NOT NULL,+ schema_id VARCHAR(200) NOT NULL,+ run_uuid VARCHAR(200) NOT NULL,+ batch_index INT NOT NULL,+ batch_id UUID NOT NULL REFERENCES {BATCH_TABLE}(id) ON DELETE CASCADE,+ row_count INT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT sbdga_unique_batch_apply UNIQUE (team_id, schema_id, run_uuid, batch_index)+ )+ """)+ conn.execute(f"DROP VIEW IF EXISTS {STATUS_VIEW}")+ conn.execute(f"""+ CREATE VIEW {STATUS_VIEW} AS+ SELECT DISTINCT ON (batch_id) *+ FROM {STATUS_TABLE}+ ORDER BY batch_id ASC, created_at DESC, id DESC+ """)+ conn.execute(f"DROP VIEW IF EXISTS {DUCKGRES_STATUS_VIEW}")+ conn.execute(f"""+ CREATE VIEW {DUCKGRES_STATUS_VIEW} AS+ SELECT DISTINCT ON (batch_id) *+ FROM {DUCKGRES_STATUS_TABLE}+ ORDER BY batch_id ASC, created_at DESC, id DESC+ """)+++def _truncate_tables(conn: psycopg.Connection[Any]) -> None:+ conn.execute(+ f"TRUNCATE {DUCKGRES_APPLY_TABLE}, {DUCKGRES_STATUS_TABLE}, {STATUS_TABLE}, {BATCH_TABLE} RESTART IDENTITY CASCADE"+ )+++_BATCH_DEFAULTS: dict[str, Any] = {+ "team_id": 1,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "job_id": "job-1",+ "run_uuid": "run-1",+ "batch_index": 0,+ "s3_path": "s3://bucket/path",+ "row_count": 100,+ "byte_size": 1024,+ "is_final_batch": False,+ "total_batches": None,+ "total_rows": None,+ "sync_type": "full_refresh",+ "cumulative_row_count": 0,+ "resource_name": "test_resource",+ "is_resume": False,+ "is_first_ever_sync": False,+ "metadata": {},+}+++async def _insert_batch(conn: psycopg.AsyncConnection[Any], **overrides: Any) -> str:+ return await BatchQueue.insert(conn, **{**_BATCH_DEFAULTS, **overrides})++[email protected](scope="session")+def _db_url() -> str:+ return _get_test_database_url()++[email protected](scope="session", autouse=True)+def _create_tables(_db_url: str) -> None:+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:+ _ensure_tables(conn)++[email protected](autouse=True)+def _clean_tables(_db_url: str) -> None:+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:+ _truncate_tables(conn)+ conn.execute("SELECT pg_advisory_unlock_all()")+++async def conn(_db_url: str):+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:+ yield c++[email protected]_db(transaction=True)+class TestDuckgresBatchQueueEligibility:+ @pytest.mark.asyncio+ async def test_ignores_batches_until_delta_succeeds(self, conn):+ await _insert_batch(conn)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert batches == []++ @pytest.mark.asyncio+ async def test_returns_delta_succeeded_batches(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert len(batches) == 1+ assert str(batches[0].id) == batch_id++ @pytest.mark.asyncio+ async def test_skips_duckgres_succeeded_batches(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert batches == []++ @pytest.mark.asyncio+ async def test_returns_duckgres_retry_batches(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.update_status(conn, batch_id=batch_id, job_state="waiting_retry", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert len(batches) == 1+ assert batches[0].latest_attempt == 1++ @pytest.mark.asyncio+ async def test_enforces_prior_batch_apply_order(self, conn):+ first_id = await _insert_batch(conn, batch_index=0)+ second_id = await _insert_batch(conn, batch_index=1)+ await BatchQueue.update_status(conn, batch_id=first_id, job_state="succeeded", attempt=1)+ await BatchQueue.update_status(conn, batch_id=second_id, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert [batch.batch_index for batch in batches] == [0]++ @pytest.mark.asyncio+ async def test_final_marker_waits_for_matching_data_batch_apply(self, conn):+ data_id = await _insert_batch(conn, batch_index=0, is_final_batch=False)+ final_id = await _insert_batch(conn, batch_index=0, is_final_batch=True, total_batches=1, total_rows=100)+ await BatchQueue.update_status(conn, batch_id=data_id, job_state="succeeded", attempt=1)+ await BatchQueue.update_status(conn, batch_id=final_id, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [str(batch.id) for batch in batches] == [data_id]++ await DuckgresBatchQueue.mark_applied(conn, batch=batches[0])+ await DuckgresBatchQueue.unlock_for_batches(conn, batches=batches)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [str(batch.id) for batch in batches] == [final_id]++ @pytest.mark.asyncio+ async def test_delta_failed_run_is_skipped(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ failed_id = await _insert_batch(conn, batch_index=1)+ await BatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert batches == []++ @pytest.mark.asyncio+ async def test_duckgres_failed_run_is_skipped(self, conn):+ batch_id = await _insert_batch(conn)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)+ failed_id = await _insert_batch(conn, batch_index=1)+ await BatchQueue.update_status(conn, batch_id=failed_id, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.update_status(conn, batch_id=failed_id, job_state="failed", attempt=3)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert batches == []+++async def _mark_applied_raw(+ conn: psycopg.AsyncConnection[Any],+ *,+ batch_id: str,+ run_uuid: str,+ batch_index: int,+ team_id: int = 1,+ schema_id: str = "schema-1",+) -> None:+ await conn.execute(+ f"""+ INSERT INTO {DUCKGRES_APPLY_TABLE} (team_id, schema_id, run_uuid, batch_index, batch_id, row_count)+ VALUES (%s, %s, %s, %s, %s, 0)+ """,+ [team_id, schema_id, run_uuid, batch_index, batch_id],+ )++[email protected]_db(transaction=True)+class TestDuckgresCrossRunOrdering:+ @pytest.mark.asyncio+ async def test_newer_run_blocked_while_older_run_incomplete(self, conn):+ # run-1: batch 0 applied, batch 1 delta-succeeded but unapplied -> incomplete+ old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)+ old1 = await _insert_batch(conn, run_uuid="run-1", batch_index=1)+ await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)+ await BatchQueue.update_status(conn, batch_id=old1, job_state="succeeded", attempt=1)+ await _mark_applied_raw(conn, batch_id=old0, run_uuid="run-1", batch_index=0)++ # run-2 (newer, same schema): batch 0 delta-succeeded+ new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ # Only the older run's next batch is eligible; run-2 waits behind it.+ assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 1)]++ @pytest.mark.asyncio+ async def test_newer_run_eligible_once_older_run_failed(self, conn):+ old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)+ await DuckgresBatchQueue.update_status(conn, batch_id=old0, job_state="failed", attempt=3)++ new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)++ assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]++ @pytest.mark.asyncio+ async def test_supersede_retires_older_run_when_replace_head_pending(self, conn):+ # run-1: batch 0 applied, batch 1 delta-succeeded but unapplied+ old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)+ old1 = await _insert_batch(conn, run_uuid="run-1", batch_index=1)+ await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)+ await BatchQueue.update_status(conn, batch_id=old1, job_state="succeeded", attempt=1)+ await _mark_applied_raw(conn, batch_id=old0, run_uuid="run-1", batch_index=0)++ # run-2: a full_refresh replace head (batch 0) is delta-succeeded+ new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0, sync_type="full_refresh")+ await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)++ superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)+ assert superseded == 1 # run-1's pending batch 1++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-2", 0)]++ @pytest.mark.asyncio+ async def test_supersede_does_not_touch_incremental_successor(self, conn):+ old0 = await _insert_batch(conn, run_uuid="run-1", batch_index=0)+ await BatchQueue.update_status(conn, batch_id=old0, job_state="succeeded", attempt=1)++ # Newer incremental (not first-ever) run does not replace the table, so the+ # older run's work must still apply first.+ new0 = await _insert_batch(conn, run_uuid="run-2", batch_index=0, sync_type="incremental")+ await BatchQueue.update_status(conn, batch_id=new0, job_state="succeeded", attempt=1)++ superseded = await DuckgresBatchQueue.supersede_replaced_runs(conn)+ assert superseded == 0++ batches = await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn)+ assert [(b.run_uuid, b.batch_index) for b in batches] == [("run-1", 0)]++[email protected]_db(transaction=True)+class TestDuckgresTeamFilterAndBacklog:+ @pytest.mark.asyncio+ async def test_team_filter(self, conn):+ batch_id = await _insert_batch(conn, team_id=1)+ await BatchQueue.update_status(conn, batch_id=batch_id, job_state="succeeded", attempt=1)++ # Advisory locks are session-reentrant, so repeated fetches on one conn are fine.+ assert await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=[2]) == []+ assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=[1, 2])) == 1+ assert len(await DuckgresBatchQueue.get_delta_succeeded_and_lock(conn, team_ids=None)) == 1++ @pytest.mark.asyncio+ async def test_backlog_stats(self, conn):+ batch_id = await _insert_batch(conn)+ 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+ assert oldest_age is not None and oldest_age >= 0++ await _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 Nonediff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.pynew file mode 100644index 000000000000..0836b4231044--- /dev/null+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/duckgres/test_processor.py@@ -0,0 +1,395 @@+from typing import Any++from unittest.mock import MagicMock, Mock, patch++from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor import (+ DuckgresColumn,+ _ensure_duckgres_apply_table,+ _insert_batch,+ _mark_duckgres_batch_applied,+ _process_batch,+)+from posthog.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import PendingBatch+++def _make_batch(**overrides: Any) -> PendingBatch:+ defaults: dict[str, Any] = {+ "id": "00000000-0000-0000-0000-000000000001",+ "team_id": 1,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "job_id": "job-1",+ "run_uuid": "run-1",+ "batch_index": 0,+ "s3_path": "s3://bucket/path",+ "row_count": 100,+ "byte_size": 1024,+ "is_final_batch": False,+ "total_batches": None,+ "total_rows": None,+ "sync_type": "incremental",+ "cumulative_row_count": 0,+ "resource_name": "test_resource",+ "is_resume": False,+ "is_first_ever_sync": False,+ "metadata": {},+ "latest_attempt": 0,+ }+ defaults.update(overrides)+ return PendingBatch(**defaults)+++def _make_schema() -> Mock:+ schema = Mock()+ schema.normalized_name = "customers"+ schema.source.source_type = "Stripe"+ schema.source.prefix = None+ return schema+++def _make_conn() -> MagicMock:+ return MagicMock()+++def _parquet_schema() -> list[DuckgresColumn]:+ return [DuckgresColumn("id", "BIGINT"), DuckgresColumn("email", "VARCHAR")]+++class _RecordingTransaction:+ def __init__(self, conn: "_RecordingConn") -> None:+ self.conn = conn++ def __enter__(self) -> None:+ self.conn.in_transaction = True+ self.conn.events.append("transaction:start")++ def __exit__(self, *args: object) -> None:+ self.conn.events.append("transaction:end")+ self.conn.in_transaction = False+++class _RecordingConn:+ def __init__(self) -> None:+ self.execute = MagicMock()+ self.events: list[str] = []+ self.in_transaction = False++ def transaction(self) -> _RecordingTransaction:+ return _RecordingTransaction(self)+++def test_first_ever_incremental_batch_replaces_table() -> None:+ conn = _make_conn()+ batch = _make_batch(batch_index=0, is_first_ever_sync=True, is_resume=False, sync_type="incremental")++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table") as replace_table,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists") as table_exists,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch") as insert_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ replace_table.assert_called_once()+ table_exists.assert_not_called()+ merge_batch.assert_not_called()+ insert_batch.assert_not_called()+++def test_existing_incremental_batch_zero_merges_after_first_sync() -> None:+ conn = _make_conn()+ batch = _make_batch(+ batch_index=0,+ sync_type="incremental",+ is_first_ever_sync=False,+ metadata={"primary_keys": ["id"]},+ )++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table") as replace_table,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",+ create=True,+ ) as ensure_columns,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ replace_table.assert_not_called()+ ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())+ merge_batch.assert_called_once()+++def test_first_ever_incremental_followup_batch_inserts_without_primary_keys() -> None:+ conn = _make_conn()+ batch = _make_batch(+ batch_index=1,+ sync_type="incremental",+ is_first_ever_sync=True,+ metadata={},+ )++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",+ create=True,+ ) as ensure_columns,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch") as insert_batch,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())+ insert_batch.assert_called_once()+ merge_batch.assert_not_called()+++def test_existing_incremental_table_merges_after_first_sync() -> None:+ conn = _make_conn()+ batch = _make_batch(+ batch_index=1,+ sync_type="incremental",+ is_first_ever_sync=False,+ metadata={"primary_keys": ["id"]},+ )++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",+ create=True,+ ) as ensure_columns,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch") as insert_batch,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ ensure_columns.assert_called_once_with(conn, "posthog_data_imports_team_1", "stripe_customers", _parquet_schema())+ insert_batch.assert_not_called()+ merge_batch.assert_called_once()+++def test_schema_evolution_merge_and_apply_marker_are_one_transaction() -> None:+ conn: Any = _RecordingConn()+ batch = _make_batch(+ batch_index=1,+ sync_type="incremental",+ is_first_ever_sync=False,+ metadata={"primary_keys": ["id"]},+ )++ def ensure_columns(*args: object) -> None:+ assert conn.in_transaction+ conn.events.append("ensure_columns")++ def merge_batch(*args: object) -> None:+ assert conn.in_transaction+ conn.events.append("merge")++ def mark_applied(*args: object, **kwargs: object) -> None:+ assert conn.in_transaction+ conn.events.append("mark")++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_target_columns",+ side_effect=ensure_columns,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch",+ side_effect=merge_batch,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied",+ side_effect=mark_applied,+ ),+ ):+ _process_batch(conn, batch, _make_schema())++ assert conn.events == ["transaction:start", "ensure_columns", "merge", "mark", "transaction:end"]+++def test_missing_table_is_created_from_parquet() -> None:+ conn = _make_conn()+ batch = _make_batch(+ batch_index=1,+ sync_type="incremental",+ is_first_ever_sync=False,+ metadata={"primary_keys": ["id"]},+ )++ with (+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table"),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._table_exists",+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._create_table_from_parquet"+ ) as create_table,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ create_table.assert_called_once()+ merge_batch.assert_not_called()+++def test_insert_batch_uses_explicit_column_projection() -> None:+ conn = _make_conn()++ _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"]+++def test_already_applied_batch_skips_duckgres_mutation() -> None:+ conn = _make_conn()+ batch = _make_batch(batch_index=0, is_first_ever_sync=True)++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table",+ create=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ create=True,+ return_value=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ) as read_schema,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table") as replace_table,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._insert_batch") as insert_batch,+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._merge_batch") as merge_batch,+ ):+ _process_batch(conn, batch, _make_schema())++ read_schema.assert_not_called()+ replace_table.assert_not_called()+ insert_batch.assert_not_called()+ merge_batch.assert_not_called()+++def test_marks_duckgres_batch_applied_after_successful_mutation() -> None:+ conn = _make_conn()+ batch = _make_batch(batch_index=0, is_first_ever_sync=True)++ with (+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._ensure_duckgres_apply_table",+ create=True,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._has_duckgres_batch_applied",+ create=True,+ return_value=False,+ ),+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._read_parquet_schema",+ return_value=_parquet_schema(),+ ),+ patch("posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._replace_table") as replace_table,+ patch(+ "posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.processor._mark_duckgres_batch_applied",+ create=True,+ ) as mark_applied,+ ):+ _process_batch(conn, batch, _make_schema())++ replace_table.assert_called_once()+ mark_applied.assert_called_once_with(conn, "posthog_data_imports_team_1", batch=batch)+++def test_duckgres_apply_marker_is_scoped_by_schema_id() -> None:+ conn = _make_conn()+ batch = _make_batch(schema_id="schema-1", run_uuid="run-1", batch_index=2)++ _ensure_duckgres_apply_table(conn, "warehouse")+ create_query = conn.execute.call_args.args[0]++ assert "schema_id" in repr(create_query)+ assert "PRIMARY KEY (schema_id, run_uuid, batch_index)" in repr(create_query)++ _mark_duckgres_batch_applied(conn, "warehouse", batch=batch)++ query = conn.execute.call_args.args[0]+ assert "ON CONFLICT (schema_id, run_uuid, batch_index)" in repr(query)+ assert conn.execute.call_args.args[1] == [+ "schema-1",+ "run-1",+ 2,+ "00000000-0000-0000-0000-000000000001",+ ]diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.pyindex 02575cfc1834..cfc593df5234 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py@@ -31,6 +31,31 @@ ADVISORY_LOCK_NAMESPACE = 0x57485300 # "WHS\0" in hexPARTITION_PRUNING_INTERVAL = "14 days"+def pending_batch_select_columns(status_alias: str) -> str:+ return f"""+ b.id, b.team_id, b.schema_id, b.source_id, b.job_id,+ b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,+ b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,+ b.cumulative_row_count, b.resource_name, b.is_resume,+ b.is_first_ever_sync, b.metadata,+ COALESCE({status_alias}.attempt, 0) AS latest_attempt,+ b.created_at+ """+++async def unlock_advisory_locks(+ conn: psycopg.AsyncConnection[Any],+ *,+ batches: list[PendingBatch],+ namespace: int,+) -> None:+ for batch in batches:+ await conn.execute(+ "SELECT pg_advisory_unlock(%(ns)s, hashtext(%(key)s))",+ {"ns": namespace, "key": f"{batch.team_id}:{batch.schema_id}"},+ )++@dataclass(frozen=True, slots=True)class PendingBatch:"""A batch row fetched from the queue, ready to be processed by the consumer."""@@ -219,13 +244,7 @@ class BatchQueue:f"""WITH candidates AS MATERIALIZED (SELECT- b.id, b.team_id, b.schema_id, b.source_id, b.job_id,- b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,- b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,- b.cumulative_row_count, b.resource_name, b.is_resume,- b.is_first_ever_sync, b.metadata,- COALESCE(s.attempt, 0) AS latest_attempt,- b.created_at+ {pending_batch_select_columns("s")}FROM {BATCH_TABLE} bLEFT JOIN {STATUS_VIEW} s ON b.id = s.batch_idWHERE@@ -327,13 +346,7 @@ class BatchQueue:f"""WITH candidates AS MATERIALIZED (SELECT- b.id, b.team_id, b.schema_id, b.source_id, b.job_id,- b.run_uuid, b.batch_index, b.s3_path, b.row_count, b.byte_size,- b.is_final_batch, b.total_batches, b.total_rows, b.sync_type,- b.cumulative_row_count, b.resource_name, b.is_resume,- b.is_first_ever_sync, b.metadata,- COALESCE(s.attempt, 0) AS latest_attempt,- b.created_at+ {pending_batch_select_columns("s")}FROM {BATCH_TABLE} bJOIN {STATUS_VIEW} s ON b.id = s.batch_idWHERE@@ -445,8 +458,4 @@ class BatchQueue:only acquired on rows that actually appear in the result set, soone unlock per row balances the depth exactly."""- for batch in batches:- await conn.execute(- "SELECT pg_advisory_unlock(%(ns)s, hashtext(%(key)s))",- {"ns": ADVISORY_LOCK_NAMESPACE, "key": f"{batch.team_id}:{batch.schema_id}"},- )+ await unlock_advisory_locks(conn, batches=batches, namespace=ADVISORY_LOCK_NAMESPACE)diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.pyindex 3fb562b25bfa..4b9ad3f4da89 100644--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/metrics.py@@ -1,3 +1,5 @@+from dataclasses import dataclass+from prometheus_client import Counter, Gauge, HistogramBATCHES_PROCESSED_TOTAL = Counter(@@ -53,3 +55,89 @@ RUNS_RECONCILED_TOTAL = Counter("Runs whose ExternalDataJob was left non-terminal despite a failed queue batch and ""was reconciled to Failed by the reconcile sweep",)+++@dataclass(frozen=True)+class ConsumerMetrics:+ """The metric set the shared batch-consumer engine emits.++ The Delta consumer keeps the historical un-prefixed ``warehouse_pg_consumer_*``+ names; other sinks get their own families via :func:`make_consumer_metrics` so+ dashboards, alerts, and KEDA queries never conflate two consumers' series.+ """++ batches_processed_total: Counter+ batch_processing_duration_seconds: Histogram+ batch_retry_total: Counter+ runs_failed_total: Counter+ poll_duration_seconds: Histogram+ poll_batches_fetched: Histogram+ active_groups: Gauge+ recovery_sweeps_total: Counter+++DELTA_CONSUMER_METRICS = ConsumerMetrics(+ batches_processed_total=BATCHES_PROCESSED_TOTAL,+ batch_processing_duration_seconds=BATCH_PROCESSING_DURATION_SECONDS,+ batch_retry_total=BATCH_RETRY_TOTAL,+ runs_failed_total=RUNS_FAILED_TOTAL,+ poll_duration_seconds=POLL_DURATION_SECONDS,+ poll_batches_fetched=POLL_BATCHES_FETCHED,+ active_groups=ACTIVE_GROUPS,+ recovery_sweeps_total=RECOVERY_SWEEPS_TOTAL,+)++_metrics_by_prefix: dict[str, ConsumerMetrics] = {}+++def make_consumer_metrics(prefix: str) -> ConsumerMetrics:+ """Build (once per process) the engine metric set under ``{prefix}_pg_consumer_*``."""+ existing = _metrics_by_prefix.get(prefix)+ if existing is not None:+ return existing++ p = f"{prefix}_pg_consumer"+ metrics = ConsumerMetrics(+ batches_processed_total=Counter(+ f"{p}_batches_processed_total",+ f"Total batches processed by the {prefix} Postgres consumer",+ labelnames=["team_id", "schema_id", "status"],+ ),+ batch_processing_duration_seconds=Histogram(+ f"{p}_batch_processing_duration_seconds",+ "Duration of individual batch processing",+ labelnames=["team_id", "schema_id"],+ buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),+ ),+ batch_retry_total=Counter(+ f"{p}_batch_retry_total",+ "Total batch retry attempts",+ labelnames=["attempt", "error_type"],+ ),+ runs_failed_total=Counter(+ f"{p}_runs_failed_total",+ "Total runs fully failed via fail_run()",+ ),+ poll_duration_seconds=Histogram(+ f"{p}_poll_duration_seconds",+ "Duration of Postgres poll queries",+ buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0),+ ),+ poll_batches_fetched=Histogram(+ f"{p}_poll_batches_fetched",+ "Number of batches returned per poll cycle",+ buckets=(0, 1, 5, 10, 25, 50, 100, 250, 500),+ ),+ active_groups=Gauge(+ f"{p}_active_groups",+ "Number of (team_id, schema_id) groups currently being processed",+ multiprocess_mode="livesum",+ ),+ recovery_sweeps_total=Counter(+ f"{p}_recovery_sweeps_total",+ "Total recovery sweeps executed",+ labelnames=["outcome"],+ ),+ )+ _metrics_by_prefix[prefix] = metrics+ return metricsdiff --git a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.pyindex 7164c0102ccd..e1476d0cd29b 100644--- a/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/ducklake/ducklake_copy_data_imports_workflow.py@@ -45,6 +45,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.data_imports.pipelines.pipeline_v3.duckgres.enablement import DUCKGRES_BATCH_SINK_FLAGfrom posthog.temporal.ducklake.metrics import (get_ducklake_copy_data_imports_finished_metric,get_ducklake_copy_data_imports_verification_metric,@@ -155,6 +156,28 @@ async def ducklake_copy_data_imports_gate_activity(inputs: DuckLakeCopyWorkflowGawait logger.aerror("Team does not exist when evaluating DuckLake data imports gate")return False+ # Mutual exclusion with the Duckgres v3 batch sink: both writers target the+ # same posthog_data_imports_team_{id} tables with zero coordination, so a+ # team must never have both enabled. The sink wins.+ try:+ if posthoganalytics.feature_enabled(+ DUCKGRES_BATCH_SINK_FLAG,+ str(team.uuid),+ groups={+ "organization": str(team.organization_id),+ "project": str(team.id),+ },+ send_feature_flag_events=False,+ ):+ await logger.ainfo("DuckLake copy workflow skipped: duckgres batch sink owns this team's tables")+ return False+ except Exception as error:+ await logger.awarning(+ "Failed to evaluate duckgres batch sink flag; continuing with copy-workflow gate",+ error=str(error),+ )+ capture_exception(error)+try:return posthoganalytics.feature_enabled("ducklake-data-imports-copy-workflow",diff --git a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.pyindex 80979cf28c75..7018567d1a26 100644--- a/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py+++ b/posthog/temporal/tests/ducklake/test_ducklake_copy_data_imports_workflow.py@@ -89,6 +89,9 @@ async def test_ducklake_copy_data_imports_gate_respects_feature_flag(monkeypatchonly_evaluate_locally=False,send_feature_flag_events=True,):+ if key == "duckgres-batch-sink":+ # The sink-exclusion check runs first; this team is not sink-enabled.+ return Falsecaptured["key"] = keycaptured["distinct_id"] = distinct_idcaptured["groups"] = groups@@ -112,6 +115,25 @@ async def test_ducklake_copy_data_imports_gate_respects_feature_flag(monkeypatchassert captured["send_feature_flag_events"] is False+async def test_ducklake_copy_data_imports_gate_skips_duckgres_sink_teams(monkeypatch, ateam):+ """A team on the duckgres batch sink must never also run the copy workflow."""++ def fake_feature_enabled(key, distinct_id, **kwargs):+ # Both flags enabled: the sink exclusion must win.+ return True++ monkeypatch.setattr(+ "posthog.temporal.ducklake.ducklake_copy_data_imports_workflow.posthoganalytics.feature_enabled",+ fake_feature_enabled,+ )++ result = await ducklake_copy_data_imports_gate_activity(DuckLakeCopyWorkflowGateInputs(team_id=ateam.id))++ assert result is False++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_prepare_data_imports_ducklake_metadata_activity_basic(ateam, monkeypatch):@@ -1086,7 +1108,9 @@ async def test_ducklake_copy_data_imports_workflow_runs_when_feature_flag_enablemonkeypatch.setattr(ducklake_module.posthoganalytics,"feature_enabled",- lambda *args, **kwargs: True,+ # Key-aware: the gate checks the duckgres-batch-sink exclusion first,+ # and a catch-all True would wrongly trip it.+ lambda key, *args, **kwargs: key == "ducklake-data-imports-copy-workflow",)monkeypatch.setattr(ducklake_module, "prepare_data_imports_ducklake_metadata_activity", metadata_stub)monkeypatch.setattr(ducklake_module, "copy_data_imports_to_ducklake_activity", copy_stub)@@ -1176,7 +1200,9 @@ async def test_ducklake_copy_data_imports_workflow_calls_cleanup_after_verify(momonkeypatch.setattr(ducklake_module.posthoganalytics,"feature_enabled",- lambda *args, **kwargs: True,+ # Key-aware: the gate checks the duckgres-batch-sink exclusion first,+ # and a catch-all True would wrongly trip it.+ lambda key, *args, **kwargs: key == "ducklake-data-imports-copy-workflow",)monkeypatch.setattr(ducklake_module, "prepare_data_imports_ducklake_metadata_activity", metadata_stub)monkeypatch.setattr(ducklake_module, "copy_data_imports_to_ducklake_activity", copy_stub)diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.pyindex efa265d60dc7..1fb849ea5371 100644--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py@@ -12,10 +12,17 @@ import temporalio.activitylogger = structlog.get_logger(__name__)-PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus"]+PARTITIONED_TABLES = ["sourcebatch", "sourcebatchstatus", "sourcebatchduckgresstatus"]PARTITIONS_AHEAD = 7RETENTION_DAYS = 7+# The duckgres apply-marker table is unpartitioned (small rows, UNIQUE-constrained),+# so retention is DELETE-based. Must comfortably exceed the consumers' eligibility+# window (PARTITION_PRUNING_INTERVAL, 14d): the duckgres ordering gate and+# has_applied idempotency read apply rows for everything still eligible.+DUCKGRES_APPLY_TABLE = "sourcebatchduckgresapply"+DUCKGRES_APPLY_RETENTION_DAYS = 30+@dataclass(frozen=True, slots=True)class PartitionResult:@@ -83,6 +90,17 @@ async def manage_warehouse_sources_queue_partitions() -> dict:_verify_partitions(conn, today, errors)+ try:+ cursor = conn.execute(+ f"DELETE FROM {DUCKGRES_APPLY_TABLE} "+ f"WHERE created_at < now() - interval '{DUCKGRES_APPLY_RETENTION_DAYS} days'"+ )+ if cursor.rowcount:+ logger.info("duckgres_apply_markers_pruned", count=cursor.rowcount)+ except Exception as e:+ errors.append(f"Failed to prune {DUCKGRES_APPLY_TABLE}: {e}")+ logger.exception("Failed to prune duckgres apply markers")+s3_deleted = _cleanup_old_s3_extractions(today, errors)result = PartitionResult(ensured=ensured, dropped=dropped, errors=errors, s3_deleted=s3_deleted)diff --git a/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.py b/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.pynew file mode 100644index 000000000000..1e84109f8978--- /dev/null+++ b/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.py@@ -0,0 +1,184 @@+import django.db.models.manager+import django.db.models.deletion+from django.db import migrations, models++from posthog.models.utils import uuid7++PARTITIONS_AHEAD = 7+++def _create_duckgres_tables(apps, schema_editor):+ schema_editor.execute("""+ CREATE TABLE sourcebatchduckgresstatus (+ id UUID NOT NULL DEFAULT gen_random_uuid(),+ batch_id UUID NOT NULL,+ job_state VARCHAR(32) NOT NULL,+ attempt SMALLINT NOT NULL DEFAULT 0,+ exec_time TIMESTAMPTZ,+ error_response JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (id, created_at)+ ) PARTITION BY RANGE (created_at);++ CREATE INDEX sbdgs_batch_desc_state_idx+ ON sourcebatchduckgresstatus (batch_id, created_at DESC, id DESC, job_state);++ CREATE TABLE sourcebatchduckgresstatus_default PARTITION OF sourcebatchduckgresstatus DEFAULT;+ """)++ schema_editor.execute("""+ CREATE TABLE sourcebatchduckgresapply (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ team_id BIGINT NOT NULL,+ schema_id VARCHAR(200) NOT NULL,+ run_uuid VARCHAR(200) NOT NULL,+ batch_index INT NOT NULL,+ batch_id UUID NOT NULL,+ row_count INT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT sbdga_unique_batch_apply UNIQUE (team_id, schema_id, run_uuid, batch_index)+ );++ CREATE INDEX sbdga_run_idx+ ON sourcebatchduckgresapply (team_id, schema_id, run_uuid);++ CREATE INDEX sbdga_team_id_idx+ ON sourcebatchduckgresapply (team_id);+ """)++ schema_editor.execute(f"""+ DO $$+ DECLARE+ d DATE;+ BEGIN+ FOR d IN SELECT generate_series(+ CURRENT_DATE,+ CURRENT_DATE + {PARTITIONS_AHEAD},+ '1 day'::interval+ )::date+ LOOP+ EXECUTE format(+ 'CREATE TABLE IF NOT EXISTS sourcebatchduckgresstatus_%%s '+ 'PARTITION OF sourcebatchduckgresstatus '+ 'FOR VALUES FROM (%%L) TO (%%L)',+ to_char(d, 'YYYYMMDD'), d, d + 1+ );+ END LOOP;+ END $$;+ """)+++def _create_latest_duckgres_status_view(apps, schema_editor):+ schema_editor.execute("""+ CREATE VIEW v_latest_source_batch_duckgres_status AS+ SELECT DISTINCT ON (batch_id) *+ FROM sourcebatchduckgresstatus+ ORDER BY batch_id ASC, created_at DESC, id DESC+ """)+++def _drop_duckgres_tables(apps, schema_editor):+ schema_editor.execute("DROP VIEW IF EXISTS v_latest_source_batch_duckgres_status")+ schema_editor.execute("DROP TABLE IF EXISTS sourcebatchduckgresapply CASCADE")+ schema_editor.execute("DROP TABLE IF EXISTS sourcebatchduckgresstatus CASCADE")+++class Migration(migrations.Migration):+ dependencies = [+ ("warehouse_sources_queue", "0002_sourcebatch_run_uuid_batch_index_idx"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.CreateModel(+ name="SourceBatchDuckgresStatus",+ fields=[+ (+ "id",+ models.UUIDField(default=uuid7, editable=False, primary_key=True, serialize=False),+ ),+ (+ "job_state",+ models.CharField(+ choices=[+ ("executing", "executing"),+ ("succeeded", "succeeded"),+ ("waiting_retry", "waiting_retry"),+ ("failed", "failed"),+ ],+ max_length=32,+ ),+ ),+ ("attempt", models.SmallIntegerField(default=0)),+ ("exec_time", models.DateTimeField(blank=True, null=True)),+ ("error_response", models.JSONField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "batch",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.DO_NOTHING,+ related_name="duckgres_statuses",+ to="warehouse_sources_queue.sourcebatch",+ ),+ ),+ ],+ options={+ "db_table": "sourcebatchduckgresstatus",+ "indexes": [+ models.Index(+ fields=["batch_id", "-created_at", "-id", "job_state"],+ name="sbdgs_batch_desc_state_idx",+ )+ ],+ },+ ),+ migrations.CreateModel(+ name="SourceBatchDuckgresApply",+ fields=[+ (+ "id",+ models.UUIDField(default=uuid7, editable=False, primary_key=True, serialize=False),+ ),+ ("team_id", models.BigIntegerField(db_index=True)),+ ("schema_id", models.CharField(max_length=200)),+ ("run_uuid", models.CharField(max_length=200)),+ ("batch_index", models.IntegerField()),+ ("row_count", models.IntegerField()),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "batch",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.DO_NOTHING,+ related_name="duckgres_applies",+ to="warehouse_sources_queue.sourcebatch",+ ),+ ),+ ],+ options={+ "db_table": "sourcebatchduckgresapply",+ "indexes": [models.Index(fields=["team_id", "schema_id", "run_uuid"], name="sbdga_run_idx")],+ "constraints": [+ models.UniqueConstraint(+ fields=("team_id", "schema_id", "run_uuid", "batch_index"),+ name="sbdga_unique_batch_apply",+ )+ ],+ },+ managers=[+ ("all_teams", django.db.models.manager.Manager()),+ ],+ ),+ ],+ database_operations=[],+ ),+ migrations.RunPython(_create_duckgres_tables, _drop_duckgres_tables),+ migrations.RunPython(+ _create_latest_duckgres_status_view,+ lambda apps, schema_editor: schema_editor.execute(+ "DROP VIEW IF EXISTS v_latest_source_batch_duckgres_status"+ ),+ ),+ ]diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txtindex 8d5811080b8a..0d9e5787f4a4 100644--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_sourcebatch_run_uuid_batch_index_idx+0003_duckgres_sinkdiff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.pyindex 442b322fa182..e9b0e7f64938 100644--- a/products/warehouse_sources_queue/backend/models.py+++ b/products/warehouse_sources_queue/backend/models.py@@ -1,5 +1,6 @@from django.db import models+from posthog.models.scoping.product_mixin import ProductTeamModelfrom posthog.models.utils import UUIDModel, sane_repr@@ -82,3 +83,58 @@ class SourceBatchStatus(UUIDModel):name="sbs_batch_id_desc_state_idx",),]+++class SourceBatchDuckgresStatus(UUIDModel):+ class State(models.TextChoices):+ EXECUTING = "executing", "executing"+ SUCCEEDED = "succeeded", "succeeded"+ WAITING_RETRY = "waiting_retry", "waiting_retry"+ FAILED = "failed", "failed"++ batch = models.ForeignKey(+ SourceBatch,+ on_delete=models.DO_NOTHING,+ db_constraint=False,+ related_name="duckgres_statuses",+ )+ job_state = models.CharField(max_length=32, choices=State.choices)+ attempt = models.SmallIntegerField(default=0)+ exec_time = models.DateTimeField(null=True, blank=True)+ error_response = models.JSONField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "sourcebatchduckgresstatus"+ indexes = [+ models.Index(+ fields=["batch_id", "-created_at", "-id", "job_state"],+ name="sbdgs_batch_desc_state_idx",+ ),+ ]+++class SourceBatchDuckgresApply(ProductTeamModel, UUIDModel):+ schema_id = models.CharField(max_length=200)+ run_uuid = models.CharField(max_length=200)+ batch_index = models.IntegerField()+ batch = models.ForeignKey(+ SourceBatch,+ on_delete=models.DO_NOTHING,+ db_constraint=False,+ related_name="duckgres_applies",+ )+ row_count = models.IntegerField()+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ db_table = "sourcebatchduckgresapply"+ constraints = [+ models.UniqueConstraint(+ fields=["team_id", "schema_id", "run_uuid", "batch_index"],+ name="sbdga_unique_batch_apply",+ )+ ]+ indexes = [+ models.Index(fields=["team_id", "schema_id", "run_uuid"], name="sbdga_run_idx"),+ ]diff --git a/products/warehouse_sources_queue/backend/tests/test_models.py b/products/warehouse_sources_queue/backend/tests/test_models.pyindex 0039783664fe..2f74a2ecca7d 100644--- a/products/warehouse_sources_queue/backend/tests/test_models.py+++ b/products/warehouse_sources_queue/backend/tests/test_models.py@@ -1,4 +1,11 @@-from products.warehouse_sources_queue.backend.models import SourceBatch, SourceBatchStatus+from django.db.models import UniqueConstraint++from products.warehouse_sources_queue.backend.models import (+ SourceBatch,+ SourceBatchDuckgresApply,+ SourceBatchDuckgresStatus,+ SourceBatchStatus,+)class TestSourceBatchModel:@@ -21,3 +28,35 @@ class TestSourceBatchStatusModel:def test_batch_fk_has_no_db_constraint(self):field = SourceBatchStatus._meta.get_field("batch")assert not field.db_constraint # type: ignore[attr-defined]+++class TestSourceBatchDuckgresStatusModel:+ def test_state_choices(self):+ values = {c.value for c in SourceBatchDuckgresStatus.State}+ assert values == {"executing", "succeeded", "waiting_retry", "failed"}++ def test_db_table(self):+ assert SourceBatchDuckgresStatus._meta.db_table == "sourcebatchduckgresstatus"++ def test_batch_fk_has_no_db_constraint(self):+ field = SourceBatchDuckgresStatus._meta.get_field("batch")+ assert not field.db_constraint # type: ignore[attr-defined]+++class TestSourceBatchDuckgresApplyModel:+ def test_db_table(self):+ assert SourceBatchDuckgresApply._meta.db_table == "sourcebatchduckgresapply"++ def test_batch_fk_has_no_db_constraint(self):+ field = SourceBatchDuckgresApply._meta.get_field("batch")+ assert not field.db_constraint # type: ignore[attr-defined]++ def test_unique_constraint_matches_apply_key(self):+ constraint = next(+ constraint+ for constraint in SourceBatchDuckgresApply._meta.constraints+ if constraint.name == "sbdga_unique_batch_apply"+ )++ assert isinstance(constraint, UniqueConstraint)+ assert tuple(constraint.fields) == ("team_id", "schema_id", "run_uuid", "batch_index")