: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): instrument duckgres sink apply-phase timing (#67472)
Eric Duong1cc2c18b0a5f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.pyindex 566b56dfba46..7d32f1441cc3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/processor.py@@ -1,5 +1,8 @@from __future__ import annotations+import time+from collections.abc import Iterator+from contextlib import contextmanagerfrom dataclasses import dataclassfrom typing import Any, Literal@@ -8,6 +11,7 @@ from django.db import close_old_connectionsimport psycopgimport structlog+from prometheus_client import Histogramfrom psycopg import sqlfrom posthog.ducklake.common import duckgres_data_imports_schema, get_duckgres_config_for_org@@ -32,6 +36,41 @@ APPLY_MARKER_RETENTION_DAYS = 30EXTRACT_READ_SECRET_NAME = "posthog_extract_read"+# Per-batch apply latency, split by phase and kind. Fine buckets on purpose: the+# shared engine histogram (batch_processing_duration_seconds) floors at 0.5s, so+# this is the only place sub-second live-apply latency and the backfill phase+# breakdown (schema_read vs data_load vs swap) are observable.+_PHASE_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0)++APPLY_PHASE_DURATION_SECONDS = Histogram(+ "duckgres_sink_apply_phase_duration_seconds",+ "Duckgres sink per-batch apply latency by phase (connect_setup, schema_read, data_load/apply, swap) and kind (live/backfill)",+ labelnames=["phase", "kind"],+ buckets=_PHASE_BUCKETS,+)++BACKFILL_CHUNK_FILES = Histogram(+ "duckgres_sink_backfill_chunk_files",+ "Source parquet files per backfill chunk — drives read_parquet/union_by_name footer-read cost",+ buckets=(1, 2, 5, 10, 25, 50, 100, 200, 350, 512),+)+++def _record_phase(phase: str, kind: str, elapsed: float, acc: dict[str, float]) -> None:+ """Observe a phase's wall time on the histogram and record it (ms) into ``acc`` for logging."""+ APPLY_PHASE_DURATION_SECONDS.labels(phase=phase, kind=kind).observe(elapsed)+ acc[phase] = round(elapsed * 1000, 1)+++@contextmanager+def _timed(phase: str, kind: str, acc: dict[str, float]) -> Iterator[None]:+ """Time a block and record the phase even if it raises (mirrors error-path capture)."""+ start = time.monotonic()+ try:+ yield+ finally:+ _record_phase(phase, kind, time.monotonic() - start, acc)+class DuckgresBatchAlreadyAppliedError(Exception):"""A concurrent processor applied this batch first; our write was rolled back."""@@ -72,29 +111,41 @@ def process_batch(batch: PendingBatch) -> None:raise ValueError(f"ExternalDataJob {batch.job_id} has no schema")schema = job.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:- if _is_backfill_batch(batch):- _process_backfill_batch(conn, batch, schema)- else:- _process_batch(conn, batch, schema)- except DuckgresBatchAlreadyAppliedError:- # A concurrent processor (lost advisory-lock session + recovery sweep)- # won the marker insert; its committed write is the canonical one and- # 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,- )+ kind = "backfill" if _is_backfill_batch(batch) else "live"+ timings: dict[str, float] = {}+ # Fresh connect + session + secret is per-batch fixed cost; measured as one+ # phase so the connection-reuse trade-off is visible against the apply itself.+ # Recorded in a finally so a slow/failing connect (e.g. cold-tenant activation+ # timeout) still lands in the phase metric, matching the _timed error-path capture.+ connect_start = time.monotonic()+ try:+ 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)+ _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)+ try:+ if kind == "backfill":+ _process_backfill_batch(conn, batch, schema, timings=timings)+ else:+ _process_batch(conn, batch, schema, timings=timings)+ 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,+ )+ finally:+ if "connect_setup" not in timings:+ _record_phase("connect_setup", kind, time.monotonic() - connect_start, timings)def _connect_to_duckgres(team_id: int) -> psycopg.Connection[Any]:@@ -200,7 +251,13 @@ def _backfill_table_name(live_table: str, schema_id: str) -> str:return f"{live_table[:42]}__bf_{schema_id.replace('-', '')[:8]}"-def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: ExternalDataSchema) -> None:+def _process_batch(+ conn: psycopg.Connection[Any],+ batch: PendingBatch,+ schema: ExternalDataSchema,+ timings: dict[str, float] | None = None,+) -> None:+ timings = timings if timings is not None else {}duckgres_schema = _duckgres_schema_name(batch.team_id)duckgres_table = _duckgres_table_name(schema)@@ -224,7 +281,8 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: E)return- parquet_schema = _read_parquet_schema(conn, [batch.s3_path])+ with _timed("schema_read", "live", timings):+ parquet_schema = _read_parquet_schema(conn, [batch.s3_path])columns = [column.name for column in parquet_schema]operation = _plan_batch_operation(conn,@@ -242,7 +300,7 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: Etable=duckgres_table,)- with conn.transaction():+ with _timed("apply", "live", timings), conn.transaction():if operation.ensure_target_columns:_ensure_target_columns(conn, duckgres_schema, duckgres_table, parquet_schema)_apply_batch_operation(@@ -257,13 +315,19 @@ def _process_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: Ereturn-def _process_backfill_batch(conn: psycopg.Connection[Any], batch: PendingBatch, schema: ExternalDataSchema) -> None:+def _process_backfill_batch(+ conn: psycopg.Connection[Any],+ batch: PendingBatch,+ schema: ExternalDataSchema,+ timings: dict[str, float] | None = None,+) -> None:"""Apply one backfill chunk into <table>__backfill; the last chunk swaps it live.See BACKFILL_SPEC.md. The swap (DROP live + RENAME) shares the last chunk'stransaction together with the apply-marker arbiter, so it is atomic andexactly-once even with a concurrent processor."""+ timings = timings if timings is not None else {}duckgres_schema = _duckgres_schema_name(batch.team_id)live_table = _duckgres_table_name(schema)backfill_table = _backfill_table_name(live_table, batch.schema_id)@@ -293,22 +357,25 @@ def _process_backfill_batch(conn: psycopg.Connection[Any], batch: PendingBatch,returnchunk_paths = _backfill_chunk_paths(batch)- parquet_schema = _read_parquet_schema(conn, chunk_paths, union_by_name=True)+ BACKFILL_CHUNK_FILES.observe(len(chunk_paths))+ with _timed("schema_read", "backfill", timings):+ parquet_schema = _read_parquet_schema(conn, chunk_paths, union_by_name=True)columns = [column.name for column in parquet_schema]with conn.transaction():- if batch.batch_index == 0:- # CREATE OR REPLACE makes a re-planned backfill self-cleaning.- conn.execute(- sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(backfill_table),- _read_parquet_expr(chunk_paths, union_by_name=True),+ with _timed("data_load", "backfill", timings):+ if batch.batch_index == 0:+ # CREATE OR REPLACE makes a re-planned backfill self-cleaning.+ conn.execute(+ sql.SQL("CREATE OR REPLACE TABLE {}.{} AS SELECT * FROM {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(backfill_table),+ _read_parquet_expr(chunk_paths, union_by_name=True),+ ))- )- else:- _ensure_target_columns(conn, duckgres_schema, backfill_table, parquet_schema)- _insert_batch(conn, duckgres_schema, backfill_table, chunk_paths, columns, union_by_name=True)+ else:+ _ensure_target_columns(conn, duckgres_schema, backfill_table, parquet_schema)+ _insert_batch(conn, duckgres_schema, backfill_table, chunk_paths, columns, union_by_name=True)if is_last:logger.info(@@ -319,21 +386,37 @@ def _process_backfill_batch(conn: psycopg.Connection[Any], batch: PendingBatch,table=live_table,chunk_count=chunk_count,)- conn.execute(- sql.SQL("DROP TABLE IF EXISTS {}.{}").format(- sql.Identifier(duckgres_schema), sql.Identifier(live_table)+ with _timed("swap", "backfill", timings):+ conn.execute(+ sql.SQL("DROP TABLE IF EXISTS {}.{}").format(+ sql.Identifier(duckgres_schema), sql.Identifier(live_table)+ ))- )- conn.execute(- sql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(- sql.Identifier(duckgres_schema),- sql.Identifier(backfill_table),- sql.Identifier(live_table),+ conn.execute(+ sql.SQL("ALTER TABLE {}.{} RENAME TO {}").format(+ sql.Identifier(duckgres_schema),+ sql.Identifier(backfill_table),+ sql.Identifier(live_table),+ ))- )_mark_duckgres_batch_applied(conn, duckgres_schema, batch=batch)+ logger.info(+ "duckgres_backfill_chunk_timing",+ team_id=batch.team_id,+ schema_id=batch.schema_id,+ run_uuid=batch.run_uuid,+ batch_index=batch.batch_index,+ chunk_count=chunk_count,+ is_last=is_last,+ file_count=len(chunk_paths),+ connect_setup_ms=timings.get("connect_setup"),+ schema_read_ms=timings.get("schema_read"),+ data_load_ms=timings.get("data_load"),+ swap_ms=timings.get("swap"),+ )+if is_last:from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.backfill import (mark_primed,