: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(ducklake): add operational metrics (#76379)
Eric Duong11d7cb7587d0
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 7fea42114b44..9aa4630ce5bc 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -94,6 +94,7 @@ from products.managed_warehouse.backend.facade.api import ()from products.managed_warehouse.backend.facade.client import make_duckgres_conninfofrom products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTeamMembership+from products.managed_warehouse.backend.facade.metrics import record_duckling_backfill_workload, track_duckling_backfillfrom products.managed_warehouse.backend.facade.team_state import (list_enabled_backfill_team_memberships,resolve_events_persons_tables,@@ -2369,11 +2370,12 @@ def register_persons_files_with_duckling(tags={"owner": JobOwners.TEAM_MANAGED_WAREHOUSE.value, **EVENTS_CONCURRENCY_TAG},)def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:- team_id, _ = parse_partition_key_dates(context.partition_key)+ team_id, dates = parse_partition_key_dates(context.partition_key)if config.dry_run:_run_duckling_events_backfill(context, config)return+ mode = "monthly" if len(dates) > 1 else "daily"run_id = context.run.run_idrecord_backfill_started(team_id=team_id,@@ -2381,24 +2383,29 @@ def duckling_events_backfill(context: AssetExecutionContext, config: DucklingBacpartition_key=context.partition_key,run_id=run_id,)- try:- _run_duckling_events_backfill(context, config)- except Exception as error:+ with track_duckling_backfill(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,+ mode=mode,+ ):+ try:+ _run_duckling_events_backfill(context, config)+ except Exception as error:+ record_backfill_finished(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,+ partition_key=context.partition_key,+ run_id=run_id,+ error=error,+ )+ raise+record_backfill_finished(team_id=team_id,dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,partition_key=context.partition_key,run_id=run_id,- error=error,)- raise-- record_backfill_finished(- team_id=team_id,- dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,- partition_key=context.partition_key,- run_id=run_id,- )def _run_duckling_events_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:@@ -2550,6 +2557,14 @@ def _run_duckling_events_backfill(context: AssetExecutionContext, config: Duckli"bucket": target.bucket,})+ if not config.dry_run:+ record_duckling_backfill_workload(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.EVENTS,+ mode="monthly" if len(dates) > 1 else "daily",+ files_registered=total_registered,+ partitions_exported=days_exported,+ )context.log.info(f"Completed duckling backfill for team_id={team_id}: "@@ -2589,24 +2604,30 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBapartition_key=partition_key,run_id=run_id,)- try:- _run_duckling_persons_backfill(context, config)- except Exception as error:+ mode = "full" if is_full_export_partition(partition_key) else "daily"+ with track_duckling_backfill(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,+ mode=mode,+ ):+ try:+ _run_duckling_persons_backfill(context, config)+ except Exception as error:+ record_backfill_finished(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,+ partition_key=partition_key,+ run_id=run_id,+ error=error,+ )+ raise+record_backfill_finished(team_id=team_id,dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,partition_key=partition_key,run_id=run_id,- error=error,)- raise-- record_backfill_finished(- team_id=team_id,- dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,- partition_key=partition_key,- run_id=run_id,- )def _run_duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBackfillConfig) -> None:@@ -2749,6 +2770,14 @@ def _run_duckling_persons_backfill(context: AssetExecutionContext, config: Duckl"bucket": target.bucket,})+ if not config.dry_run:+ record_duckling_backfill_workload(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,+ mode="full",+ files_registered=files_registered,+ partitions_exported=int(bool(s3_glob)),+ )context.log.info(f"Completed duckling persons full backfill for team_id={team_id}: {files_registered} files registered"@@ -2827,6 +2856,14 @@ def _run_duckling_persons_backfill(context: AssetExecutionContext, config: Duckl"bucket": target.bucket,})+ if not config.dry_run:+ record_duckling_backfill_workload(+ team_id=team_id,+ dataset=ManagedWarehouseBackfillPartition.Dataset.PERSONS,+ mode="daily",+ files_registered=total_registered,+ partitions_exported=days_exported,+ )context.log.info(f"Completed duckling persons daily backfill for team_id={team_id}: "diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.pyindex ee54739ddfad..e146a295152e 100644--- a/posthog/temporal/ai_observability/test_metrics.py+++ b/posthog/temporal/ai_observability/test_metrics.py@@ -75,6 +75,28 @@ class TestExecutionTimeRecorder:assert call_args["status"] == "SKIPPED"assert call_args["exception"] == ""+ def test_forwards_duration_and_terminal_attributes_to_recorder(self):+ mock_meter = MagicMock()+ mock_hist = MagicMock()+ histogram_recorder = MagicMock()+ mock_meter.create_histogram_timedelta.return_value = mock_hist++ with (+ patch("posthog.temporal.common.metrics.get_metric_meter", return_value=mock_meter),+ patch("posthog.temporal.common.metrics.time.perf_counter", side_effect=[1.0, 1.25]),+ ):+ with ExecutionTimeRecorder(+ "test_histogram",+ histogram_attributes={"stage": "copy"},+ histogram_recorder=histogram_recorder,+ ) as recorder:+ recorder.set_status("SKIPPED")++ histogram_recorder.assert_called_once_with(+ 250.0,+ {"stage": "copy", "status": "SKIPPED", "exception": ""},+ )+class TestEvalsMetricsInterceptor:def test_interceptor_creates_activity_interceptor(self):diff --git a/posthog/temporal/common/metrics.py b/posthog/temporal/common/metrics.pyindex f64ad3a3fccc..21c349201f29 100644--- a/posthog/temporal/common/metrics.py+++ b/posthog/temporal/common/metrics.py@@ -35,11 +35,13 @@ class ExecutionTimeRecorder:description: str | None = None,histogram_attributes: Attributes | None = None,log: bool = False,+ histogram_recorder: typing.Callable[[float, Attributes], None] | None = None,) -> None:self.histogram_name = histogram_nameself.description = descriptionself.histogram_attributes = histogram_attributes or {}self.log = log+ self.histogram_recorder = histogram_recorderself._start_counter: float | None = Noneself._status_override: str | None = None@@ -75,6 +77,8 @@ class ExecutionTimeRecorder:meter = get_metric_meter(attributes)hist = meter.create_histogram_timedelta(name=self.histogram_name, description=self.description, unit="ms")hist.record(value=delta)+ if self.histogram_recorder is not None:+ self.histogram_recorder(float(delta_milli_seconds), attributes)except Exception:LOGGER.exception("Failed to record execution time to histogram '%s'", self.histogram_name)if self.log:diff --git a/products/managed_warehouse/backend/facade/metrics.py b/products/managed_warehouse/backend/facade/metrics.pynew file mode 100644index 000000000000..0b417e6cc603--- /dev/null+++ b/products/managed_warehouse/backend/facade/metrics.py@@ -0,0 +1,3 @@+from products.managed_warehouse.backend.metrics import record_duckling_backfill_workload, track_duckling_backfill++__all__ = ["record_duckling_backfill_workload", "track_duckling_backfill"]diff --git a/products/managed_warehouse/backend/metrics.py b/products/managed_warehouse/backend/metrics.pynew file mode 100644index 000000000000..33e6e4bf3997--- /dev/null+++ b/products/managed_warehouse/backend/metrics.py@@ -0,0 +1,120 @@+import time+from collections.abc import Iterator, Mapping+from contextlib import contextmanager++import posthoganalytics+from posthoganalytics.metrics_capture import PostHogMetrics+from temporalio import workflow++MetricAttributes = Mapping[str, str | int | float | bool]+++def _should_record() -> bool:+ return not (workflow.in_workflow() and workflow.unsafe.is_replaying())+++def _metrics() -> PostHogMetrics | None:+ client = posthoganalytics.default_client+ return client.metrics if client is not None else None+++def record_counter(+ name: str,+ value: int,+ attributes: MetricAttributes,+ *,+ unit: str | None = None,+) -> None:+ if not _should_record():+ return+ metrics = _metrics()+ if metrics is not None:+ metrics.count(name, value, unit=unit, attributes=dict(attributes))+++def record_histogram(+ name: str,+ value: float,+ attributes: MetricAttributes,+ *,+ unit: str,+) -> None:+ if not _should_record():+ return+ metrics = _metrics()+ if metrics is not None:+ metrics.histogram(name, value, unit=unit, attributes=dict(attributes))+++def record_gauge(+ name: str,+ value: float,+ attributes: MetricAttributes,+ *,+ unit: str | None = None,+) -> None:+ if not _should_record():+ return+ metrics = _metrics()+ if metrics is not None:+ metrics.gauge(name, value, unit=unit, attributes=dict(attributes))+++@contextmanager+def track_duckling_backfill(*, team_id: int, dataset: str, mode: str) -> Iterator[None]:+ attributes = {"team_id": str(team_id), "dataset": dataset, "mode": mode}+ record_counter(+ "warehouse.duckling.backfill.started",+ 1,+ attributes,+ )+ started_at = time.perf_counter()+ status = "failed"+ try:+ yield+ status = "completed"+ record_gauge(+ "warehouse.duckling.backfill.last.success.timestamp",+ time.time(),+ attributes,+ unit="s",+ )+ finally:+ terminal_attributes = {**attributes, "status": status}+ record_counter(+ "warehouse.duckling.backfill.finished",+ 1,+ terminal_attributes,+ )+ record_histogram(+ "warehouse.duckling.backfill.duration",+ time.perf_counter() - started_at,+ terminal_attributes,+ unit="s",+ )+ metrics = _metrics()+ if metrics is not None:+ metrics.flush()+++def record_duckling_backfill_workload(+ *,+ team_id: int,+ dataset: str,+ mode: str,+ files_registered: int,+ partitions_exported: int,+) -> None:+ attributes = {"team_id": str(team_id), "dataset": dataset, "mode": mode}+ record_histogram(+ "warehouse.duckling.backfill.files.registered",+ float(files_registered),+ attributes,+ unit="file",+ )+ record_histogram(+ "warehouse.duckling.backfill.partitions.exported",+ float(partitions_exported),+ attributes,+ unit="partition",+ )diff --git a/products/managed_warehouse/backend/storage.py b/products/managed_warehouse/backend/storage.pyindex 1a6cab3986bc..119facf66a2d 100644--- a/products/managed_warehouse/backend/storage.py+++ b/products/managed_warehouse/backend/storage.py@@ -511,33 +511,79 @@ def get_deltalake_storage_options(STAGING_PREFIX = "__posthog_staging"[email protected](frozen=True, kw_only=True)+class DeltaTableSnapshotWorkload:+ file_count: int+ row_count: int | None+ byte_count: int | None++[email protected](frozen=True, kw_only=True)+class StagedDeltaTable:+ staging_uri: str+ workload: DeltaTableSnapshotWorkload++def compute_staging_uri(source_uri: str, catalog_bucket: str) -> str:"""Place source key path under __posthog_staging/ in the catalog bucket."""key_path = urlparse(source_uri).path.lstrip("/")return f"s3://{catalog_bucket}/{STAGING_PREFIX}/{key_path}"-def _get_delta_snapshot_files(+def _get_delta_snapshot(source_uri: str,*,storage_config: DuckLakeStorageConfig | None = None,team_id: int | None = None,organization_id: str | None = None,-) -> tuple[int, list[str]]:- """Pin to the current Delta table version and return its data file S3 keys.+) -> tuple[int, list[str], DeltaTableSnapshotWorkload]:+ import deltalake- Opens the Delta table at *source_uri* using the deltalake library (which- reads the transaction log atomically), records the current version, and- converts the absolute ``file_uris()`` into plain S3 object keys.+ delta_table = deltalake.DeltaTable(+ table_uri=source_uri,+ storage_options=get_deltalake_storage_options(+ storage_config=storage_config,+ team_id=team_id,+ organization_id=organization_id,+ ),+ )+ version = delta_table.version()+ data_keys = [urlparse(uri).path.lstrip("/") for uri in delta_table.file_uris()]++ add_actions = delta_table.get_add_actions(flatten=True)+ column_names = add_actions.schema.names++ byte_count: int | None = None+ if "size_bytes" in column_names:+ sizes = add_actions.column("size_bytes").to_pylist()+ if all(size is not None for size in sizes):+ byte_count = sum(sizes)++ row_count: int | None = None+ if "num_records" in column_names:+ record_counts = add_actions.column("num_records").to_pylist()+ if all(record_count is not None for record_count in record_counts):+ row_count = sum(record_counts)++ workload = DeltaTableSnapshotWorkload(+ file_count=len(data_keys),+ row_count=row_count,+ byte_count=byte_count,+ )+ return version, data_keys, workload- Returns:- (version, data_file_keys) — version is the Delta log version that was- read; data_file_keys are S3 keys (no ``s3://bucket/`` prefix) for the- data files that belong to that version's snapshot.- """++def _get_delta_snapshot_files(+ source_uri: str,+ *,+ storage_config: DuckLakeStorageConfig | None = None,+ team_id: int | None = None,+ organization_id: str | None = None,+) -> tuple[int, list[str]]:+ """Pin to the current Delta table version and return its data file S3 keys."""import deltalake- dt = deltalake.DeltaTable(+ delta_table = deltalake.DeltaTable(table_uri=source_uri,storage_options=get_deltalake_storage_options(storage_config=storage_config,@@ -545,12 +591,25 @@ def _get_delta_snapshot_files(organization_id=organization_id,),)- version = dt.version()- keys: list[str] = []- for uri in dt.file_uris():- parsed = urlparse(uri)- keys.append(parsed.path.lstrip("/"))- return version, keys+ version = delta_table.version()+ data_keys = [urlparse(uri).path.lstrip("/") for uri in delta_table.file_uris()]+ return version, data_keys+++def get_delta_table_snapshot_workload(+ source_uri: str,+ *,+ storage_config: DuckLakeStorageConfig | None = None,+ team_id: int | None = None,+ organization_id: str | None = None,+) -> DeltaTableSnapshotWorkload:+ _, _, workload = _get_delta_snapshot(+ source_uri,+ storage_config=storage_config,+ team_id=team_id,+ organization_id=organization_id,+ )+ return workload_DELTA_LOG_VERSION_RE = re.compile(r"^(\d{20})\.")@@ -598,14 +657,36 @@ def stage_delta_table(team_id: int | None = None,organization_id: str | None = None,) -> str:- """Copy a version-pinned Delta table snapshot to the catalog bucket under __posthog_staging/.+ """Copy a version-pinned Delta table snapshot to the catalog staging prefix."""+ version, data_keys = _get_delta_snapshot_files(+ source_uri,+ storage_config=storage_config,+ team_id=team_id,+ organization_id=organization_id,+ )+ return _copy_delta_snapshot_to_staging(source_uri, catalog_bucket, version, data_keys)- Pins to the current Delta table version via the deltalake library, then- copies only the data files and log entries for that version (or earlier).- This prevents inconsistency when a new transaction commits during the copy.- Returns the staging URI for the Delta table.- """+def stage_delta_table_with_workload(+ source_uri: str,+ catalog_bucket: str,+ *,+ storage_config: DuckLakeStorageConfig | None = None,+ team_id: int | None = None,+ organization_id: str | None = None,+) -> StagedDeltaTable:+ """Stage a version-pinned Delta table and return its transaction-log workload."""+ version, data_keys, workload = _get_delta_snapshot(+ source_uri,+ storage_config=storage_config,+ team_id=team_id,+ organization_id=organization_id,+ )+ staging_uri = _copy_delta_snapshot_to_staging(source_uri, catalog_bucket, version, data_keys)+ return StagedDeltaTable(staging_uri=staging_uri, workload=workload)+++def _copy_delta_snapshot_to_staging(source_uri: str, catalog_bucket: str, version: int, data_keys: list[str]) -> str:from concurrent.futures import ThreadPoolExecutorimport boto3@@ -616,17 +697,8 @@ def stage_delta_table(if not source_prefix.endswith("/"):source_prefix += "/"- version, data_keys = _get_delta_snapshot_files(- source_uri,- storage_config=storage_config,- team_id=team_id,- organization_id=organization_id,- )-s3 = boto3.client("s3")-log_keys = _collect_delta_log_keys(s3, source_bucket, source_prefix, version)-objects_to_copy = data_keys + log_keysdef copy_one(key: str) -> None:diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.pyindex c3839108e819..41bfb069db3a 100644--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_imports_workflow.py@@ -23,6 +23,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.common.metrics import Attributes, ExecutionTimeRecorderfrom products.managed_warehouse.backend.common import (_get_org_id_for_team,@@ -40,25 +41,71 @@ from products.managed_warehouse.backend.logic.verification import (get_data_imports_verification_queries,)from products.managed_warehouse.backend.storage import (+ DeltaTableSnapshotWorkload,cleanup_staged_files,compute_staging_uri,configure_connection,connect_to_duckgres,create_staging_read_secret,ensure_ducklake_bucket_exists,+ get_delta_table_snapshot_workload,get_deltalake_storage_options,setup_duckgres_session,- stage_delta_table,+ stage_delta_table_with_workload,)from products.managed_warehouse.backend.temporal.metrics import (+ get_ducklake_copy_data_imports_bytes_metric,+ get_ducklake_copy_data_imports_duration_metric,+ get_ducklake_copy_data_imports_files_metric,get_ducklake_copy_data_imports_finished_metric,+ get_ducklake_copy_data_imports_last_success_metric,+ get_ducklake_copy_data_imports_rows_metric,+ get_ducklake_copy_data_imports_started_metric,get_ducklake_copy_data_imports_verification_metric,+ record_ducklake_copy_data_imports_stage_duration,)from products.warehouse_sources.backend.facade.models import ExternalDataSchemafrom products.warehouse_sources.backend.facade.pipelines import DUCKGRES_BATCH_SINK_FLAG, is_duckgres_sink_team_memberLOGGER = get_logger(__name__)DATA_IMPORTS_DUCKLAKE_WORKFLOW_PREFIX = "data_imports"+DUCKLAKE_COPY_DATA_IMPORTS_STAGE_DURATION_METRIC = "ducklake_copy_data_imports_stage_duration"+++def _stage_timer(*, stage: str, team_id: int, schema_id: str | None = None) -> ExecutionTimeRecorder:+ attributes: Attributes = {"stage": stage, "team_id": str(team_id)}+ if schema_id is not None:+ attributes["schema_id"] = schema_id+ return ExecutionTimeRecorder(+ DUCKLAKE_COPY_DATA_IMPORTS_STAGE_DURATION_METRIC,+ "Execution duration of one post-gate DuckLake data import copy stage.",+ attributes,+ log=True,+ histogram_recorder=record_ducklake_copy_data_imports_stage_duration,+ )+++def _bind_copy_activity_context(*, team_id: int, job_id: str, schema_id: str | None = None) -> None:+ identifiers: dict[str, str | int] = {"team_id": team_id, "job_id": job_id}+ if schema_id is not None:+ identifiers["schema_id"] = schema_id+ if activity.in_activity():+ workflow_id = activity.info().workflow_id+ if workflow_id is not None:+ identifiers["workflow_id"] = workflow_id+ bind_contextvars(**identifiers)+++def _record_copy_workload(*, team_id: int, schema_id: str, workload: DeltaTableSnapshotWorkload) -> None:+ get_ducklake_copy_data_imports_files_metric(team_id=team_id, schema_id=schema_id).record(float(workload.file_count))+ if workload.row_count is not None:+ get_ducklake_copy_data_imports_rows_metric(team_id=team_id, schema_id=schema_id).record(+ float(workload.row_count)+ )+ if workload.byte_count is not None:+ get_ducklake_copy_data_imports_bytes_metric(team_id=team_id, schema_id=schema_id).record(+ float(workload.byte_count)+ )class _VerificationCursor(typing.Protocol):@@ -199,9 +246,16 @@ async def prepare_data_imports_ducklake_metadata_activity(inputs: DataImportsDuckLakeCopyInputs,) -> list[DuckLakeCopyDataImportsMetadata]:"""Resolve data imports schemas referenced in the workflow inputs into copy-ready metadata."""- bind_contextvars(team_id=inputs.team_id)+ _bind_copy_activity_context(team_id=inputs.team_id, job_id=inputs.job_id)logger = LOGGER.bind()+ with _stage_timer(stage="prepare", team_id=inputs.team_id):+ return await _prepare_data_imports_ducklake_metadata(inputs, logger)+++async def _prepare_data_imports_ducklake_metadata(+ inputs: DataImportsDuckLakeCopyInputs, logger: typing.Any+) -> list[DuckLakeCopyDataImportsMetadata]:if not inputs.schema_ids:await logger.ainfo("DuckLake copy requested but no schema_ids were provided - skipping")return []@@ -290,9 +344,12 @@ async def prepare_data_imports_ducklake_metadata_activity(@activity.defn-def copy_data_imports_to_ducklake_activity(inputs: DuckLakeCopyDataImportsActivityInputs) -> None:+def copy_data_imports_to_ducklake_activity(+ inputs: DuckLakeCopyDataImportsActivityInputs,+) -> DeltaTableSnapshotWorkload:"""Copy a single data imports schema's Delta snapshot into DuckLake."""- bind_contextvars(team_id=inputs.team_id)+ schema_id = inputs.model.source_schema_id+ _bind_copy_activity_context(team_id=inputs.team_id, schema_id=schema_id, job_id=inputs.job_id)logger = LOGGER.bind(model_label=inputs.model.model_label, job_id=inputs.job_id)# This activity runs in a long-lived worker thread that never goes through Django's# request/response cycle, so a connection killed by the DB/proxy (e.g. after@@ -301,15 +358,17 @@ def copy_data_imports_to_ducklake_activity(inputs: DuckLakeCopyDataImportsActiviclose_old_connections()heartbeater = HeartbeaterSync(details=("ducklake_copy", inputs.model.model_label), logger=logger)- with heartbeater:+ with heartbeater, _stage_timer(stage="copy", team_id=inputs.team_id, schema_id=schema_id):if is_dev_mode():- _copy_data_imports_via_duckdb(inputs, logger)- else:- _copy_data_imports_via_duckgres(inputs, logger)+ return _copy_data_imports_via_duckdb(inputs, logger)+ return _copy_data_imports_via_duckgres(inputs, logger)-def _copy_data_imports_via_duckdb(inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any) -> None:+def _copy_data_imports_via_duckdb(+ inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any+) -> DeltaTableSnapshotWorkload:"""Create the DuckLake table directly from Delta using the local DuckDB client."""+ workload = get_delta_table_snapshot_workload(inputs.model.source_table_uri, team_id=inputs.team_id)alias = "ducklake"with duckdb.connect() as conn:config = get_config()@@ -332,6 +391,8 @@ def _copy_data_imports_via_duckdb(inputs: DuckLakeCopyDataImportsActivityInputs,)logger.info("Successfully materialized DuckLake table", ducklake_table=qualified_table)+ return workload+# A v3 full-refresh sync purges the source Delta table during extract and the# delta-load consumer rebuilds it asynchronously after the import job (and therefore@@ -351,7 +412,7 @@ def _is_delta_table_absent_error(error: Exception) -> bool:def _stage_delta_table_waiting_for_rebuild(*, source_uri: str, catalog_bucket: str, organization_id: str, logger: typing.Any-) -> None:+) -> DeltaTableSnapshotWorkload:"""Stage the source Delta table, waiting out the v3 full-refresh rebuild window.Only the two "table momentarily absent" signals are absorbed; every other error@@ -361,12 +422,12 @@ def _stage_delta_table_waiting_for_rebuild(deadline = time.monotonic() + DELTA_REBUILD_WAIT_SECONDSwhile True:try:- stage_delta_table(+ staged_table = stage_delta_table_with_workload(source_uri=source_uri,catalog_bucket=catalog_bucket,organization_id=organization_id,)- return+ return staged_table.workloadexcept Exception as error:if not _is_delta_table_absent_error(error) or time.monotonic() >= deadline:raise@@ -379,7 +440,9 @@ def _stage_delta_table_waiting_for_rebuild(time.sleep(DELTA_REBUILD_POLL_SECONDS)-def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any) -> None:+def _copy_data_imports_via_duckgres(+ inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any+) -> DeltaTableSnapshotWorkload:"""Stage Delta files and create the DuckLake table via duckgres."""org_id = _get_org_id_for_team(inputs.team_id)server = get_duckgres_server_for_organization(org_id)@@ -396,7 +459,7 @@ def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInputsource_uri=inputs.model.source_table_uri,staging_uri=inputs.model.staging_uri,)- _stage_delta_table_waiting_for_rebuild(+ workload = _stage_delta_table_waiting_for_rebuild(source_uri=inputs.model.source_table_uri,catalog_bucket=bucket,organization_id=org_id,@@ -421,26 +484,31 @@ def _copy_data_imports_via_duckgres(inputs: DuckLakeCopyDataImportsActivityInput)logger.info("Successfully materialized DuckLake table via duckgres", ducklake_table=table)+ return workload+@dataclasses.dataclassclass DuckLakeDataImportsStagingCleanupInputs:team_id: intstaging_uri: str+ schema_id: str | None = None+ job_id: str = ""@activity.defndef cleanup_data_imports_staging_activity(inputs: DuckLakeDataImportsStagingCleanupInputs) -> None:"""Clean up staged Delta files after successful verification."""- bind_contextvars(team_id=inputs.team_id)+ _bind_copy_activity_context(team_id=inputs.team_id, schema_id=inputs.schema_id, job_id=inputs.job_id)# Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity.if not settings.TEST:close_old_connections()- server = get_duckgres_server_by_team_org(inputs.team_id)- if server is None:- return- cleanup_staged_files(- staging_uri=inputs.staging_uri,- )+ with _stage_timer(stage="cleanup", team_id=inputs.team_id, schema_id=inputs.schema_id):+ server = get_duckgres_server_by_team_org(inputs.team_id)+ if server is None:+ return+ cleanup_staged_files(+ staging_uri=inputs.staging_uri,+ )def _data_imports_source_table_uri(schema: ExternalDataSchema) -> str:@@ -509,12 +577,20 @@ def verify_data_imports_ducklake_copy_activity(inputs: DuckLakeCopyDataImportsActivityInputs,) -> list[DuckLakeCopyDataImportsVerificationResult]:"""Run configured verification queries to ensure the copy matches the source."""- bind_contextvars(team_id=inputs.team_id)+ schema_id = inputs.model.source_schema_id+ _bind_copy_activity_context(team_id=inputs.team_id, schema_id=schema_id, job_id=inputs.job_id)logger = LOGGER.bind(model_label=inputs.model.model_label, job_id=inputs.job_id)# Same long-lived worker thread caveat as copy_data_imports_to_ducklake_activity.if not settings.TEST:close_old_connections()+ with _stage_timer(stage="verify", team_id=inputs.team_id, schema_id=schema_id):+ return _verify_data_imports_ducklake_copy(inputs, logger)+++def _verify_data_imports_ducklake_copy(+ inputs: DuckLakeCopyDataImportsActivityInputs, logger: typing.Any+) -> list[DuckLakeCopyDataImportsVerificationResult]:if not inputs.model.verification_queries:logger.info("No DuckLake verification queries configured - skipping")return []@@ -1002,6 +1078,8 @@ class DuckLakeCopyDataImportsWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: DataImportsDuckLakeCopyInputs) -> None:logger = LOGGER.bind(**inputs.properties_to_log)+ if workflow.in_workflow():+ logger = logger.bind(workflow_id=workflow.info().workflow_id)logger.info("Starting DuckLakeCopyDataImportsWorkflow")if not inputs.schema_ids:@@ -1019,25 +1097,28 @@ class DuckLakeCopyDataImportsWorkflow(PostHogWorkflow):logger.info("DuckLake copy workflow disabled by feature flag")return- model_list: list[DuckLakeCopyDataImportsMetadata] = await workflow.execute_activity(- prepare_data_imports_ducklake_metadata_activity,- inputs,- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ workflow_started_at = workflow.now()+ get_ducklake_copy_data_imports_started_metric(team_id=inputs.team_id).add(1)+ pending_staging_cleanup: list[DuckLakeDataImportsStagingCleanupInputs] = []+ status = "failed"+ try:+ model_list: list[DuckLakeCopyDataImportsMetadata] = await workflow.execute_activity(+ prepare_data_imports_ducklake_metadata_activity,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )- if not model_list:- logger.info("No DuckLake copy metadata resolved - nothing to do")- return+ if not model_list:+ status = "skipped"+ logger.info("No DuckLake copy metadata resolved - nothing to do")+ return- pending_staging_cleanup: list[str] = []- failed = False- try:for model in model_list:activity_inputs = DuckLakeCopyDataImportsActivityInputs(team_id=inputs.team_id, job_id=inputs.job_id, model=model)- await workflow.execute_activity(+ copy_workload: DeltaTableSnapshotWorkload | None = await workflow.execute_activity(copy_data_imports_to_ducklake_activity,activity_inputs,# TODO: Adjust timeouts based on table size?@@ -1046,8 +1127,15 @@ class DuckLakeCopyDataImportsWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)+ cleanup_inputs = Noneif model.staging_uri:- pending_staging_cleanup.append(model.staging_uri)+ cleanup_inputs = DuckLakeDataImportsStagingCleanupInputs(+ team_id=inputs.team_id,+ staging_uri=model.staging_uri,+ schema_id=model.source_schema_id,+ job_id=inputs.job_id,+ )+ pending_staging_cleanup.append(cleanup_inputs)verification_results = await workflow.execute_activity(verify_data_imports_ducklake_copy_activity,@@ -1057,10 +1145,14 @@ class DuckLakeCopyDataImportsWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=1),)- if verification_results:- for result in verification_results:- status = "passed" if result.passed else "failed"- get_ducklake_copy_data_imports_verification_metric(result.name, status).add(1)+ for result in verification_results:+ verification_status = "passed" if result.passed else "failed"+ get_ducklake_copy_data_imports_verification_metric(+ team_id=inputs.team_id,+ schema_id=model.source_schema_id,+ check_name=result.name,+ status=verification_status,+ ).add(1)failed_checks = [result for result in verification_results if not result.passed]if failed_checks:@@ -1075,38 +1167,49 @@ class DuckLakeCopyDataImportsWorkflow(PostHogWorkflow):non_retryable=True,)- if model.staging_uri:+ if copy_workload is not None:+ _record_copy_workload(+ team_id=inputs.team_id,+ schema_id=model.source_schema_id,+ workload=copy_workload,+ )+ get_ducklake_copy_data_imports_last_success_metric(+ team_id=inputs.team_id, schema_id=model.source_schema_id+ ).set(workflow.now().timestamp())++ if cleanup_inputs is not None:await workflow.execute_activity(cleanup_data_imports_staging_activity,- DuckLakeDataImportsStagingCleanupInputs(- team_id=inputs.team_id,- staging_uri=model.staging_uri,- ),+ cleanup_inputs,start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=2),)- pending_staging_cleanup.remove(model.staging_uri)- except Exception:- failed = True- get_ducklake_copy_data_imports_finished_metric(status="failed").add(1)- raise+ pending_staging_cleanup.remove(cleanup_inputs)++ status = "completed"finally:- for staging_uri in pending_staging_cleanup:+ for cleanup_inputs in pending_staging_cleanup:try:await workflow.execute_activity(cleanup_data_imports_staging_activity,- DuckLakeDataImportsStagingCleanupInputs(- team_id=inputs.team_id,- staging_uri=staging_uri,- ),+ cleanup_inputs,start_to_close_timeout=dt.timedelta(minutes=5),retry_policy=RetryPolicy(maximum_attempts=2),)except Exception:- workflow.logger.warning(+ logger.warning("Failed to clean up staging files",- staging_uri=staging_uri,+ staging_uri=cleanup_inputs.staging_uri,)- if not failed:- get_ducklake_copy_data_imports_finished_metric(status="completed").add(1)+ finished_at = workflow.now()+ duration_seconds = (finished_at - workflow_started_at).total_seconds()+ logger.info(+ "Finished DuckLakeCopyDataImportsWorkflow",+ status=status,+ duration_seconds=duration_seconds,+ )+ get_ducklake_copy_data_imports_finished_metric(team_id=inputs.team_id, status=status).add(1)+ get_ducklake_copy_data_imports_duration_metric(team_id=inputs.team_id, status=status).record(+ duration_seconds+ )diff --git a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.pyindex fd87a9d45b6b..40e41ee0ca96 100644--- a/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py+++ b/products/managed_warehouse/backend/temporal/ducklake_register_data_imports_workflow.py@@ -48,6 +48,7 @@ from products.managed_warehouse.backend.temporal.metrics import (get_ducklake_register_data_imports_rows_metric,get_ducklake_register_data_imports_stale_metric,get_ducklake_register_data_imports_started_metric,+ record_ducklake_register_data_imports_stage_duration,)from products.warehouse_sources.backend.facade.models import ExternalDataSchema@@ -63,6 +64,7 @@ def _stage_timer(*, stage: str, team_id: int, schema_id: str) -> ExecutionTimeRe"Execution duration of one post-gate DuckLake data import registration stage.",{"stage": stage, "team_id": str(team_id), "schema_id": schema_id},log=True,+ histogram_recorder=record_ducklake_register_data_imports_stage_duration,)diff --git a/products/managed_warehouse/backend/temporal/metrics.py b/products/managed_warehouse/backend/temporal/metrics.pyindex bfc9728fdaf7..dbaa8bbb86a4 100644--- a/products/managed_warehouse/backend/temporal/metrics.py+++ b/products/managed_warehouse/backend/temporal/metrics.py@@ -1,5 +1,150 @@+from typing import Self+from temporalio import activity, workflow-from temporalio.common import MetricCounter, MetricGaugeFloat, MetricHistogramFloat, MetricMeter+from temporalio.common import MetricAttributes, MetricCounter, MetricGaugeFloat, MetricHistogramFloat, MetricMeter++from products.managed_warehouse.backend.metrics import record_counter, record_gauge, record_histogram+++def _temporal_context_active() -> bool:+ return activity.in_activity() or workflow.in_workflow()+++def _posthog_metric_name(temporal_metric_name: str) -> str:+ normalized_name = temporal_metric_name.removesuffix("_seconds")+ return f"warehouse.{normalized_name.replace('_', '.')}"+++class _CounterTwin(MetricCounter):+ def __init__(self, temporal_metric: MetricCounter, attributes: MetricAttributes) -> None:+ self._temporal_metric = temporal_metric+ self._attributes = dict(attributes)++ @property+ def name(self) -> str:+ return self._temporal_metric.name++ @property+ def description(self) -> str | None:+ return self._temporal_metric.description++ @property+ def unit(self) -> str | None:+ return self._temporal_metric.unit++ def with_additional_attributes(self, additional_attributes: MetricAttributes) -> Self:+ return type(self)(+ self._temporal_metric.with_additional_attributes(additional_attributes),+ {**self._attributes, **additional_attributes},+ )++ def add(self, value: int, additional_attributes: MetricAttributes | None = None) -> None:+ self._temporal_metric.add(value, additional_attributes)+ if _temporal_context_active():+ record_counter(+ _posthog_metric_name(self.name),+ value,+ {**self._attributes, **(additional_attributes or {})},+ unit=self.unit,+ )+++class _HistogramTwin(MetricHistogramFloat):+ def __init__(self, temporal_metric: MetricHistogramFloat, attributes: MetricAttributes) -> None:+ self._temporal_metric = temporal_metric+ self._attributes = dict(attributes)++ @property+ def name(self) -> str:+ return self._temporal_metric.name++ @property+ def description(self) -> str | None:+ return self._temporal_metric.description++ @property+ def unit(self) -> str | None:+ return self._temporal_metric.unit++ def with_additional_attributes(self, additional_attributes: MetricAttributes) -> Self:+ return type(self)(+ self._temporal_metric.with_additional_attributes(additional_attributes),+ {**self._attributes, **additional_attributes},+ )++ def record(self, value: float, additional_attributes: MetricAttributes | None = None) -> None:+ self._temporal_metric.record(value, additional_attributes)+ if _temporal_context_active():+ record_histogram(+ _posthog_metric_name(self.name),+ value,+ {**self._attributes, **(additional_attributes or {})},+ unit=self.unit or "1",+ )+++class _GaugeTwin(MetricGaugeFloat):+ def __init__(self, temporal_metric: MetricGaugeFloat, attributes: MetricAttributes) -> None:+ self._temporal_metric = temporal_metric+ self._attributes = dict(attributes)++ @property+ def name(self) -> str:+ return self._temporal_metric.name++ @property+ def description(self) -> str | None:+ return self._temporal_metric.description++ @property+ def unit(self) -> str | None:+ return self._temporal_metric.unit++ def with_additional_attributes(self, additional_attributes: MetricAttributes) -> Self:+ return type(self)(+ self._temporal_metric.with_additional_attributes(additional_attributes),+ {**self._attributes, **additional_attributes},+ )++ def set(self, value: float, additional_attributes: MetricAttributes | None = None) -> None:+ self._temporal_metric.set(value, additional_attributes)+ if _temporal_context_active():+ record_gauge(+ _posthog_metric_name(self.name),+ value,+ {**self._attributes, **(additional_attributes or {})},+ unit=self.unit,+ )+++def _counter_twin(metric: MetricCounter, attributes: MetricAttributes) -> MetricCounter:+ return _CounterTwin(metric, attributes)+++def _histogram_twin(metric: MetricHistogramFloat, attributes: MetricAttributes) -> MetricHistogramFloat:+ return _HistogramTwin(metric, attributes)+++def _gauge_twin(metric: MetricGaugeFloat, attributes: MetricAttributes) -> MetricGaugeFloat:+ return _GaugeTwin(metric, attributes)+++def record_ducklake_copy_data_imports_stage_duration(value: float, attributes: MetricAttributes) -> None:+ record_histogram(+ "warehouse.ducklake.copy.data.imports.stage.duration",+ value,+ attributes,+ unit="ms",+ )+++def record_ducklake_register_data_imports_stage_duration(value: float, attributes: MetricAttributes) -> None:+ record_histogram(+ "warehouse.ducklake.register.data.imports.stage.duration",+ value,+ attributes,+ unit="ms",+ )def _activity_meter() -> MetricMeter:@@ -10,138 +155,252 @@ def _registration_attributes(team_id: int, schema_id: str) -> dict[str, str]:return {"team_id": str(team_id), "schema_id": schema_id}+def _copy_data_imports_attributes(team_id: int, schema_id: str | None = None) -> dict[str, str]:+ attributes = {"team_id": str(team_id)}+ if schema_id is not None:+ attributes["schema_id"] = schema_id+ return attributes++def get_ducklake_copy_data_modeling_finished_metric(status: str) -> MetricCounter:- return (+ attributes = {"status": status}+ metric = (workflow.metric_meter()- .with_additional_attributes({"status": status})+ .with_additional_attributes(attributes).create_counter("ducklake_copy_data_modeling_finished","Number of DuckLake data modeling copy workflows finished, including failures.",))+ return _counter_twin(metric, attributes)def get_ducklake_copy_data_modeling_verification_metric(check: str, status: str) -> MetricCounter:- return (+ attributes = {"check": check, "status": status}+ metric = (workflow.metric_meter()- .with_additional_attributes({"check": check, "status": status})+ .with_additional_attributes(attributes).create_counter("ducklake_copy_data_modeling_verification","Number of DuckLake data modeling verification checks executed grouped by status.",))+ return _counter_twin(metric, attributes)-def get_ducklake_copy_data_imports_finished_metric(status: str) -> MetricCounter:- return (+def get_ducklake_copy_data_imports_finished_metric(*, team_id: int, status: str) -> MetricCounter:+ attributes = {**_copy_data_imports_attributes(team_id), "status": status}+ metric = (workflow.metric_meter()- .with_additional_attributes({"status": status})+ .with_additional_attributes(attributes).create_counter("ducklake_copy_data_imports_finished",- "Number of DuckLake data imports copy workflows finished, including failures.",+ "Number of DuckLake data import copy workflows finished after passing the feature flag gate.",))+ return _counter_twin(metric, attributes)-def get_ducklake_copy_data_imports_verification_metric(check_name: str, status: str) -> MetricCounter:- return (+def get_ducklake_copy_data_imports_started_metric(*, team_id: int) -> MetricCounter:+ attributes = _copy_data_imports_attributes(team_id)+ metric = (workflow.metric_meter()- .with_additional_attributes({"check": check_name, "status": status})+ .with_additional_attributes(attributes)+ .create_counter(+ "ducklake_copy_data_imports_started",+ "Number of DuckLake data import copy workflows that passed the feature flag gate.",+ )+ )+ return _counter_twin(metric, attributes)+++def get_ducklake_copy_data_imports_duration_metric(*, team_id: int, status: str) -> MetricHistogramFloat:+ attributes = {**_copy_data_imports_attributes(team_id), "status": status}+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes)+ .create_histogram_float(+ "ducklake_copy_data_imports_duration_seconds",+ "End-to-end duration of DuckLake data import copy workflows after passing the feature flag gate.",+ "s",+ )+ )+ return _histogram_twin(metric, attributes)+++def get_ducklake_copy_data_imports_last_success_metric(*, team_id: int, schema_id: str) -> MetricGaugeFloat:+ attributes = _copy_data_imports_attributes(team_id, schema_id)+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes)+ .create_gauge_float(+ "ducklake_copy_data_imports_last_success_timestamp_seconds",+ "Unix timestamp of the last successful DuckLake data import copy for a schema.",+ "s",+ )+ )+ return _gauge_twin(metric, attributes)+++def get_ducklake_copy_data_imports_verification_metric(+ *, team_id: int, schema_id: str, check_name: str, status: str+) -> MetricCounter:+ attributes = {**_copy_data_imports_attributes(team_id, schema_id), "check": check_name, "status": status}+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes).create_counter("ducklake_copy_data_imports_verification",- "Number of DuckLake data imports verification checks completed.",+ "Number of DuckLake data import verification checks completed.",+ )+ )+ return _counter_twin(metric, attributes)+++def get_ducklake_copy_data_imports_files_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:+ attributes = _copy_data_imports_attributes(team_id, schema_id)+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes)+ .create_histogram_float(+ "ducklake_copy_data_imports_data_files_copied",+ "Number of Delta data files in a successful DuckLake data import copy.",+ )+ )+ return _histogram_twin(metric, attributes)+++def get_ducklake_copy_data_imports_rows_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:+ attributes = _copy_data_imports_attributes(team_id, schema_id)+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes)+ .create_histogram_float(+ "ducklake_copy_data_imports_rows_copied",+ "Number of rows in a successful DuckLake data import copy.",+ )+ )+ return _histogram_twin(metric, attributes)+++def get_ducklake_copy_data_imports_bytes_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:+ attributes = _copy_data_imports_attributes(team_id, schema_id)+ metric = (+ workflow.metric_meter()+ .with_additional_attributes(attributes)+ .create_histogram_float(+ "ducklake_copy_data_imports_data_bytes_copied",+ "Number of Delta data file bytes in a successful DuckLake data import copy.",+ "By",))+ return _histogram_twin(metric, attributes)def get_ducklake_register_data_imports_finished_metric(*, team_id: int, schema_id: str, status: str) -> MetricCounter:- return (+ attributes = {**_registration_attributes(team_id, schema_id), "status": status}+ metric = (workflow.metric_meter()- .with_additional_attributes({**_registration_attributes(team_id, schema_id), "status": status})+ .with_additional_attributes(attributes).create_counter("ducklake_register_data_imports_finished","Number of DuckLake prepared data import registration workflows finished, including failures.",))+ return _counter_twin(metric, attributes)def get_ducklake_register_data_imports_duration_metric(*, team_id: int, schema_id: str, status: str) -> MetricHistogramFloat:- return (+ attributes = {**_registration_attributes(team_id, schema_id), "status": status}+ metric = (workflow.metric_meter()- .with_additional_attributes({**_registration_attributes(team_id, schema_id), "status": status})+ .with_additional_attributes(attributes).create_histogram_float("ducklake_register_data_imports_duration_seconds","End-to-end duration of DuckLake prepared data import registration workflows that passed the feature flag gate.","s",))+ return _histogram_twin(metric, attributes)def get_ducklake_register_data_imports_started_metric(*, team_id: int, schema_id: str) -> MetricCounter:- return (+ attributes = _registration_attributes(team_id, schema_id)+ metric = (workflow.metric_meter()- .with_additional_attributes(_registration_attributes(team_id, schema_id))+ .with_additional_attributes(attributes).create_counter("ducklake_register_data_imports_started","Number of DuckLake prepared data import registration workflows that passed the feature flag gate.",))+ return _counter_twin(metric, attributes)def get_ducklake_register_data_imports_last_success_metric(*, team_id: int, schema_id: str) -> MetricGaugeFloat:- return (+ attributes = _registration_attributes(team_id, schema_id)+ metric = (workflow.metric_meter()- .with_additional_attributes(_registration_attributes(team_id, schema_id))+ .with_additional_attributes(attributes).create_gauge_float("ducklake_register_data_imports_last_success_timestamp_seconds","Unix timestamp of the last successful DuckLake prepared data import registration workflow.","s",))+ return _gauge_twin(metric, attributes)def get_ducklake_register_data_imports_stale_metric(*, team_id: int, schema_id: str, stage: str) -> MetricCounter:- return (+ attributes = {**_registration_attributes(team_id, schema_id), "stage": stage}+ metric = (_activity_meter()- .with_additional_attributes({**_registration_attributes(team_id, schema_id), "stage": stage})+ .with_additional_attributes(attributes).create_counter("ducklake_register_data_imports_stale","Number of post-gate DuckLake registrations skipped because their prepared generation became stale.",))+ return _counter_twin(metric, attributes)def get_ducklake_register_data_imports_files_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:- return (+ attributes = _registration_attributes(team_id, schema_id)+ metric = (_activity_meter()- .with_additional_attributes(_registration_attributes(team_id, schema_id))+ .with_additional_attributes(attributes).create_histogram_float("ducklake_register_data_imports_files_registered","Number of Parquet files in a successful DuckLake data import registration.",))+ return _histogram_twin(metric, attributes)def get_ducklake_register_data_imports_rows_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:- return (+ attributes = _registration_attributes(team_id, schema_id)+ metric = (_activity_meter()- .with_additional_attributes(_registration_attributes(team_id, schema_id))+ .with_additional_attributes(attributes).create_histogram_float("ducklake_register_data_imports_rows_registered","Number of rows in a successful DuckLake data import registration.",))+ return _histogram_twin(metric, attributes)def get_ducklake_register_data_imports_bytes_metric(*, team_id: int, schema_id: str) -> MetricHistogramFloat:- return (+ attributes = _registration_attributes(team_id, schema_id)+ metric = (_activity_meter()- .with_additional_attributes(_registration_attributes(team_id, schema_id))+ .with_additional_attributes(attributes).create_histogram_float("ducklake_register_data_imports_bytes_copied","Number of prepared Parquet bytes copied by a successful DuckLake data import registration.","By",))+ return _histogram_twin(metric, attributes)diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.pyindex 5ae9aa792333..e2e605fe1709 100644--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_copy_data_imports_workflow.py@@ -3,7 +3,7 @@ import datetime as dtfrom collections.abc import Sequenceimport pytest-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockfrom django.conf import settingsfrom django.test import override_settings@@ -21,7 +21,7 @@ from products.managed_warehouse.backend.logic.verification import (DuckLakeCopyVerificationQuery,)from products.managed_warehouse.backend.models import DuckgresServer-from products.managed_warehouse.backend.storage import compute_staging_uri+from products.managed_warehouse.backend.storage import DeltaTableSnapshotWorkload, StagedDeltaTable, compute_staging_urifrom products.managed_warehouse.backend.temporal import ducklake_copy_data_imports_workflow as ducklake_modulefrom products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow import (DataImportsDuckLakeCopyInputs,@@ -522,8 +522,13 @@ def test_copy_data_imports_to_ducklake_activity_via_duckdb(monkeypatch):"products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow._attach_ducklake_catalog",mock_attach_catalog,)+ workload = DeltaTableSnapshotWorkload(file_count=2, row_count=20, byte_count=200)monkeypatch.setattr(- "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.stage_delta_table",+ "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.get_delta_table_snapshot_workload",+ MagicMock(return_value=workload),+ )+ monkeypatch.setattr(+ "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.stage_delta_table_with_workload",MagicMock(side_effect=AssertionError("stage_delta_table should not be used in dev mode")),)monkeypatch.setattr(@@ -547,8 +552,9 @@ def test_copy_data_imports_to_ducklake_activity_via_duckdb(monkeypatch):# in tests that don't need the database; override it here to prove the call still fires# outside tests, i.e. in the real long-lived worker thread.with override_settings(TEST=False):- copy_data_imports_to_ducklake_activity(inputs)+ result = copy_data_imports_to_ducklake_activity(inputs)+ assert result == workloadmock_close_old_connections.assert_called_once()mock_configure_connection.assert_called_once_with(mock_conn)mock_ensure_bucket.assert_called_once_with(config={"DUCKLAKE_BUCKET": "ducklake-dev"}, team_id=1)@@ -587,9 +593,15 @@ def test_copy_data_imports_to_ducklake_activity_via_duckgres(monkeypatch):"products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.get_duckgres_server_for_organization",MagicMock(return_value=_create_mock_server()),)- mock_stage = MagicMock()+ workload = DeltaTableSnapshotWorkload(file_count=3, row_count=30, byte_count=300)+ mock_stage = MagicMock(+ return_value=StagedDeltaTable(+ staging_uri="s3://test-bucket/__posthog_staging/team_1/customers",+ workload=workload,+ )+ )monkeypatch.setattr(- "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.stage_delta_table",+ "products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow.stage_delta_table_with_workload",mock_stage,)monkeypatch.setattr(@@ -613,8 +625,9 @@ def test_copy_data_imports_to_ducklake_activity_via_duckgres(monkeypatch):)inputs = DuckLakeCopyDataImportsActivityInputs(team_id=1, job_id="job-123", model=metadata)- copy_data_imports_to_ducklake_activity(inputs)+ result = copy_data_imports_to_ducklake_activity(inputs)+ assert result == workloadmock_stage.assert_called_once_with(source_uri="s3://bucket/team_1/customers",catalog_bucket="test-bucket",@@ -1091,6 +1104,128 @@ def test_ducklake_copy_data_imports_workflow_parse_inputs():assert inputs.schema_ids[0] == schema_id+async def test_workflow_does_not_record_metrics_when_gate_is_disabled(monkeypatch):+ execute_activity = AsyncMock(return_value=False)+ metrics = _mock_copy_workflow_metrics(monkeypatch)+ monkeypatch.setattr(ducklake_module.workflow, "execute_activity", execute_activity)++ await DuckLakeCopyDataImportsWorkflow().run(_workflow_inputs())++ metrics.started_getter.assert_not_called()+ metrics.finished_getter.assert_not_called()+ metrics.duration_getter.assert_not_called()+ metrics.last_success_getter.assert_not_called()+++async def test_workflow_records_successful_post_gate_metrics(monkeypatch):+ started_at = dt.datetime(2026, 7, 31, 12, 0, 0)+ schema_finished_at = started_at + dt.timedelta(minutes=4)+ workflow_finished_at = started_at + dt.timedelta(minutes=5, seconds=12)+ workload = DeltaTableSnapshotWorkload(file_count=3, row_count=30, byte_count=300)+ verification_result = ducklake_module.DuckLakeCopyDataImportsVerificationResult(name="row_count", passed=True)+ execute_activity = AsyncMock(side_effect=[True, [_workflow_model()], workload, [verification_result]])+ metrics = _mock_copy_workflow_metrics(monkeypatch)+ monkeypatch.setattr(ducklake_module.workflow, "execute_activity", execute_activity)+ monkeypatch.setattr(+ ducklake_module.workflow,+ "now",+ MagicMock(side_effect=[started_at, schema_finished_at, workflow_finished_at]),+ )++ await DuckLakeCopyDataImportsWorkflow().run(_workflow_inputs())++ metrics.started_getter.assert_called_once_with(team_id=1)+ metrics.started.add.assert_called_once_with(1)+ metrics.finished_getter.assert_called_once_with(team_id=1, status="completed")+ metrics.finished.add.assert_called_once_with(1)+ metrics.duration_getter.assert_called_once_with(team_id=1, status="completed")+ metrics.duration.record.assert_called_once_with(312.0)+ metrics.last_success_getter.assert_called_once_with(team_id=1, schema_id="schema-123")+ metrics.last_success.set.assert_called_once_with(schema_finished_at.timestamp())+ metrics.files_getter.assert_called_once_with(team_id=1, schema_id="schema-123")+ metrics.files.record.assert_called_once_with(3.0)+ metrics.rows_getter.assert_called_once_with(team_id=1, schema_id="schema-123")+ metrics.rows.record.assert_called_once_with(30.0)+ metrics.bytes_getter.assert_called_once_with(team_id=1, schema_id="schema-123")+ metrics.bytes.record.assert_called_once_with(300.0)+ metrics.verification_getter.assert_called_once_with(+ team_id=1,+ schema_id="schema-123",+ check_name="row_count",+ status="passed",+ )+ metrics.verification.add.assert_called_once_with(1)+++async def test_workflow_records_failed_post_gate_metrics(monkeypatch):+ started_at = dt.datetime(2026, 7, 31, 12, 0, 0)+ failed_at = started_at + dt.timedelta(seconds=5)+ execute_activity = AsyncMock(side_effect=[True, RuntimeError("prepare failed")])+ metrics = _mock_copy_workflow_metrics(monkeypatch)+ monkeypatch.setattr(ducklake_module.workflow, "execute_activity", execute_activity)+ monkeypatch.setattr(ducklake_module.workflow, "now", MagicMock(side_effect=[started_at, failed_at]))++ with pytest.raises(RuntimeError, match="prepare failed"):+ await DuckLakeCopyDataImportsWorkflow().run(_workflow_inputs())++ metrics.started_getter.assert_called_once_with(team_id=1)+ metrics.finished_getter.assert_called_once_with(team_id=1, status="failed")+ metrics.finished.add.assert_called_once_with(1)+ metrics.duration_getter.assert_called_once_with(team_id=1, status="failed")+ metrics.duration.record.assert_called_once_with(5.0)+ metrics.last_success_getter.assert_not_called()+ metrics.files_getter.assert_not_called()+++async def test_workflow_records_skipped_status_when_no_models_are_resolved(monkeypatch):+ started_at = dt.datetime(2026, 7, 31, 12, 0, 0)+ finished_at = started_at + dt.timedelta(seconds=2)+ execute_activity = AsyncMock(side_effect=[True, []])+ metrics = _mock_copy_workflow_metrics(monkeypatch)+ monkeypatch.setattr(ducklake_module.workflow, "execute_activity", execute_activity)+ monkeypatch.setattr(ducklake_module.workflow, "now", MagicMock(side_effect=[started_at, finished_at]))++ await DuckLakeCopyDataImportsWorkflow().run(_workflow_inputs())++ metrics.finished_getter.assert_called_once_with(team_id=1, status="skipped")+ metrics.duration_getter.assert_called_once_with(team_id=1, status="skipped")+ metrics.duration.record.assert_called_once_with(2.0)+ metrics.last_success_getter.assert_not_called()+++def _mock_copy_workflow_metrics(monkeypatch):+ metrics = MagicMock()+ for name in ("started", "finished", "duration", "last_success", "files", "rows", "bytes", "verification"):+ getter = MagicMock(return_value=getattr(metrics, name))+ setattr(metrics, f"{name}_getter", getter)+ monkeypatch.setattr(ducklake_module, f"get_ducklake_copy_data_imports_{name}_metric", getter)+ return metrics+++def _workflow_inputs() -> DataImportsDuckLakeCopyInputs:+ return DataImportsDuckLakeCopyInputs(+ team_id=1,+ job_id="job-123",+ schema_ids=[uuid.UUID("019ef5df-e4c7-0000-b543-8ef7f13b5f15")],+ )+++def _workflow_model() -> DuckLakeCopyDataImportsMetadata:+ return DuckLakeCopyDataImportsMetadata(+ model_label="postgres_customers",+ source_schema_id="schema-123",+ source_schema_name="customers",+ source_normalized_name="customers",+ source_table_uri="s3://bucket/team_1/customers",+ ducklake_schema_name="posthog_data_imports_team_1",+ ducklake_table_name="postgres_customers_abc12345",+ )++def test_copy_data_imports_to_ducklake_activity_raises_when_no_catalog(monkeypatch):from temporalio.exceptions import ApplicationError@@ -1444,20 +1579,24 @@ def test_stage_waits_out_delta_rebuild_window(monkeypatch, absent_error):monkeypatch.setattr(ducklake_module, "time", clock)attempts = {"count": 0}+ workload = DeltaTableSnapshotWorkload(file_count=1, row_count=10, byte_count=100)+def stage(**kwargs):attempts["count"] += 1if attempts["count"] <= 2:raise absent_error+ return StagedDeltaTable(staging_uri="s3://catalog/staged", workload=workload)- monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)+ monkeypatch.setattr(ducklake_module, "stage_delta_table_with_workload", stage)- ducklake_module._stage_delta_table_waiting_for_rebuild(+ result = ducklake_module._stage_delta_table_waiting_for_rebuild(source_uri="s3://bucket/folder/table",catalog_bucket="catalog",organization_id="org",logger=MagicMock(),)+ assert result == workloadassert attempts["count"] == 3assert clock.sleeps == [ducklake_module.DELTA_REBUILD_POLL_SECONDS] * 2@@ -1471,7 +1610,7 @@ def test_stage_raises_immediately_on_non_absent_errors(monkeypatch):attempts["count"] += 1raise deltalake.exceptions.DeltaError("Generic error: something else broke")- monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)+ monkeypatch.setattr(ducklake_module, "stage_delta_table_with_workload", stage)with pytest.raises(deltalake.exceptions.DeltaError):ducklake_module._stage_delta_table_waiting_for_rebuild(@@ -1492,7 +1631,7 @@ def test_stage_gives_up_after_rebuild_wait_budget(monkeypatch):def stage(**kwargs):raise deltalake.exceptions.DeltaError("Generic delta kernel error: No files in log segment")- monkeypatch.setattr(ducklake_module, "stage_delta_table", stage)+ monkeypatch.setattr(ducklake_module, "stage_delta_table_with_workload", stage)with pytest.raises(deltalake.exceptions.DeltaError):ducklake_module._stage_delta_table_waiting_for_rebuild(diff --git a/products/managed_warehouse/backend/tests/test_metrics.py b/products/managed_warehouse/backend/tests/test_metrics.pynew file mode 100644index 000000000000..3ccd1139c722--- /dev/null+++ b/products/managed_warehouse/backend/tests/test_metrics.py@@ -0,0 +1,189 @@+import pytest+from unittest.mock import MagicMock, call, patch++from parameterized import parameterized++from products.managed_warehouse.backend.metrics import (+ record_counter,+ record_duckling_backfill_workload,+ track_duckling_backfill,+)+from products.managed_warehouse.backend.temporal import metrics as temporal_metrics+++class TestTemporalMetricTwins:+ @parameterized.expand(+ [+ (+ "counter",+ "get_ducklake_copy_data_imports_started_metric",+ {"team_id": 7},+ "create_counter",+ "add",+ "count",+ 1,+ "ducklake_copy_data_imports_started",+ "warehouse.ducklake.copy.data.imports.started",+ None,+ {"team_id": "7"},+ ),+ (+ "histogram",+ "get_ducklake_register_data_imports_duration_metric",+ {"team_id": 7, "schema_id": "schema-1", "status": "completed"},+ "create_histogram_float",+ "record",+ "histogram",+ 4.5,+ "ducklake_register_data_imports_duration_seconds",+ "warehouse.ducklake.register.data.imports.duration",+ "s",+ {"team_id": "7", "schema_id": "schema-1", "status": "completed"},+ ),+ (+ "gauge",+ "get_ducklake_copy_data_imports_last_success_metric",+ {"team_id": 7, "schema_id": "schema-1"},+ "create_gauge_float",+ "set",+ "gauge",+ 123.0,+ "ducklake_copy_data_imports_last_success_timestamp_seconds",+ "warehouse.ducklake.copy.data.imports.last.success.timestamp",+ "s",+ {"team_id": "7", "schema_id": "schema-1"},+ ),+ ]+ )+ def test_records_temporal_and_posthog_metrics(+ self,+ _name: str,+ getter_name: str,+ getter_kwargs: dict[str, object],+ create_method: str,+ record_method: str,+ posthog_method: str,+ value: float,+ temporal_name: str,+ posthog_name: str,+ unit: str | None,+ attributes: dict[str, str],+ ) -> None:+ meter = MagicMock()+ temporal_metric = getattr(meter.with_additional_attributes.return_value, create_method).return_value+ temporal_metric.name = temporal_name+ temporal_metric.description = "description"+ temporal_metric.unit = unit+ client = MagicMock()++ with (+ patch.object(temporal_metrics.workflow, "metric_meter", return_value=meter),+ patch.object(temporal_metrics.workflow, "in_workflow", return_value=True),+ patch("products.managed_warehouse.backend.metrics.workflow.unsafe.is_replaying", return_value=False),+ patch("products.managed_warehouse.backend.metrics.posthoganalytics.default_client", client),+ ):+ metric = getattr(temporal_metrics, getter_name)(**getter_kwargs)+ getattr(metric, record_method)(value)++ getattr(temporal_metric, record_method).assert_called_once_with(value, None)+ getattr(client.metrics, posthog_method).assert_called_once_with(+ posthog_name,+ value,+ unit=unit,+ attributes=attributes,+ )+++class TestDucklingBackfillMetrics:+ @parameterized.expand([("completed", False), ("failed", True)])+ def test_records_terminal_status(self, expected_status: str, fails: bool) -> None:+ client = MagicMock()+ perf_counter_values = [10.0, 12.5]++ with (+ patch("products.managed_warehouse.backend.metrics.posthoganalytics.default_client", client),+ patch("products.managed_warehouse.backend.metrics.workflow.in_workflow", return_value=False),+ patch("products.managed_warehouse.backend.metrics.time.perf_counter", side_effect=perf_counter_values),+ patch("products.managed_warehouse.backend.metrics.time.time", return_value=123.0),+ ):+ if fails:+ with pytest.raises(RuntimeError, match="backfill failed"):+ with track_duckling_backfill(team_id=7, dataset="events", mode="daily"):+ raise RuntimeError("backfill failed")+ else:+ with track_duckling_backfill(team_id=7, dataset="events", mode="daily"):+ pass++ base_attributes = {"team_id": "7", "dataset": "events", "mode": "daily"}+ client.metrics.count.assert_has_calls(+ [+ call("warehouse.duckling.backfill.started", 1, unit=None, attributes=base_attributes),+ call(+ "warehouse.duckling.backfill.finished",+ 1,+ unit=None,+ attributes={**base_attributes, "status": expected_status},+ ),+ ]+ )+ client.metrics.histogram.assert_called_once_with(+ "warehouse.duckling.backfill.duration",+ 2.5,+ unit="s",+ attributes={**base_attributes, "status": expected_status},+ )+ if fails:+ client.metrics.gauge.assert_not_called()+ else:+ client.metrics.gauge.assert_called_once_with(+ "warehouse.duckling.backfill.last.success.timestamp",+ 123.0,+ unit="s",+ attributes=base_attributes,+ )+ client.metrics.flush.assert_called_once_with()++ def test_records_successful_workload(self) -> None:+ client = MagicMock()++ with (+ patch("products.managed_warehouse.backend.metrics.posthoganalytics.default_client", client),+ patch("products.managed_warehouse.backend.metrics.workflow.in_workflow", return_value=False),+ ):+ record_duckling_backfill_workload(+ team_id=7,+ dataset="persons",+ mode="full",+ files_registered=12,+ partitions_exported=3,+ )++ attributes = {"team_id": "7", "dataset": "persons", "mode": "full"}+ client.metrics.histogram.assert_has_calls(+ [+ call(+ "warehouse.duckling.backfill.files.registered",+ 12.0,+ unit="file",+ attributes=attributes,+ ),+ call(+ "warehouse.duckling.backfill.partitions.exported",+ 3.0,+ unit="partition",+ attributes=attributes,+ ),+ ]+ )++ def test_does_not_record_workflow_replays(self) -> None:+ client = MagicMock()++ with (+ patch("products.managed_warehouse.backend.metrics.posthoganalytics.default_client", client),+ patch("products.managed_warehouse.backend.metrics.workflow.in_workflow", return_value=True),+ patch("products.managed_warehouse.backend.metrics.workflow.unsafe.is_replaying", return_value=True),+ ):+ record_counter("warehouse.ducklake.copy.started", 1, {"status": "completed"})++ client.metrics.count.assert_not_called()diff --git a/products/managed_warehouse/backend/tests/test_storage.py b/products/managed_warehouse/backend/tests/test_storage.pyindex 2d497d91e098..bfcf03371d9b 100644--- a/products/managed_warehouse/backend/tests/test_storage.py+++ b/products/managed_warehouse/backend/tests/test_storage.py@@ -450,16 +450,22 @@ class TestDeltaLogVersionRegex:class TestGetDeltaSnapshotFiles:- def test_returns_version_and_data_keys(self, monkeypatch):+ def test_returns_version_data_keys_and_workload(self, monkeypatch):import sysimport types+ mock_add_actions = MagicMock()+ mock_add_actions.schema.names = ["size_bytes", "num_records"]+ mock_add_actions.column.side_effect = lambda name: MagicMock(+ to_pylist=MagicMock(return_value=[100, 200] if name == "size_bytes" else [10, 20])+ )mock_dt = MagicMock()mock_dt.version.return_value = 3mock_dt.file_uris.return_value = ["s3://customer-bucket/data/table/part-00000.parquet","s3://customer-bucket/data/table/part-00001.parquet",]+ mock_dt.get_add_actions.return_value = mock_add_actionsmock_delta_table_cls = MagicMock(return_value=mock_dt)mock_deltalake = types.ModuleType("deltalake")@@ -473,15 +479,16 @@ class TestGetDeltaSnapshotFiles:},)- from products.managed_warehouse.backend.storage import _get_delta_snapshot_files+ from products.managed_warehouse.backend.storage import DeltaTableSnapshotWorkload, _get_delta_snapshot- version, keys = _get_delta_snapshot_files(+ version, keys, workload = _get_delta_snapshot("s3://customer-bucket/data/table",team_id=123,organization_id="org-123",)assert version == 3assert keys == ["data/table/part-00000.parquet", "data/table/part-00001.parquet"]+ assert workload == DeltaTableSnapshotWorkload(file_count=2, row_count=30, byte_count=300)mock_delta_table_cls.assert_called_once_with(table_uri="s3://customer-bucket/data/table",@@ -492,15 +499,17 @@ class TestGetDeltaSnapshotFiles:class TestStageDeltaTable:@patch("boto3.client")def test_copies_only_pinned_version_files(self, mock_boto3_client, monkeypatch):- mock_get_snapshot_files = MagicMock(+ from products.managed_warehouse.backend.storage import DeltaTableSnapshotWorkload++ workload = DeltaTableSnapshotWorkload(file_count=2, row_count=30, byte_count=300)+ mock_get_snapshot = MagicMock(return_value=(2,["data/table/part-00000.parquet", "data/table/part-00001.parquet"],+ workload,))- monkeypatch.setattr(- "products.managed_warehouse.backend.storage._get_delta_snapshot_files", mock_get_snapshot_files- )+ monkeypatch.setattr("products.managed_warehouse.backend.storage._get_delta_snapshot", mock_get_snapshot)mock_s3 = MagicMock()mock_s3.get_paginator.return_value = _mock_paginator(@@ -516,16 +525,19 @@ class TestStageDeltaTable:)mock_boto3_client.return_value = mock_s3- from products.managed_warehouse.backend.storage import stage_delta_table+ from products.managed_warehouse.backend.storage import StagedDeltaTable, stage_delta_table_with_workload- result = stage_delta_table(+ result = stage_delta_table_with_workload(source_uri="s3://customer-bucket/data/table",catalog_bucket="catalog-bucket",organization_id="org-123",)- assert result == "s3://catalog-bucket/__posthog_staging/data/table"- mock_get_snapshot_files.assert_called_once_with(+ assert result == StagedDeltaTable(+ staging_uri="s3://catalog-bucket/__posthog_staging/data/table",+ workload=workload,+ )+ mock_get_snapshot.assert_called_once_with("s3://customer-bucket/data/table",storage_config=None,team_id=None,