Skip to content

: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.

feat(data-modeling): label node metrics by engine and count trino shadow starts (#118491)

Jovan Sakovic1c75efef8fff
diff --git a/posthog/temporal/data_modeling/metrics.py b/posthog/temporal/data_modeling/metrics.py
index bfbc74f5d317..b33c2d5fbc39 100644
--- a/posthog/temporal/data_modeling/metrics.py
+++ b/posthog/temporal/data_modeling/metrics.py
@@ -169,43 +169,70 @@ def get_dag_node_count_metric(outcome: str, engine: str) -> MetricHistogramFloat
# Node-level metrics (v2 MaterializeViewWorkflow)
-def get_node_finished_metric(status: str) -> MetricCounter:
+def get_trino_shadow_start_metric(outcome: str) -> MetricCounter:
return (
workflow.metric_meter()
- .with_additional_attributes({"status": status})
+ .with_additional_attributes({"outcome": outcome})
+ .create_counter(
+ "data_modeling_trino_shadow_start",
+ "Trino shadow run start attempts. Outcome is started, skipped_still_running, or error.",
+ )
+ )
+
+
+def get_node_finished_metric(status: str, engine: str) -> MetricCounter:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"status": status, "engine": engine})
.create_counter(
"data_modeling_node_finished",
- "Number of node materializations finished. Status is completed, failed, or cancelled.",
+ "Number of node materializations finished. Status is completed, failed, cancelled, or quality_blocked.",
)
)
-def get_node_duration_metric() -> MetricHistogramFloat:
- return workflow.metric_meter().create_histogram_float(
- "data_modeling_node_duration_seconds",
- "Wall-clock duration of a single node materialization.",
- "s",
+def get_node_duration_metric(engine: str) -> MetricHistogramFloat:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"engine": engine})
+ .create_histogram_float(
+ "data_modeling_node_duration_seconds",
+ "Wall-clock duration of a single node materialization.",
+ "s",
+ )
)
-def get_node_rows_materialized_metric() -> MetricHistogramFloat:
- return workflow.metric_meter().create_histogram_float(
- "data_modeling_node_rows_materialized",
- "Number of rows materialized per node.",
+def get_node_rows_materialized_metric(engine: str) -> MetricHistogramFloat:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"engine": engine})
+ .create_histogram_float(
+ "data_modeling_node_rows_materialized",
+ "Number of rows materialized per node.",
+ )
)
-def get_node_storage_delta_mib_metric() -> MetricHistogramFloat:
- return workflow.metric_meter().create_histogram_float(
- "data_modeling_node_storage_delta_mib",
- "Change in S3 storage size (MiB) after a node materialization.",
- "MiB",
+def get_node_storage_delta_mib_metric(engine: str) -> MetricHistogramFloat:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"engine": engine})
+ .create_histogram_float(
+ "data_modeling_node_storage_delta_mib",
+ "Change in storage size (MiB) after a node materialization.",
+ "MiB",
+ )
)
-def get_node_total_storage_mib_metric() -> MetricHistogramFloat:
- return workflow.metric_meter().create_histogram_float(
- "data_modeling_node_total_storage_mib",
- "Total S3 storage size (MiB) of the materialized table after a node materialization.",
- "MiB",
+def get_node_total_storage_mib_metric(engine: str) -> MetricHistogramFloat:
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"engine": engine})
+ .create_histogram_float(
+ "data_modeling_node_total_storage_mib",
+ "Total storage size (MiB) of the materialized table after a node materialization.",
+ "MiB",
+ )
)
diff --git a/posthog/temporal/data_modeling/workflows/execute_dag.py b/posthog/temporal/data_modeling/workflows/execute_dag.py
index 154ec2525720..13a779f6750e 100644
--- a/posthog/temporal/data_modeling/workflows/execute_dag.py
+++ b/posthog/temporal/data_modeling/workflows/execute_dag.py
@@ -30,6 +30,7 @@ from posthog.temporal.data_modeling.metrics import (
get_dag_duration_metric,
get_dag_finished_metric,
get_dag_node_count_metric,
+ get_trino_shadow_start_metric,
)
from posthog.temporal.data_modeling.workflows.materialize_view import (
MaterializeViewWorkflow,
@@ -628,13 +629,17 @@ class ExecuteDAGWorkflow(PostHogWorkflow):
execution_timeout=TRINO_SHADOW_RUN_TIMEOUT,
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),
)
+ get_trino_shadow_start_metric("started").add(1)
except WorkflowAlreadyStartedError:
+ # A shadow that hangs until its timeout emits no DAG metric, so a rising skip rate is its only signal.
+ get_trino_shadow_start_metric("skipped_still_running").add(1)
temporalio.workflow.logger.info(
"Previous Trino shadow run is still running, skipping", extra=inputs.properties_to_log
)
except Exception as e:
if _is_cancellation(e):
raise
+ get_trino_shadow_start_metric("error").add(1)
capture_exception(e)
temporalio.workflow.logger.warning(
"Could not start the Trino shadow run", extra={"error": str(e), **inputs.properties_to_log}
diff --git a/posthog/temporal/data_modeling/workflows/materialize_view.py b/posthog/temporal/data_modeling/workflows/materialize_view.py
index 23ce3c896c0e..b6f563217217 100644
--- a/posthog/temporal/data_modeling/workflows/materialize_view.py
+++ b/posthog/temporal/data_modeling/workflows/materialize_view.py
@@ -161,6 +161,25 @@ class _StagedAuditVerdict:
blocking_failures: int
+CLICKHOUSE_ENGINE = DataModelingJobEngine.CLICKHOUSE.value
+MANAGED_WAREHOUSE_ENGINE = DataModelingJobEngine.MANAGED_WAREHOUSE.value
+
+
+def _record_managed_warehouse_node_metrics(result: ManagedWarehouseShadowResult) -> None:
+ if result.error is not None:
+ get_node_finished_metric("failed", MANAGED_WAREHOUSE_ENGINE).add(1)
+ return
+ get_node_finished_metric("completed", MANAGED_WAREHOUSE_ENGINE).add(1)
+ get_node_duration_metric(MANAGED_WAREHOUSE_ENGINE).record(result.duration_seconds)
+ get_node_rows_materialized_metric(MANAGED_WAREHOUSE_ENGINE).record(result.row_count)
+ if result.file_size_bytes > 0:
+ get_node_total_storage_mib_metric(MANAGED_WAREHOUSE_ENGINE).record(result.file_size_bytes / (1024 * 1024))
+ if result.file_size_delta_bytes >= 0:
+ get_node_storage_delta_mib_metric(MANAGED_WAREHOUSE_ENGINE).record(
+ result.file_size_delta_bytes / (1024 * 1024)
+ )
+
+
@temporalio.workflow.defn(name="data-modeling-materialize-view")
class MaterializeViewWorkflow(PostHogWorkflow):
"""Temporal workflow to materialize a single view.
@@ -329,7 +348,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
start_to_close_timeout=dt.timedelta(minutes=5),
retry_policy=temporalio.common.RetryPolicy(maximum_attempts=3),
)
- get_node_finished_metric("quality_blocked").add(1)
+ get_node_finished_metric("quality_blocked", CLICKHOUSE_ENGINE).add(1)
await self._discard_staged_cdp_rows(inputs, job_id, materialize_result)
end_time = temporalio.workflow.now()
blocked_duration_seconds = (end_time - start_time).total_seconds()
@@ -429,13 +448,13 @@ class MaterializeViewWorkflow(PostHogWorkflow):
)
# node-level metrics
- get_node_finished_metric("completed").add(1)
- get_node_duration_metric().record(duration_seconds)
- get_node_rows_materialized_metric().record(materialize_result.row_count)
+ get_node_finished_metric("completed", CLICKHOUSE_ENGINE).add(1)
+ get_node_duration_metric(CLICKHOUSE_ENGINE).record(duration_seconds)
+ get_node_rows_materialized_metric(CLICKHOUSE_ENGINE).record(materialize_result.row_count)
if storage_result.storage_delta_mib is not None and storage_result.storage_delta_mib >= 0:
- get_node_storage_delta_mib_metric().record(storage_result.storage_delta_mib)
+ get_node_storage_delta_mib_metric(CLICKHOUSE_ENGINE).record(storage_result.storage_delta_mib)
if storage_result.total_storage_mib is not None:
- get_node_total_storage_mib_metric().record(storage_result.total_storage_mib)
+ get_node_total_storage_mib_metric(CLICKHOUSE_ENGINE).record(storage_result.total_storage_mib)
return MaterializeViewWorkflowResult(
job_id=job_id,
@@ -487,7 +506,7 @@ class MaterializeViewWorkflow(PostHogWorkflow):
f"Failed to mark job as failed: {str(fail_err)}",
extra=inputs.properties_to_log,
)
- get_node_finished_metric("cancelled" if cancelled else "failed").add(1)
+ get_node_finished_metric("cancelled" if cancelled else "failed", CLICKHOUSE_ENGINE).add(1)
raise
# Keep the parent workflow's concurrency slot until managed warehouse finishes the query.
@@ -495,7 +514,11 @@ class MaterializeViewWorkflow(PostHogWorkflow):
if managed_warehouse_shadow_handle is not None:
try:
result = await managed_warehouse_shadow_handle
+ _record_managed_warehouse_node_metrics(result)
except Exception as shadow_err:
+ get_node_finished_metric(
+ "cancelled" if _is_cancellation(shadow_err) else "failed", MANAGED_WAREHOUSE_ENGINE
+ ).add(1)
await self._finalize_orphaned_managed_warehouse_job(managed_warehouse_job_id, inputs, str(shadow_err))
temporalio.workflow.logger.warning(
f"Managed warehouse shadow activity failed (managed_warehouse_only): {str(shadow_err)}",
diff --git a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
index 901ae2d79d8e..3281332a7312 100644
--- a/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_execute_dag_workflow.py
@@ -1153,18 +1153,25 @@ class TestTrinoShadowRun:
assert {call.args[1] for call in node_count.call_args_list} == {expected_engine}
@pytest.mark.parametrize(
- "error",
+ "error,expected_outcome",
[
+ pytest.param(None, "started", id="started"),
pytest.param(
WorkflowAlreadyStartedError("execute-dag-trino-dag:3600", "data-modeling-execute-dag"),
+ "skipped_still_running",
id="previous_shadow_still_running",
),
- pytest.param(RuntimeError("task queue is gone"), id="start_failed"),
+ pytest.param(RuntimeError("task queue is gone"), "error", id="start_failed"),
],
)
- async def test_a_shadow_that_cannot_start_does_not_fail_the_clickhouse_run(self, error: Exception) -> None:
- outcome = await self._run(ExecuteDAGInputs(team_id=7, dag_id="dag"), shadow_start_error=error)
+ async def test_a_shadow_start_is_counted_by_outcome_and_never_fails_the_clickhouse_run(
+ self, error: Exception | None, expected_outcome: str
+ ) -> None:
+ # A shadow that hangs until its timeout emits no DAG metric, so the skip count is what alerts on it.
+ with patch("posthog.temporal.data_modeling.workflows.execute_dag.get_trino_shadow_start_metric") as start:
+ outcome = await self._run(ExecuteDAGInputs(team_id=7, dag_id="dag"), shadow_start_error=error)
+ assert [call.args[0] for call in start.call_args_list] == [expected_outcome]
assert outcome.result.successful_nodes == 2
assert outcome.result.failed_nodes == 0
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
index df250b7801df..7324422a94b2 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_workflow.py
@@ -52,6 +52,11 @@ def _materialize_result(quality_audit: QualityAuditMode) -> MaterializeViewResul
class TestQualityGateBranching:
+ metrics: dict[str, MagicMock]
+
+ def setup_method(self) -> None:
+ self.metrics = {}
+
async def _run(
self,
activity_results: list,
@@ -98,7 +103,7 @@ class TestQualityGateBranching:
"get_managed_warehouse_shadow_storage_mib_metrics",
"get_managed_warehouse_shadow_storage_delta_mib_metrics",
):
- stack.enter_context(patch(f"{WORKFLOW_MODULE}.{metric}"))
+ self.metrics[metric] = stack.enter_context(patch(f"{WORKFLOW_MODULE}.{metric}"))
result = await MaterializeViewWorkflow().run(inputs or _inputs())
return result, execute_activity
@@ -161,6 +166,10 @@ class TestQualityGateBranching:
assert result.trino_materialized is True
assert result.job_id == "shadow-job"
+ finished = self.metrics["get_node_finished_metric"]
+ assert finished.call_args.args == ("failed" if shadow_error else "completed", "managed_warehouse")
+ assert self.metrics["get_node_duration_metric"].called is (shadow_error is None)
+
async def test_a_clickhouse_run_does_not_wait_for_a_slow_trino_shadow(self) -> None:
results = {
"check_managed_warehouse_shadow_eligibility_activity": True,