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-catalog): instrument catalog reads, metric runs, and join probes (#82843)

Thiago Salvatorecdace5745836
diff --git a/posthog/hogql/database/data_catalog_metrics.py b/posthog/hogql/database/data_catalog_metrics.py
new file mode 100644
index 000000000000..4c316354a7c0
--- /dev/null
+++ b/posthog/hogql/database/data_catalog_metrics.py
@@ -0,0 +1,40 @@
+from typing import Literal, get_args
+
+from prometheus_client import Counter
+
+CatalogSurface = Literal[
+ "metrics",
+ "certifications",
+ "relationships",
+ "relationship_proposals",
+ "tables",
+ "schema_serialization",
+ "table_visibility",
+]
+
+DATA_CATALOG_READS_COUNTER = Counter(
+ "posthog_data_catalog_reads_total",
+ "Data catalog reads attempted, per surface. The denominator for posthog_data_catalog_read_failures_total",
+ labelnames=["surface"],
+)
+
+DATA_CATALOG_READ_FAILURES_COUNTER = Counter(
+ "posthog_data_catalog_read_failures_total",
+ "Data catalog reads that failed and fell back to an empty result. The caller sees an empty catalog "
+ "rather than an error, so every failure silently hides governed metrics, trust marks, or joins. "
+ "Alert on a sustained rate rather than on any single failure: one team's broken definition "
+ "increments on every read until it is fixed. The structured log next to each increment carries team_id",
+ labelnames=["surface"],
+)
+
+for _surface in get_args(CatalogSurface):
+ DATA_CATALOG_READS_COUNTER.labels(surface=_surface)
+ DATA_CATALOG_READ_FAILURES_COUNTER.labels(surface=_surface)
+
+
+def record_catalog_read(surface: CatalogSurface) -> None:
+ DATA_CATALOG_READS_COUNTER.labels(surface=surface).inc()
+
+
+def record_catalog_read_failure(surface: CatalogSurface) -> None:
+ DATA_CATALOG_READ_FAILURES_COUNTER.labels(surface=surface).inc()
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index d44ef6f1def4..42459638fb3c 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -20,6 +20,7 @@ from pydantic import BaseModel, ConfigDict
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.data_catalog_metrics import record_catalog_read, record_catalog_read_failure
from posthog.hogql.database.direct_sql_table import DirectSQLTable
from posthog.hogql.database.lazy_join_tags import (
DATA_WAREHOUSE,
@@ -2684,6 +2685,7 @@ def _settled_catalog_certifications(
if team is None or team_id is None or not is_data_catalog_enabled(team) or not _can_read_catalog(context):
return {}, {}
+ record_catalog_read("schema_serialization")
by_table_id: dict[str, DatabaseSchemaTableCertification] = {}
by_saved_query_id: dict[str, DatabaseSchemaTableCertification] = {}
certifications = (
@@ -2707,6 +2709,7 @@ def _settled_catalog_certifications(
by_saved_query_id[str(certification.saved_query_id)] = serialized
return by_table_id, by_saved_query_id
except Exception:
+ record_catalog_read_failure("schema_serialization")
logger.exception("serialize_database: failed to load catalog certifications", team_id=team_id)
return {}, {}
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index a8352f7f2ffe..2e75ca93e80a 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -22,6 +22,7 @@ from django.db.models import Q
import structlog
from posthog.hogql import ast
+from posthog.hogql.database.data_catalog_metrics import record_catalog_read, record_catalog_read_failure
from posthog.hogql.database.models import (
BooleanDatabaseField,
DANGEROUS_NoTeamIdCheckTable,
@@ -953,6 +954,7 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])
from products.data_catalog.backend.facade.api import compute_drift # noqa: PLC0415
from products.data_catalog.backend.facade.models import Metric # noqa: PLC0415
+ record_catalog_read("metrics")
try:
denied = context.database._denied_tables if context.database is not None else set()
queryset = (
@@ -987,6 +989,7 @@ def _catalog_metrics(context: "HogQLContext", allowed: Optional[frozenset[str]])
)
return rows
except Exception:
+ record_catalog_read_failure("metrics")
logger.exception("information_schema: failed to load catalog metrics", team_id=team_id)
return []
@@ -1026,6 +1029,7 @@ def _catalog_certifications(context: "HogQLContext", allowed: Optional[frozenset
from products.data_catalog.backend.facade.enums import CertificationStatus # noqa: PLC0415
from products.data_catalog.backend.facade.models import TableCertification # noqa: PLC0415
+ record_catalog_read("tables")
try:
result: dict[tuple[str, str], str] = {}
certs = TableCertification.objects.for_team(team_id).filter(
@@ -1046,6 +1050,7 @@ def _catalog_certifications(context: "HogQLContext", allowed: Optional[frozenset
result[("view", str(saved_query_id))] = status
return result
except Exception:
+ record_catalog_read_failure("tables")
logger.exception("information_schema: failed to load certifications", team_id=team_id)
return {}
@@ -1054,9 +1059,16 @@ def _catalog_table_visible(context: "HogQLContext", table_name: str) -> bool:
database = context.database
if database is None or _references_denied_table([table_name], database._denied_tables):
return False
+ record_catalog_read("table_visibility")
try:
return database.has_table(table_name) and database.get_table(table_name) is not None
except Exception:
+ record_catalog_read_failure("table_visibility")
+ logger.exception(
+ "information_schema: failed to resolve catalog table visibility",
+ table_name=table_name,
+ team_id=context.team_id,
+ )
return False
@@ -1079,6 +1091,7 @@ def _catalog_accepted_relationships(
from products.data_catalog.backend.facade.enums import RelationshipStatus # noqa: PLC0415
from products.data_catalog.backend.facade.models import RelationshipProposal # noqa: PLC0415
+ record_catalog_read("relationships")
try:
accepted = RelationshipProposal.objects.for_team(team_id).filter(
status=RelationshipStatus.ACCEPTED,
@@ -1138,6 +1151,7 @@ def _catalog_accepted_relationships(
)
return result
except Exception:
+ record_catalog_read_failure("relationships")
logger.exception("information_schema: failed to load accepted relationships", team_id=team_id)
return {}
@@ -1156,6 +1170,7 @@ def _catalog_relationship_proposals(context: "HogQLContext", allowed: Optional[f
from products.data_catalog.backend.facade.enums import RelationshipStatus # noqa: PLC0415
from products.data_catalog.backend.facade.models import RelationshipProposal # noqa: PLC0415
+ record_catalog_read("relationship_proposals")
try:
proposals = RelationshipProposal.objects.for_team(team_id).filter(status=RelationshipStatus.PROPOSED)
if allowed is not None:
@@ -1183,6 +1198,7 @@ def _catalog_relationship_proposals(context: "HogQLContext", allowed: Optional[f
)
return rows
except Exception:
+ record_catalog_read_failure("relationship_proposals")
logger.exception("information_schema: failed to load relationship proposals", team_id=team_id)
return []
@@ -1200,6 +1216,7 @@ def _catalog_certification_rows(context: "HogQLContext", allowed: Optional[froze
return []
from products.data_catalog.backend.facade.models import TableCertification # noqa: PLC0415
+ record_catalog_read("certifications")
try:
certs = (
TableCertification.objects.for_team(team_id)
@@ -1239,6 +1256,7 @@ def _catalog_certification_rows(context: "HogQLContext", allowed: Optional[froze
)
return rows
except Exception:
+ record_catalog_read_failure("certifications")
logger.exception("information_schema: failed to load certifications table", team_id=team_id)
return []
diff --git a/products/data_catalog/backend/logic/execution.py b/products/data_catalog/backend/logic/execution.py
index bbc65c9e7199..1eb38baee74c 100644
--- a/products/data_catalog/backend/logic/execution.py
+++ b/products/data_catalog/backend/logic/execution.py
@@ -9,6 +9,7 @@ included — so opening it reproduces exactly what ran.
"""
import json
+import time
from copy import deepcopy
from datetime import timedelta
from typing import TYPE_CHECKING, Optional
@@ -37,6 +38,7 @@ from posthog.models import Team, User
from posthog.utils import absolute_uri
from ..facade.enums import HOGQL_DEFINITION_KIND, MARKDOWN_DEFINITION_KIND, NODE_DEFINITION_KINDS
+from ..metrics import metric_run_outcome, metric_run_outcome_for
from ..models import Metric
from .analytics import METRIC_RUN_EVENT, METRIC_RUN_FAILED_EVENT, capture_metric_event
from .drift import compute_drift
@@ -63,72 +65,94 @@ def run_metric(
query_id: Optional[str] = None,
request: "Request | None" = None,
) -> dict:
- if not metric.definition:
- raise MetricHasNoDefinition()
+ with metric_run_outcome(metric.definition_kind) as run:
+ if not metric.definition:
+ run.record("rejected")
+ raise MetricHasNoDefinition()
- is_drifted = compute_drift([metric])[metric.id]
+ is_drifted = compute_drift([metric])[metric.id]
- def capture_run(event: str, **extra: object) -> None:
- capture_metric_event(
- event, metric, team=team, user=user, request=request, extra={"is_drifted": is_drifted, **extra}
+ def capture_run(event: str, **extra: object) -> None:
+ capture_metric_event(
+ event, metric, team=team, user=user, request=request, extra={"is_drifted": is_drifted, **extra}
+ )
+
+ if metric.definition_kind == MARKDOWN_DEFINITION_KIND:
+ # Agent-calculated: return the steps to follow instead of executing a query. Still recorded
+ # as a run for attribution.
+ _touch_last_run(team, metric)
+ capture_run(METRIC_RUN_EVENT)
+ return _markdown_envelope(metric, is_drifted)
+
+ try:
+ query = prepare_execution_query(metric.definition, date_from=date_from, date_to=date_to, interval=interval)
+ except ValidationError:
+ run.record("rejected")
+ raise
+
+ execution_mode = (
+ execution_mode_from_refresh(refresh) if refresh else ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
)
+ started_at = time.monotonic()
+ try:
+ with tags_context(product=Product.DATA_CATALOG, feature=Feature.QUERY):
+ raw = process_query_dict(
+ team,
+ query,
+ execution_mode=execution_mode,
+ user=user,
+ query_id=query_id,
+ # Mirror /query and endpoint execution: API-key runs are subject to the same query
+ # safeguards (rejected constructs, API-team concurrency limiter) as those paths.
+ is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),
+ )
+ except (ExposedHogQLError, ExposedCHQueryError) as e:
+ run.record(metric_run_outcome_for(e))
+ capture_run(METRIC_RUN_FAILED_EVENT, reason="definition_error")
+ raise ValidationError(
+ {
+ "definition": f"This metric could not run: {e} "
+ "A table or column it references may no longer exist. Check system.information_schema.tables."
+ }
+ )
+ except ConcurrencyLimitExceeded:
+ run.record("concurrency_limited")
+ raise Throttled(detail=_CONCURRENCY_LIMIT_MESSAGE)
+ except ValidationError:
+ run.record("rejected")
+ raise
+ except Exception as e:
+ run.record(metric_run_outcome_for(e))
+ capture_exception(e)
+ raise
+ elapsed_seconds = time.monotonic() - started_at
+
+ payload = raw.model_dump(mode="json") if isinstance(raw, BaseModel) else raw
+ payload = payload if isinstance(payload, dict) else {}
+ if payload.get("error"):
+ # The engine reports schema-validation failures as an error payload instead of raising; a
+ # run that produced no results must not read as a success.
+ run.record("invalid_query")
+ capture_run(METRIC_RUN_FAILED_EVENT, reason="invalid_query")
+ raise ValidationError(
+ {
+ "definition": f"This metric could not run: {payload['error']} "
+ "The definition (or a date/interval override) does not form a valid query."
+ }
+ )
+
+ if _is_async_enqueue(payload):
+ run.record("async_enqueued")
+ else:
+ run.observe_duration(elapsed_seconds)
- if metric.definition_kind == MARKDOWN_DEFINITION_KIND:
- # Agent-calculated: return the steps to follow instead of executing a query. Still recorded
- # as a run for attribution.
_touch_last_run(team, metric)
capture_run(METRIC_RUN_EVENT)
- return _markdown_envelope(metric, is_drifted)
-
- query = prepare_execution_query(metric.definition, date_from=date_from, date_to=date_to, interval=interval)
-
- execution_mode = (
- execution_mode_from_refresh(refresh) if refresh else ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
- )
- try:
- with tags_context(product=Product.DATA_CATALOG, feature=Feature.QUERY):
- raw = process_query_dict(
- team,
- query,
- execution_mode=execution_mode,
- user=user,
- query_id=query_id,
- # Mirror /query and endpoint execution: API-key runs are subject to the same query
- # safeguards (rejected constructs, API-team concurrency limiter) as those paths.
- is_query_service=is_api_key_access_method(get_query_tag_value("access_method")),
- )
- except (ExposedHogQLError, ExposedCHQueryError) as e:
- capture_run(METRIC_RUN_FAILED_EVENT, reason="definition_error")
- raise ValidationError(
- {
- "definition": f"This metric could not run: {e} "
- "A table or column it references may no longer exist. Check system.information_schema.tables."
- }
- )
- except ConcurrencyLimitExceeded:
- raise Throttled(detail=_CONCURRENCY_LIMIT_MESSAGE)
- except ValidationError:
- raise
- except Exception as e:
- capture_exception(e)
- raise
-
- payload = raw.model_dump(mode="json") if isinstance(raw, BaseModel) else raw
- payload = payload if isinstance(payload, dict) else {}
- if payload.get("error"):
- # The engine reports schema-validation failures as an error payload instead of raising; a
- # run that produced no results must not read as a success.
- capture_run(METRIC_RUN_FAILED_EVENT, reason="invalid_query")
- raise ValidationError(
- {
- "definition": f"This metric could not run: {payload['error']} "
- "The definition (or a date/interval override) does not form a valid query."
- }
- )
+ return _envelope(metric, payload, team, query, is_drifted)
+
- _touch_last_run(team, metric)
- capture_run(METRIC_RUN_EVENT)
- return _envelope(metric, payload, team, query, is_drifted)
+def _is_async_enqueue(payload: dict) -> bool:
+ return payload.get("results") is None and payload.get("query_status") is not None
def prepare_execution_query(
diff --git a/products/data_catalog/backend/logic/relationships.py b/products/data_catalog/backend/logic/relationships.py
index 4b9246d098b4..e7b420a781e7 100644
--- a/products/data_catalog/backend/logic/relationships.py
+++ b/products/data_catalog/backend/logic/relationships.py
@@ -34,12 +34,14 @@ from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.errors import ExposedCHQueryError
from posthog.exceptions_capture import capture_exception
from posthog.models import Team, User
from products.data_tools.backend.facade.models import DataWarehouseJoin
from ..facade.enums import RelationshipStatus
+from ..metrics import record_relationship_probe, relationship_probe_outcome_for
from ..models import RelationshipProposal
from .analytics import (
RELATIONSHIP_ACCEPTED_EVENT,
@@ -168,56 +170,64 @@ def _probe_join(
proposal: RelationshipProposal, user: Optional[User], *, existing_join: Optional[DataWarehouseJoin]
) -> None:
"""Prove the join works by running SELECT {joined_field} FROM {source} LIMIT 10 through it."""
- database = Database.create_for(team_id=proposal.team_id, user=user)
- from_field = get_join_field_chain(proposal.source_table_key)
- to_field = get_join_field_chain(proposal.joining_table_key)
- if from_field is None or to_field is None:
- raise ValidationError({"keys": "Join keys must be field expressions."})
-
try:
- source_table = database.get_table(proposal.source_table_name)
- joining_table = database.get_table(proposal.joining_table_name)
- existing_field = source_table.fields.get(proposal.field_name)
- if existing_field is not None and existing_join is None:
- raise ValidationError(
- {"field_name": f"'{proposal.field_name}' is already a field on '{proposal.source_table_name}'."}
- )
- # Mirror the resolver selection Database uses when it materializes the real join, so the
- # probe exercises the same code path -- otherwise an experiments-optimized join is probed with
- # the plain equality resolver and an invalid experiments_timestamp_key survives review.
- configuration = proposal.configuration if isinstance(proposal.configuration, dict) else {}
- use_experiments = bool(proposal.joining_table_name == "events" and configuration.get("experiments_optimized"))
- source_table.fields["_catalog_probe"] = LazyJoin(
- from_field=from_field,
- to_field=to_field,
- join_table=joining_table,
- resolver=DATA_WAREHOUSE_EXPERIMENTS if use_experiments else DATA_WAREHOUSE,
- resolver_params=data_warehouse_resolver_params(
- source_table_key=proposal.source_table_key,
- joining_table_key=proposal.joining_table_key,
- joining_table_name=proposal.joining_table_name,
- configuration=proposal.configuration,
- override_join_type="INNER JOIN",
- ),
- )
- validation_query = parse_select(
- "SELECT {to_field} FROM {source_table_name} LIMIT 10",
- placeholders={
- "to_field": ast.Field(chain=["_catalog_probe", *to_field]),
- "source_table_name": parse_expr(proposal.source_table_name),
- },
- )
- tag_queries(product=Product.WAREHOUSE, feature=Feature.QUERY)
- execute_hogql_query(
- query=validation_query, team=proposal.team, context=HogQLContext(database=database, user=user)
- )
+ _execute_probe(proposal, user, existing_join=existing_join)
except ValidationError:
+ record_relationship_probe("join_invalid")
raise
- except ExposedHogQLError as e:
+ except (ExposedHogQLError, ExposedCHQueryError) as e:
+ record_relationship_probe(relationship_probe_outcome_for(e))
raise ValidationError({"join": f"The join does not work: {e}"})
except Exception as e:
+ record_relationship_probe(relationship_probe_outcome_for(e))
capture_exception(e)
raise ValidationError({"join": "The join could not be validated against the data."})
+ record_relationship_probe("ok")
+
+
+def _execute_probe(
+ proposal: RelationshipProposal, user: Optional[User], *, existing_join: Optional[DataWarehouseJoin]
+) -> None:
+ database = Database.create_for(team_id=proposal.team_id, user=user)
+ from_field = get_join_field_chain(proposal.source_table_key)
+ to_field = get_join_field_chain(proposal.joining_table_key)
+ if from_field is None or to_field is None:
+ raise ValidationError({"keys": "Join keys must be field expressions."})
+
+ source_table = database.get_table(proposal.source_table_name)
+ joining_table = database.get_table(proposal.joining_table_name)
+ existing_field = source_table.fields.get(proposal.field_name)
+ if existing_field is not None and existing_join is None:
+ raise ValidationError(
+ {"field_name": f"'{proposal.field_name}' is already a field on '{proposal.source_table_name}'."}
+ )
+ # Mirror the resolver selection Database uses when it materializes the real join, so the
+ # probe exercises the same code path -- otherwise an experiments-optimized join is probed with
+ # the plain equality resolver and an invalid experiments_timestamp_key survives review.
+ configuration = proposal.configuration if isinstance(proposal.configuration, dict) else {}
+ use_experiments = bool(proposal.joining_table_name == "events" and configuration.get("experiments_optimized"))
+ source_table.fields["_catalog_probe"] = LazyJoin(
+ from_field=from_field,
+ to_field=to_field,
+ join_table=joining_table,
+ resolver=DATA_WAREHOUSE_EXPERIMENTS if use_experiments else DATA_WAREHOUSE,
+ resolver_params=data_warehouse_resolver_params(
+ source_table_key=proposal.source_table_key,
+ joining_table_key=proposal.joining_table_key,
+ joining_table_name=proposal.joining_table_name,
+ configuration=proposal.configuration,
+ override_join_type="INNER JOIN",
+ ),
+ )
+ validation_query = parse_select(
+ "SELECT {to_field} FROM {source_table_name} LIMIT 10",
+ placeholders={
+ "to_field": ast.Field(chain=["_catalog_probe", *to_field]),
+ "source_table_name": parse_expr(proposal.source_table_name),
+ },
+ )
+ tag_queries(product=Product.DATA_CATALOG, feature=Feature.QUERY)
+ execute_hogql_query(query=validation_query, team=proposal.team, context=HogQLContext(database=database, user=user))
def _acquire_accessor_lock(proposal: RelationshipProposal) -> None:
diff --git a/products/data_catalog/backend/metrics.py b/products/data_catalog/backend/metrics.py
new file mode 100644
index 000000000000..9f5a7fc3ee5d
--- /dev/null
+++ b/products/data_catalog/backend/metrics.py
@@ -0,0 +1,140 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Literal, get_args
+
+from prometheus_client import Counter, Histogram
+
+from posthog.errors import QueryErrorCategory, classify_query_error
+
+from .facade.enums import HOGQL_DEFINITION_KIND, MARKDOWN_DEFINITION_KIND, NODE_DEFINITION_KINDS
+
+MetricRunOutcome = Literal[
+ "success",
+ "definition_error",
+ "invalid_query",
+ "rejected",
+ "query_performance",
+ "capacity",
+ "cancelled",
+ "concurrency_limited",
+ "async_enqueued",
+ "internal_error",
+]
+
+DefinitionKindLabel = Literal["hogql", "insight", "node", "markdown", "none"]
+
+RelationshipProbeOutcome = Literal["ok", "join_invalid", "query_performance", "capacity", "cancelled", "error"]
+
+METRIC_RUNS_COUNTER = Counter(
+ "posthog_data_catalog_metric_runs_total",
+ "Canonical metric runs, one per invocation. "
+ "outcome is success (results returned, markdown metrics included); "
+ "definition_error (the stored definition no longer runs — the table or column it names is gone); "
+ "invalid_query (the engine rejected the prepared query, returned as 400); "
+ "rejected (refused before execution: no definition, or a date override on a fixed-window metric); "
+ "query_performance (the query hit a ClickHouse cost guardrail — timeout/memory/size/estimated-too-slow); "
+ "capacity (shared ClickHouse pool momentarily saturated); "
+ "cancelled (the caller dropped the query); "
+ "concurrency_limited (denominator only — alert on posthog_clickhouse_query_concurrency_limit_exceeded); "
+ "async_enqueued (a query status was returned to poll, not results — completion lands in the generic query series); "
+ "or internal_error (unexpected system failure). "
+ 'Only internal_error is a system fault — alert on outcome="internal_error", and on the '
+ "definition_error + invalid_query + internal_error ratio for catalog rot.",
+ labelnames=["definition_kind", "outcome"],
+)
+
+METRIC_RUN_DURATION_SECONDS = Histogram(
+ "posthog_data_catalog_metric_run_duration_seconds",
+ "Blocking metric-run duration; only runs that returned results are observed (async enqueues excluded)",
+ labelnames=["kind"],
+ buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 45, 90, 180, 300, float("inf")),
+)
+
+RELATIONSHIP_PROBE_COUNTER = Counter(
+ "posthog_data_catalog_relationship_probe_total",
+ "Live join probes run while accepting a relationship proposal. "
+ "outcome is ok; join_invalid (the proposed join does not work against the team's data, returned as 400); "
+ "query_performance (the probe query hit a ClickHouse cost guardrail); "
+ "capacity (shared ClickHouse pool momentarily saturated); cancelled (the caller dropped the query); "
+ 'or error (the probe itself broke). Only error is a system fault — alert on outcome="error", '
+ "because no relationship can be accepted while the probe is broken.",
+ labelnames=["outcome"],
+)
+
+# Both counters classify a query failure with the same function the query SLO path uses, so a
+# ClickHouse cost guardrail or a saturated pool never reads as a broken definition or a broken probe.
+_RUN_OUTCOME_BY_CATEGORY: dict[QueryErrorCategory, MetricRunOutcome] = {
+ QueryErrorCategory.USER_ERROR: "definition_error",
+ QueryErrorCategory.QUERY_PERFORMANCE_ERROR: "query_performance",
+ QueryErrorCategory.RATE_LIMITED: "capacity",
+ QueryErrorCategory.CANCELLED: "cancelled",
+ QueryErrorCategory.ERROR: "internal_error",
+}
+
+_PROBE_OUTCOME_BY_CATEGORY: dict[QueryErrorCategory, RelationshipProbeOutcome] = {
+ QueryErrorCategory.USER_ERROR: "join_invalid",
+ QueryErrorCategory.QUERY_PERFORMANCE_ERROR: "query_performance",
+ QueryErrorCategory.RATE_LIMITED: "capacity",
+ QueryErrorCategory.CANCELLED: "cancelled",
+ QueryErrorCategory.ERROR: "error",
+}
+
+for _kind in get_args(DefinitionKindLabel):
+ METRIC_RUN_DURATION_SECONDS.labels(kind=_kind)
+ for _outcome in get_args(MetricRunOutcome):
+ METRIC_RUNS_COUNTER.labels(definition_kind=_kind, outcome=_outcome)
+
+for _probe_outcome in get_args(RelationshipProbeOutcome):
+ RELATIONSHIP_PROBE_COUNTER.labels(outcome=_probe_outcome)
+
+
+def definition_kind_label(definition_kind: str | None) -> DefinitionKindLabel:
+ if definition_kind is None:
+ return "none"
+ if definition_kind == HOGQL_DEFINITION_KIND:
+ return "hogql"
+ if definition_kind == MARKDOWN_DEFINITION_KIND:
+ return "markdown"
+ if definition_kind in NODE_DEFINITION_KINDS:
+ return "node"
+ return "insight"
+
+
+class MetricRunRecorder:
+ def __init__(self, kind: DefinitionKindLabel) -> None:
+ self._kind = kind
+ self._recorded = False
+
+ def record(self, outcome: MetricRunOutcome) -> None:
+ if self._recorded:
+ return
+ self._recorded = True
+ METRIC_RUNS_COUNTER.labels(definition_kind=self._kind, outcome=outcome).inc()
+
+ def observe_duration(self, seconds: float) -> None:
+ METRIC_RUN_DURATION_SECONDS.labels(kind=self._kind).observe(seconds)
+
+
+@contextmanager
+def metric_run_outcome(definition_kind: str | None) -> Iterator[MetricRunRecorder]:
+ """Record exactly one outcome per run: the first outcome claimed inside the block wins."""
+ recorder = MetricRunRecorder(definition_kind_label(definition_kind))
+ try:
+ yield recorder
+ except Exception:
+ recorder.record("internal_error")
+ raise
+ else:
+ recorder.record("success")
+
+
+def metric_run_outcome_for(error: Exception) -> MetricRunOutcome:
+ return _RUN_OUTCOME_BY_CATEGORY.get(classify_query_error(error), "internal_error")
+
+
+def relationship_probe_outcome_for(error: Exception) -> RelationshipProbeOutcome:
+ return _PROBE_OUTCOME_BY_CATEGORY.get(classify_query_error(error), "error")
+
+
+def record_relationship_probe(outcome: RelationshipProbeOutcome) -> None:
+ RELATIONSHIP_PROBE_COUNTER.labels(outcome=outcome).inc()
diff --git a/products/data_catalog/backend/tests/test_information_schema.py b/products/data_catalog/backend/tests/test_information_schema.py
index 10114b0cbed6..d26c13501c09 100644
--- a/products/data_catalog/backend/tests/test_information_schema.py
+++ b/products/data_catalog/backend/tests/test_information_schema.py
@@ -1,17 +1,29 @@
import json
from collections.abc import Callable
+from typing import Any
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
from django.db import DatabaseError, connection
+from django.db.models import Model
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
+from prometheus_client import REGISTRY
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.database import Database
+from posthog.hogql.database.database import Database, _settled_catalog_certifications
+from posthog.hogql.database.schema import information_schema
+from posthog.hogql.database.schema.information_schema import (
+ _catalog_accepted_relationships,
+ _catalog_certification_rows,
+ _catalog_certifications,
+ _catalog_metrics,
+ _catalog_relationship_proposals,
+ _catalog_table_visible,
+)
from posthog.hogql.errors import QueryError
from posthog.hogql.query import execute_hogql_query
@@ -46,6 +58,15 @@ def _fail_queries_for_table(table_name: str) -> Callable[..., object]:
return wrapper
+_CATALOG_READERS: list[tuple[str, Callable[..., Any], type[Model], Any]] = [
+ ("metrics", _catalog_metrics, Metric, []),
+ ("tables", _catalog_certifications, TableCertification, {}),
+ ("certifications", _catalog_certification_rows, TableCertification, []),
+ ("relationships", _catalog_accepted_relationships, RelationshipProposal, {}),
+ ("relationship_proposals", _catalog_relationship_proposals, RelationshipProposal, []),
+]
+
+
class TestInformationSchemaMetrics(ClickhouseTestMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -864,3 +885,54 @@ class TestInformationSchemaCertificationsAndRelationships(ClickhouseTestMixin, A
"SELECT target_name FROM system.information_schema.certifications", team=self.team
)
assert response.results == []
+
+
+class TestCatalogReadCounters(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ flag_patch = patch("products.data_catalog.backend.facade.flags.is_data_catalog_enabled", return_value=True)
+ flag_patch.start()
+ self.addCleanup(flag_patch.stop)
+
+ def _context(self) -> HogQLContext:
+ database = Database.create_for(team=self.team, user=self.user)
+ return HogQLContext(team=self.team, team_id=self.team.pk, database=database)
+
+ def _counts(self, surface: str) -> tuple[float, float]:
+ return (
+ REGISTRY.get_sample_value("posthog_data_catalog_reads_total", {"surface": surface}) or 0.0,
+ REGISTRY.get_sample_value("posthog_data_catalog_read_failures_total", {"surface": surface}) or 0.0,
+ )
+
+ @parameterized.expand(_CATALOG_READERS)
+ def test_read_failure_increments_its_surface_and_stays_fail_soft(
+ self, surface: str, read: Callable[..., object], failing_model: type[Model], empty: object
+ ) -> None:
+ reads, failures = self._counts(surface)
+ with connection.execute_wrapper(_fail_queries_for_table(failing_model._meta.db_table)):
+ assert read(self._context(), None) == empty
+ assert self._counts(surface) == (reads + 1, failures + 1)
+
+ @parameterized.expand(_CATALOG_READERS)
+ def test_successful_read_counts_only_as_an_attempt(
+ self, surface: str, read: Callable[..., object], _failing_model: type[Model], _empty: object
+ ) -> None:
+ reads, failures = self._counts(surface)
+ read(self._context(), None)
+ assert self._counts(surface) == (reads + 1, failures)
+
+ def test_schema_serialization_failure_increments_and_returns_no_marks(self) -> None:
+ reads, failures = self._counts("schema_serialization")
+ with connection.execute_wrapper(_fail_queries_for_table(TableCertification._meta.db_table)):
+ assert _settled_catalog_certifications(self._context()) == ({}, {})
+ assert self._counts("schema_serialization") == (reads + 1, failures + 1)
+
+ def test_table_visibility_failure_increments_and_logs(self) -> None:
+ context = self._context()
+ reads, failures = self._counts("table_visibility")
+ with patch.object(Database, "has_table", side_effect=RuntimeError("database resolution broke")):
+ with patch.object(information_schema.logger, "exception") as log_exception:
+ assert _catalog_table_visible(context, "events") is False
+
+ assert self._counts("table_visibility") == (reads + 1, failures + 1)
+ assert log_exception.call_count == 1
diff --git a/products/data_catalog/backend/tests/test_instrumentation.py b/products/data_catalog/backend/tests/test_instrumentation.py
new file mode 100644
index 000000000000..50269a0cc8e8
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_instrumentation.py
@@ -0,0 +1,298 @@
+from typing import Any, Optional, cast, get_args
+
+from posthog.test.base import APIBaseTest, BaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+from rest_framework.exceptions import Throttled, ValidationError
+
+from posthog.hogql.database.data_catalog_metrics import CatalogSurface
+from posthog.hogql.errors import ExposedHogQLError, QueryError
+
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
+from posthog.clickhouse.query_tagging import Product, get_query_tags
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryTimeOut
+
+from products.data_catalog.backend.logic import relationships
+from products.data_catalog.backend.logic.exceptions import MetricHasNoDefinition
+from products.data_catalog.backend.logic.execution import run_metric
+from products.data_catalog.backend.logic.metrics import upsert_metric
+from products.data_catalog.backend.logic.relationships import accept_proposal, propose_relationship
+from products.data_catalog.backend.metrics import DefinitionKindLabel, MetricRunOutcome, RelationshipProbeOutcome
+
+_RUNS_METRIC = "posthog_data_catalog_metric_runs_total"
+_DURATION_COUNT_METRIC = "posthog_data_catalog_metric_run_duration_seconds_count"
+_PROBE_METRIC = "posthog_data_catalog_relationship_probe_total"
+_READS_METRIC = "posthog_data_catalog_reads_total"
+_READ_FAILURES_METRIC = "posthog_data_catalog_read_failures_total"
+
+_KINDS = get_args(DefinitionKindLabel)
+_OUTCOMES = get_args(MetricRunOutcome)
+_PROBE_OUTCOMES = get_args(RelationshipProbeOutcome)
+_SURFACES = get_args(CatalogSurface)
+
+_PROCESS_QUERY = "products.data_catalog.backend.logic.execution.process_query_dict"
+
+# ClickHouse error codes. Every one is user_safe, so all four surface as ExposedCHQueryError, but
+# they classify differently: a missing table is the definition's problem, a timeout is a cost
+# guardrail, and an unreadable S3 file is ours.
+_UNKNOWN_TABLE_CODE = 60
+_ILLEGAL_TYPE_CODE = 43
+_TIMEOUT_EXCEEDED_CODE = 159
+_S3_ERROR_CODE = 499
+
+_HOGQL = {"kind": "HogQLQuery", "query": "select count() as c from events"}
+_EVENTS_NODE = {"kind": "EventsNode", "event": "purchase"}
+_MARKDOWN = {"kind": "MarkdownDefinition", "markdown": "1. Count activated users."}
+_OK_PAYLOAD: dict[str, Any] = {"results": [[1]], "hogql": "SELECT 1"}
+_ASYNC_PAYLOAD: dict[str, Any] = {"results": None, "query_status": {"id": "abc", "complete": False}}
+
+_JOIN: dict[str, Any] = {
+ "source_table_name": "events",
+ "source_table_key": "distinct_id",
+ "joining_table_name": "persons",
+ "joining_table_key": "id",
+ "field_name": "linked_person",
+}
+
+
+def _sample(name: str, labels: dict[str, str]) -> float:
+ return REGISTRY.get_sample_value(name, labels) or 0.0
+
+
+def _run_outcomes() -> dict[tuple[str, str], float]:
+ return {
+ (kind, outcome): _sample(_RUNS_METRIC, {"definition_kind": kind, "outcome": outcome})
+ for kind in _KINDS
+ for outcome in _OUTCOMES
+ }
+
+
+def _durations() -> dict[str, float]:
+ return {kind: _sample(_DURATION_COUNT_METRIC, {"kind": kind}) for kind in _KINDS}
+
+
+def _probe_outcomes() -> dict[str, float]:
+ return {outcome: _sample(_PROBE_METRIC, {"outcome": outcome}) for outcome in _PROBE_OUTCOMES}
+
+
+def _delta(before: dict, after: dict) -> dict:
+ return {key: after[key] - value for key, value in before.items() if after[key] != value}
+
+
+class TestPreCreatedSeries(SimpleTestCase):
+ def test_every_alert_relevant_label_combination_exists_at_import(self) -> None:
+ for kind in _KINDS:
+ assert REGISTRY.get_sample_value(_DURATION_COUNT_METRIC, {"kind": kind}) is not None, kind
+ for outcome in _OUTCOMES:
+ assert (
+ REGISTRY.get_sample_value(_RUNS_METRIC, {"definition_kind": kind, "outcome": outcome}) is not None
+ ), f"{kind}/{outcome}"
+ for probe_outcome in _PROBE_OUTCOMES:
+ assert REGISTRY.get_sample_value(_PROBE_METRIC, {"outcome": probe_outcome}) is not None, probe_outcome
+ for surface in _SURFACES:
+ assert REGISTRY.get_sample_value(_READS_METRIC, {"surface": surface}) is not None, surface
+ assert REGISTRY.get_sample_value(_READ_FAILURES_METRIC, {"surface": surface}) is not None, surface
+
+
+class TestMetricRunOutcomes(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("blocking_success", _HOGQL, {"return_value": dict(_OK_PAYLOAD)}, {}, None, "hogql", "success"),
+ ("node_success", _EVENTS_NODE, {"return_value": dict(_OK_PAYLOAD)}, {}, None, "node", "success"),
+ ("markdown_success", _MARKDOWN, {"return_value": dict(_OK_PAYLOAD)}, {}, None, "markdown", "success"),
+ (
+ "async_enqueue",
+ _HOGQL,
+ {"return_value": dict(_ASYNC_PAYLOAD)},
+ {"refresh": "async"},
+ None,
+ "hogql",
+ "async_enqueued",
+ ),
+ (
+ "definition_error_hogql",
+ _HOGQL,
+ {"side_effect": ExposedHogQLError("no such table")},
+ {},
+ ValidationError,
+ "hogql",
+ "definition_error",
+ ),
+ (
+ "definition_error_clickhouse",
+ _HOGQL,
+ {"side_effect": ExposedCHQueryError("Unknown table", code=_UNKNOWN_TABLE_CODE)},
+ {},
+ ValidationError,
+ "hogql",
+ "definition_error",
+ ),
+ (
+ "invalid_query",
+ _HOGQL,
+ {"return_value": {"results": None, "error": "1 validation error"}},
+ {},
+ ValidationError,
+ "hogql",
+ "invalid_query",
+ ),
+ ("rejected_no_definition", None, {}, {}, MetricHasNoDefinition, "none", "rejected"),
+ ("rejected_date_override", _HOGQL, {}, {"date_from": "-7d"}, ValidationError, "hogql", "rejected"),
+ (
+ "rejected_safeguard",
+ _HOGQL,
+ {"side_effect": ValidationError("that construct is not allowed")},
+ {},
+ ValidationError,
+ "hogql",
+ "rejected",
+ ),
+ (
+ "concurrency_limited",
+ _HOGQL,
+ {"side_effect": ConcurrencyLimitExceeded("too many")},
+ {},
+ Throttled,
+ "hogql",
+ "concurrency_limited",
+ ),
+ (
+ "query_performance_timeout",
+ _HOGQL,
+ {"side_effect": ClickHouseQueryTimeOut()},
+ {},
+ ClickHouseQueryTimeOut,
+ "hogql",
+ "query_performance",
+ ),
+ (
+ "query_performance_exposed_guardrail",
+ _HOGQL,
+ {"side_effect": ExposedCHQueryError("timeout exceeded", code=_TIMEOUT_EXCEEDED_CODE)},
+ {},
+ ValidationError,
+ "hogql",
+ "query_performance",
+ ),
+ (
+ "capacity",
+ _HOGQL,
+ {"side_effect": ClickHouseAtCapacity()},
+ {},
+ ClickHouseAtCapacity,
+ "hogql",
+ "capacity",
+ ),
+ (
+ "internal_error_operational_clickhouse",
+ _HOGQL,
+ {"side_effect": ExposedCHQueryError("S3 file changed during read", code=_S3_ERROR_CODE)},
+ {},
+ ValidationError,
+ "hogql",
+ "internal_error",
+ ),
+ (
+ "internal_error",
+ _HOGQL,
+ {"side_effect": RuntimeError("engine bug")},
+ {},
+ RuntimeError,
+ "hogql",
+ "internal_error",
+ ),
+ ]
+ )
+ def test_run_records_exactly_one_outcome(
+ self,
+ _name: str,
+ definition: Optional[dict],
+ patch_kwargs: dict,
+ run_kwargs: dict,
+ expected_error: Optional[type[Exception]],
+ expected_kind: str,
+ expected_outcome: str,
+ ) -> None:
+ metric = upsert_metric(team=self.team, user=self.user, name="mrr", description="d", definition=definition)
+ outcomes_before, durations_before = _run_outcomes(), _durations()
+
+ with patch(_PROCESS_QUERY, **patch_kwargs):
+ if expected_error is not None:
+ with self.assertRaises(expected_error):
+ run_metric(team=self.team, metric=metric, user=self.user, **run_kwargs)
+ else:
+ run_metric(team=self.team, metric=metric, user=self.user, **run_kwargs)
+
+ assert _delta(outcomes_before, _run_outcomes()) == {(expected_kind, expected_outcome): 1.0}
+ timed = expected_outcome == "success" and expected_kind != "markdown"
+ assert _delta(durations_before, _durations()) == ({expected_kind: 1.0} if timed else {})
+
+
+class TestRelationshipProbeOutcomes(BaseTest):
+ def _propose(self):
+ return propose_relationship(team=self.team, user=self.user, **_JOIN)
+
+ @parameterized.expand(
+ [
+ ("ok", None, None, "ok"),
+ ("join_invalid_hogql", QueryError("no such column"), ValidationError, "join_invalid"),
+ (
+ "join_invalid_clickhouse",
+ ExposedCHQueryError("Illegal types of arguments", code=_ILLEGAL_TYPE_CODE),
+ ValidationError,
+ "join_invalid",
+ ),
+ ("query_performance", ClickHouseQueryTimeOut(), ValidationError, "query_performance"),
+ ("capacity", ClickHouseAtCapacity(), ValidationError, "capacity"),
+ ("error", RuntimeError("probe infrastructure down"), ValidationError, "error"),
+ ]
+ )
+ def test_probe_records_its_outcome(
+ self,
+ _name: str,
+ probe_error: Optional[Exception],
+ expected_error: Optional[type[Exception]],
+ expected_outcome: str,
+ ) -> None:
+ proposal = self._propose()
+ before = _probe_outcomes()
+
+ with patch.object(relationships, "execute_hogql_query", side_effect=probe_error):
+ if expected_error is not None:
+ with self.assertRaises(expected_error):
+ accept_proposal(proposal, self.user)
+ else:
+ accept_proposal(proposal, self.user)
+
+ assert _delta(before, _probe_outcomes()) == {expected_outcome: 1.0}
+
+ def test_clickhouse_rejection_reports_the_real_error(self) -> None:
+ proposal = self._propose()
+ with patch.object(
+ relationships,
+ "execute_hogql_query",
+ side_effect=ExposedCHQueryError("Illegal types of arguments", code=_ILLEGAL_TYPE_CODE),
+ ):
+ with self.assertRaises(ValidationError) as ctx:
+ accept_proposal(proposal, self.user)
+
+ assert "Illegal types of arguments" in str(cast(dict, ctx.exception.detail)["join"])
+
+ def test_probe_tags_queries_with_the_data_catalog_product(self) -> None:
+ # The probe attributed itself to the warehouse product, so its cost and failures landed under
+ # another product in the generic posthog_query_execution_* series.
+ proposal = self._propose()
+ captured: dict[str, object] = {}
+
+ def capture(*args: object, **kwargs: object) -> None:
+ captured["product"] = get_query_tags().product
+
+ with patch.object(relationships, "execute_hogql_query", side_effect=capture):
+ accept_proposal(proposal, self.user)
+
+ assert captured["product"] == Product.DATA_CATALOG
diff --git a/products/data_catalog/docs/production-monitoring.md b/products/data_catalog/docs/production-monitoring.md
index 12f972419a41..ee018bca7fc9 100644
--- a/products/data_catalog/docs/production-monitoring.md
+++ b/products/data_catalog/docs/production-monitoring.md
@@ -60,6 +60,103 @@ The Hog authoring constraints learned from those incidents still apply to any fu
- `trackToolSpan` captures an `$ai_span` (args + truncated results) for every tool by default, joining the same session trace, so a trace-target evaluation sees a call's args and result. Secret-bearing fields (passwords, `client_secret`, API keys, tokens) are redacted from both input and output before capture, so defaulting every tool on never lands a credential in telemetry.
- `execute-sql` is the one exception, because its payload is the query result and it serves all traffic. Spans are captured for its metadata queries only (SQL referencing `information_schema`, ~4.5% of calls): those results are small and describe what the agent knew about the workspace before writing its next query. That covers catalog lookups of `metrics`, `certifications`, and `relationships` without the telemetry layer naming them. The gate strips SQL comments and string literals before matching, so the marker inside a comment or literal on a data query does not pull the result into telemetry.
+## 4. Prometheus metrics and alerts
+
+Everything above measures agent behavior. This section measures the product itself: whether catalog reads, metric runs, and join probes are working. Everything in the data catalog runs synchronously inside web requests, so these are plain `prometheus_client` instruments scraped from the web pods.
+
+The instruments ship in this repo: the run and probe counters in `products/data_catalog/backend/metrics.py`, the read counters in `posthog/hogql/database/data_catalog_metrics.py` (core cannot import product internals, and the loaders that set them live in core). The alert rules do not ship here: vmalert rules live in the private PostHog/charts repo, and Grafana dashboards are UI-managed. The expressions below are the proposed starting points to land there. Every label combination is pre-created at import, so an expression can be validated against live series before any incident.
+
+### Metrics
+
+| Metric | Labels | What it measures |
+| -------------------------------------------------- | ---------------------------- | ----------------------------------------------------------------- |
+| `posthog_data_catalog_reads_total` | `surface` | Catalog reads attempted. The denominator for the failure counter. |
+| `posthog_data_catalog_read_failures_total` | `surface` | Catalog reads that failed and returned an empty result. |
+| `posthog_data_catalog_metric_runs_total` | `definition_kind`, `outcome` | Canonical metric runs, exactly one per invocation. |
+| `posthog_data_catalog_metric_run_duration_seconds` | `kind` | Blocking metric runs that returned results. |
+| `posthog_data_catalog_relationship_probe_total` | `outcome` | Live join probes run while accepting a relationship proposal. |
+
+`surface` names the read that broke, not the model it reads:
+
+| `surface` | Loader | What disappears when it fails |
+| ------------------------ | --------------------------------- | --------------------------------------------------------------------------------------------- |
+| `metrics` | `_catalog_metrics` | `information_schema.metrics` returns no rows. |
+| `tables` | `_catalog_certifications` | The `certification` column on `information_schema.tables` reads as null. |
+| `certifications` | `_catalog_certification_rows` | `information_schema.certifications` returns no rows. |
+| `relationships` | `_catalog_accepted_relationships` | Accepted joins lose their confidence and reasoning. |
+| `relationship_proposals` | `_catalog_relationship_proposals` | The review queue reads as empty. |
+| `table_visibility` | `_catalog_table_visible` | Individual relationship and certification rows vanish while their own loader reports success. |
+| `schema_serialization` | `_settled_catalog_certifications` | Trust marks vanish from the serialized database schema. |
+
+No counter carries `team_id`. Each increment sits next to a `logger.exception` that does, so the counter says something is broken and the structured log says for whom.
+
+### How a failed query picks its outcome
+
+Both the run counter and the probe counter classify a failed query with `classify_query_error`, the same function the query SLO path uses. That keeps three classes of failure out of the buckets people alert on:
+
+| `classify_query_error` category | Metric run outcome | Probe outcome |
+| ------------------------------- | ------------------- | ------------------- |
+| `USER_ERROR` | `definition_error` | `join_invalid` |
+| `QUERY_PERFORMANCE_ERROR` | `query_performance` | `query_performance` |
+| `RATE_LIMITED` | `capacity` | `capacity` |
+| `CANCELLED` | `cancelled` | `cancelled` |
+| `ERROR` | `internal_error` | `error` |
+
+The distinction is not cosmetic. A metric that times out is the query's cost, not a rotten definition, so it must not raise the rot ratio. A ClickHouse error that the classifier calls `ERROR` (an unreadable Parquet file, an S3 object that changed under a warehouse table) is ours to fix, so it must not read as a user's broken definition. A timeout on a join probe does not mean the probe is broken, so it must not page.
+
+`concurrency_limited` stays separate from `capacity`: it is the API concurrency limiter rejecting the run with a 429, not the shared ClickHouse pool saturating.
+
+### Proposed alerts
+
+**Catalog reads are failing** (warning, not a page). Every read path is fail-soft, so a broken catalog looks to an agent exactly like an empty one. This is the only signal that the difference exists.
+
+```promql
+sum by (surface) (increase(posthog_data_catalog_read_failures_total[15m])) > 5
+```
+
+A rate threshold rather than `> 0`: one team with a poisoned metric definition increments on every read until someone fixes it, and a `> 0` page could never resolve. During triage, divide by `posthog_data_catalog_reads_total` for blast radius and read the `team_id` from the logs.
+
+**Metric runs are hitting system faults** (page). `internal_error` is the only outcome that means PostHog broke rather than a definition, a cost guardrail, or a user.
+
+```promql
+sum(increase(posthog_data_catalog_metric_runs_total{outcome="internal_error"}[15m])) > 0
+```
+
+**Governed metrics are rotting** (warning). Definitions that no longer run against the current schema.
+
+```promql
+(
+ sum(increase(posthog_data_catalog_metric_runs_total{outcome=~"definition_error|invalid_query|internal_error"}[30m]))
+ /
+ sum(increase(posthog_data_catalog_metric_runs_total{outcome!="async_enqueued"}[30m]))
+) > 0.2
+and
+sum(increase(posthog_data_catalog_metric_runs_total{outcome!="async_enqueued"}[30m])) > 20
+```
+
+The threshold and the minimum-volume guard are starting numbers and want tuning against real traffic. `async_enqueued` leaves the denominator because an enqueue has no outcome yet. `query_performance`, `capacity`, and `cancelled` stay in the denominator and out of the numerator: those runs happened, and none of them says the definition is stale.
+
+**The join probe is broken** (page). No relationship can be accepted while it is.
+
+```promql
+sum(increase(posthog_data_catalog_relationship_probe_total{outcome="error"}[15m])) > 0
+```
+
+There is deliberately no alert on `concurrency_limited`. That condition already has one on `posthog_clickhouse_query_concurrency_limit_exceeded{product="data_catalog"}`, and a second series measuring the same thing would page twice for one incident.
+
+### What these metrics do not cover
+
+- **Async metric runs end at the enqueue.** `outcome="async_enqueued"` records that a query status was handed back to poll. Whether that run later succeeded lands in the generic worker-side query series, not here.
+- **Governance actions** (create, approve, certify, accept, reject) are covered by the capture events in `backend/logic/analytics.py`. Their failures are user-caused 4xx, and django_prometheus middleware already covers 5xx.
+- **Backlog size** (pending proposals, drifted approved metrics) needs a periodic sweep, and the product has no background job. Adding it means a `PushGatewayTask` Celery beat entry.
+
+### Follow-ups
+
+- A p95 duration alert on `posthog_data_catalog_metric_run_duration_seconds`. Deferred because the product is flag-gated and low-volume, so the alert would flap. The expression is `histogram_quantile(0.95, sum by (le, kind) (rate(posthog_data_catalog_metric_run_duration_seconds_bucket[30m])))`, validatable today against the pre-created series.
+- OTLP twins through `OtelInstrumentFactory`, so the same series also land in the PostHog Metrics product.
+- A counter on the scout harness's fail-silent catalog context injection (`products/signals/backend/scout_harness/runner.py`), exported through the data catalog facade.
+- The backlog gauges described above.
+
## Known limits
- The evaluation scheduler triggers only on `$ai_generation`, so sessions with no `execute-sql` call are never evaluated; they remain visible in the dashboard tiles via `$mcp_tool_call`.