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): sync metrics to the lineage graph (#101594)

Thiago Salvatore3957c1ac17e7
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 9e79f9194712..608628734e79 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -25,6 +25,7 @@
'posthog.tasks.comment_slack_sync.backfill_comment_slack_thread',
'posthog.tasks.comment_slack_sync.ingest_slack_discussion_reply',
'posthog.tasks.comment_slack_sync.mirror_comment_reply_to_slack',
+ 'posthog.tasks.data_catalog.sync_metric_lineage',
'posthog.tasks.delete_persons.delete_persons_async',
'posthog.tasks.demo_create_data.create_data_for_demo_team',
'posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature',
diff --git a/products/data_catalog/backend/logic/lineage.py b/products/data_catalog/backend/logic/lineage.py
new file mode 100644
index 000000000000..8d77f46027f3
--- /dev/null
+++ b/products/data_catalog/backend/logic/lineage.py
@@ -0,0 +1,116 @@
+"""Keeps a metric's node in the data modeling lineage graph in step with the metric itself."""
+
+from enum import StrEnum
+
+from django.db import transaction
+
+import structlog
+
+from posthog.hogql.database.database import Database
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.scoping import team_scope
+
+from products.data_modeling.backend.facade.api import delete_metric_node, mark_metric_node_degraded, sync_metric_to_dag
+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLES
+
+from ..facade.enums import HOGQL_DEFINITION_KIND, MARKDOWN_DEFINITION_KIND
+from ..models.metric import Metric
+from .validation import definition_nodes, table_names_as_written
+
+logger = structlog.get_logger(__name__)
+
+SYSTEM_TABLE_PREFIX = "system."
+
+# An events node names an event, and an actions node names a stored filter over events. Both read
+# the events table and nothing else a reader could open, so `events` is the whole upstream they add.
+EVENT_SOURCE_KINDS = frozenset({"EventsNode", "ActionsNode"})
+EVENTS_TABLE_NAME = "events"
+
+
+class LineageSyncOutcome(StrEnum):
+ SYNCED = "synced"
+ # The node is written and its other edges are in place, but a dependency name matched no node,
+ # so the metric is missing that edge and carries the unresolved marker. A later write to the
+ # metric, or the backfill, links it once the missing node exists.
+ UNRESOLVED = "unresolved"
+ REMOVED = "removed"
+ DEGRADED = "degraded"
+
+
+def has_executable_definition(metric: Metric) -> bool:
+ return metric.definition is not None and metric.definition_kind != MARKDOWN_DEFINITION_KIND
+
+
+def _referenced_names(metric: Metric) -> list[str]:
+ """What the metric reads, by the names its own definition uses.
+
+ ``referenced_table_names`` is collected after the query is resolved, and resolution replaces a
+ non-materialized view with its body, so the view's name is not in there. Every other definition
+ kind records direct references already, so it keeps using the field.
+ """
+ if metric.definition_kind == HOGQL_DEFINITION_KIND and metric.definition:
+ return table_names_as_written(metric.definition)
+ return metric.referenced_table_names or []
+
+
+def dependency_names(metric: Metric) -> list[str]:
+ """The tables and views a metric reads, as lineage dependency names.
+
+ Catalog metadata tables under `system.` are dropped: they describe the catalog rather than
+ feeding the metric, and they have no node.
+ """
+ names = {name for name in _referenced_names(metric) if not name.startswith(SYSTEM_TABLE_PREFIX)}
+ if next(definition_nodes(metric.definition, EVENT_SOURCE_KINDS), None) is not None:
+ names.add(EVENTS_TABLE_NAME)
+ return sorted(names)
+
+
+def sync_metric_lineage(metric: Metric, database: Database | None = None) -> LineageSyncOutcome:
+ """Bring the metric's lineage node in line with the metric, best effort.
+
+ `metric` may be minutes old: the caller reads it, then the schema build below takes far longer
+ than the write that scheduled this. The row is read again under a lock once the schema is ready,
+ so a metric deleted or rewritten in the meantime decides the outcome rather than the stale copy.
+
+ A lineage failure must never fail the write that triggered it, so everything here is caught and
+ left on the node as a marker the graph can show. The outcome is returned rather than raised, so
+ a caller running this over many metrics can report how many actually landed.
+ """
+ try:
+ if metric.deleted or not has_executable_definition(metric):
+ delete_metric_node(metric.team, metric.id)
+ return LineageSyncOutcome.REMOVED
+ if database is None:
+ database = Database.create_for(
+ team=metric.team,
+ bypass_warehouse_access_control=True,
+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,
+ )
+ with team_scope(metric.team_id), transaction.atomic():
+ current = Metric.objects.for_team(metric.team_id).select_for_update().filter(pk=metric.pk).first()
+ if current is None or current.deleted or not has_executable_definition(current):
+ delete_metric_node(metric.team, metric.id)
+ return LineageSyncOutcome.REMOVED
+ unresolved = sync_metric_to_dag(
+ metric.team, current.id, current.name, dependency_names(current), database=database
+ )
+ return LineageSyncOutcome.UNRESOLVED if unresolved else LineageSyncOutcome.SYNCED
+ except Exception as error:
+ capture_exception(error)
+ logger.exception("Failed to sync metric lineage", metric_id=str(metric.id), team_id=metric.team_id)
+ try:
+ mark_metric_node_degraded(metric.team, metric.id, metric.name, str(error))
+ except Exception as marker_error:
+ capture_exception(marker_error)
+ return LineageSyncOutcome.DEGRADED
+
+
+def remove_metric_lineage(metric: Metric) -> None:
+ """Drop the metric's lineage node. The metric row is already gone, so a failure here only
+ strands a node the next backfill removes, and must not turn a successful delete into an error."""
+ try:
+ delete_metric_node(metric.team, metric.id)
+ except Exception as error:
+ capture_exception(error)
+ logger.exception("Failed to remove metric lineage", metric_id=str(metric.id), team_id=metric.team_id)
diff --git a/products/data_catalog/backend/logic/metrics.py b/products/data_catalog/backend/logic/metrics.py
index 26764a98e82b..7eeea54475b1 100644
--- a/products/data_catalog/backend/logic/metrics.py
+++ b/products/data_catalog/backend/logic/metrics.py
@@ -31,6 +31,7 @@ from products.product_analytics.backend.facade.models import Insight
from ..facade.enums import CreatedSource, MetricStatus
from ..models import METRIC_NAME_REGEX, Metric
+from ..tasks.tasks import sync_metric_lineage_task
from .analytics import (
METRIC_APPROVAL_BLOCKED_EVENT,
METRIC_APPROVED_EVENT,
@@ -41,6 +42,7 @@ from .analytics import (
)
from .drift import canonical_query_hash, compute_drift, fetch_insight
from .exceptions import MetricDrifted, SourceInsightUnavailable
+from .lineage import remove_metric_lineage
from .validation import validate_description, validate_metric_definition
if TYPE_CHECKING:
@@ -59,6 +61,7 @@ _UNSET = _Unset()
# The columns _reset_to_proposed touches, so a lifecycle reset can be scoped into update_fields.
_APPROVAL_FIELDS = frozenset({"status", "approved_by", "approved_at"})
+_LINEAGE_FIELDS = frozenset({"definition", "referenced_table_names"})
# Fields that carry the metric's reviewed meaning: editing any of them invalidates a prior approval.
# The definition is compared by canonical hash separately; these are compared by value. display_name
@@ -200,6 +203,19 @@ def _refine(metric: Metric, fields: dict) -> None:
metric.save()
+def _schedule_lineage_sync(metric: Metric) -> None:
+ """Refresh the metric's lineage node after the write it belongs to commits.
+
+ Dispatched rather than run inline: resolving dependency names builds the team's HogQL schema,
+ which is far more work than the write itself and must not sit in the caller's request.
+
+ `robust=True` so a broker that refuses the message does not turn a committed metric write into
+ an error for the person who made it. The backfill is the repair for a message that never went.
+ """
+ metric_id, team_id = str(metric.id), metric.team_id
+ transaction.on_commit(lambda: sync_metric_lineage_task.delay(metric_id, team_id), robust=True)
+
+
def upsert_metric(
*,
team: Team,
@@ -246,6 +262,7 @@ def upsert_metric(
fields[key] = value
fields.update(_resolve_definition_fields(definition, source_insight_short_id, team, user))
+ written_fields = set(fields)
# team_scope so the ModelActivityMixin's before-update lookup (via the fail-closed manager)
# works regardless of caller context (viewset, Celery, MCP, tests).
@@ -274,6 +291,8 @@ def upsert_metric(
_refine(existing, fields)
metric, created = existing, False
+ if created or written_fields & _LINEAGE_FIELDS:
+ _schedule_lineage_sync(metric)
capture_metric_event(
METRIC_CREATED_EVENT if created else METRIC_UPDATED_EVENT, metric, team=team, user=user, request=request
)
@@ -324,6 +343,8 @@ def update_metric(
if renamed_from is None:
raise
raise ValidationError({"name": "A metric with this name already exists."})
+ if renamed_from is not None or changed_fields & _LINEAGE_FIELDS:
+ _schedule_lineage_sync(metric)
capture_metric_event(
METRIC_UPDATED_EVENT,
metric,
@@ -391,6 +412,7 @@ def refresh_metric_from_insight(metric: Metric, user: Optional[User], request: "
changed_fields |= _APPROVAL_FIELDS
metric.save(update_fields=[*changed_fields, "updated_at"])
+ _schedule_lineage_sync(metric)
capture_metric_event(METRIC_UPDATED_EVENT, metric, team=metric.team, user=user, request=request)
return metric
@@ -404,6 +426,7 @@ def _apply_soft_delete(metric: Metric) -> None:
def soft_delete_metric(metric: Metric, user: Optional[User] = None, request: "Request | None" = None) -> None:
with team_scope(metric.team_id):
_apply_soft_delete(metric)
+ remove_metric_lineage(metric)
capture_metric_event(METRIC_DELETED_EVENT, metric, team=metric.team, user=user, request=request)
@@ -514,6 +537,9 @@ def bulk_soft_delete_metrics(
deleted.append(metric)
_capture_after_commit(METRIC_DELETED_EVENT, deleted, team=team, user=user, request=request)
+ for metric in deleted:
+ remove_metric_lineage(metric)
+
return deleted, skipped
diff --git a/products/data_catalog/backend/logic/validation.py b/products/data_catalog/backend/logic/validation.py
index a9ad44771c4a..956c959d893f 100644
--- a/products/data_catalog/backend/logic/validation.py
+++ b/products/data_catalog/backend/logic/validation.py
@@ -5,6 +5,7 @@ upgrade-canonical definition (so schema migrations never read as drift later) pl
directly references (cached on the row for the catalog's denied-table filter).
"""
+from collections.abc import Iterator
from typing import NoReturn, Optional
from pydantic import BaseModel
@@ -55,10 +56,15 @@ class _TableReferenceCollector(TraversingVisitor):
does not see its own name), silently defeating the catalog's denied-table filter. So CTE
names are tracked per scope: each CTE body is visited under the scope of the CTEs defined
before it, and only single-part FROM/JOIN targets naming an in-scope CTE are skipped.
+
+ ``skip_table_functions`` drops a table-function call such as ``numbers(10)``. Lineage wants the
+ data assets a metric reads, and a generator is not one; the denied-table filter keeps them,
+ because it must see every name the query reads.
"""
- def __init__(self) -> None:
+ def __init__(self, *, skip_table_functions: bool = False) -> None:
self.tables: set[str] = set()
+ self._skip_table_functions = skip_table_functions
self._cte_scopes: list[set[str]] = [set()]
def visit_select_query(self, node: ast.SelectQuery) -> None:
@@ -79,7 +85,8 @@ class _TableReferenceCollector(TraversingVisitor):
self._cte_scopes.pop()
def visit_join_expr(self, node: ast.JoinExpr) -> None:
- if isinstance(node.table, ast.Field):
+ is_table_function = node.table_args is not None
+ if isinstance(node.table, ast.Field) and not (is_table_function and self._skip_table_functions):
chain = [str(part) for part in node.table.chain]
if len(chain) != 1 or chain[0] not in self._cte_scopes[-1]:
self.tables.add(".".join(chain))
@@ -164,17 +171,8 @@ def _validate_markdown(definition: dict) -> tuple[dict, list[str]]:
return definition, []
-def _validate_hogql(definition: dict, team: Team, user: Optional[User]) -> tuple[dict, list[str]]:
- extra_keys = set(definition.keys()) - _HOGQL_ALLOWED_KEYS
- if extra_keys:
- _fail(
- f"HogQLQuery fields not allowed in a metric definition: {sorted(extra_keys)}.",
- "A metric definition may only set 'query' (and 'values'). Fields like connectionId or "
- "sendRawQuery are rejected.",
- )
-
- _ensure_valid_schema(definition, HogQLQuery)
-
+def _parse_hogql_definition(definition: dict) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Parse a HogQL definition's query text. Raises :class:`ValidationError` on unparseable SQL."""
# Both run paths substitute `values` as parse-time placeholders and set no globals, so this
# parses the same way: `HogQLQueryRunner._parse_query` for a metric run, and `bind_metric_query`
# for a data quality check on a metric. Resolving them as globals instead would accept a bare
@@ -186,7 +184,7 @@ def _validate_hogql(definition: dict, team: Team, user: Optional[User]) -> tuple
else None
)
try:
- ast_node = parse_select(definition["query"], placeholders=placeholders)
+ return parse_select(definition["query"], placeholders=placeholders)
except ExposedHogQLError as e:
_fail(f"Invalid HogQL query: {e}", "Fix the SQL syntax.")
except ResolutionError as e:
@@ -196,6 +194,34 @@ def _validate_hogql(definition: dict, team: Team, user: Optional[User]) -> tuple
capture_exception(e)
_fail("Could not parse the query.", "Check the SQL syntax.")
+
+def table_names_as_written(definition: dict) -> list[str]:
+ """The tables and views a HogQL definition names in its own query text.
+
+ Collected before resolution, which replaces a non-materialized view with its body: a metric that
+ reads a view depends on the view, not on the view's own sources. Table functions are dropped:
+ they generate rows rather than read them, so they are not upstream of the metric. Not a
+ substitute for ``referenced_table_names``, which the catalog's denied-table filter needs
+ resolved.
+ """
+ collector = _TableReferenceCollector(skip_table_functions=True)
+ collector.visit(_parse_hogql_definition(definition))
+ return sorted(collector.tables)
+
+
+def _validate_hogql(definition: dict, team: Team, user: Optional[User]) -> tuple[dict, list[str]]:
+ extra_keys = set(definition.keys()) - _HOGQL_ALLOWED_KEYS
+ if extra_keys:
+ _fail(
+ f"HogQLQuery fields not allowed in a metric definition: {sorted(extra_keys)}.",
+ "A metric definition may only set 'query' (and 'values'). Fields like connectionId or "
+ "sendRawQuery are rejected.",
+ )
+
+ _ensure_valid_schema(definition, HogQLQuery)
+
+ ast_node = _parse_hogql_definition(definition)
+
context = HogQLContext(team_id=team.pk, user=user, enable_select_queries=True)
try:
prepare_ast_for_printing(node=ast_node, context=context, dialect="clickhouse")
@@ -222,19 +248,24 @@ def _ensure_valid_schema(definition: dict, model_class: type[BaseModel]) -> None
_fail(f"Definition does not match {model_class.__name__}: {e}", "Fix the query shape.")
+def definition_nodes(definition: object, kinds: frozenset[str]) -> Iterator[dict]:
+ """Every nested query node of one of `kinds`, anywhere in a definition."""
+ if isinstance(definition, dict):
+ if definition.get("kind") in kinds:
+ yield definition
+ for child in definition.values():
+ yield from definition_nodes(child, kinds)
+ elif isinstance(definition, list):
+ for child in definition:
+ yield from definition_nodes(child, kinds)
+
+
def _extract_warehouse_tables(definition: dict) -> list[str]:
"""Walk a node/insight query dict for DataWarehouseNode table references (direct references only)."""
- tables: set[str] = set()
-
- def walk(value: object) -> None:
- if isinstance(value, dict):
- if value.get("kind") == "DataWarehouseNode" and value.get("table_name"):
- tables.add(str(value["table_name"]))
- for child in value.values():
- walk(child)
- elif isinstance(value, list):
- for child in value:
- walk(child)
-
- walk(definition)
- return sorted(tables)
+ return sorted(
+ {
+ str(node["table_name"])
+ for node in definition_nodes(definition, frozenset({"DataWarehouseNode"}))
+ if node.get("table_name")
+ }
+ )
diff --git a/products/data_catalog/backend/management/__init__.py b/products/data_catalog/backend/management/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/data_catalog/backend/management/commands/__init__.py b/products/data_catalog/backend/management/commands/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/data_catalog/backend/management/commands/backfill_metric_lineage.py b/products/data_catalog/backend/management/commands/backfill_metric_lineage.py
new file mode 100644
index 000000000000..ce5e1ce8a689
--- /dev/null
+++ b/products/data_catalog/backend/management/commands/backfill_metric_lineage.py
@@ -0,0 +1,139 @@
+from dataclasses import dataclass
+
+from django.core.management.base import BaseCommand, CommandParser
+from django.db.models import F, Q
+
+import structlog
+
+from posthog.hogql.database.database import Database
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.data_modeling.backend.facade.models import Node, NodeType
+from products.data_modeling.backend.facade.system_tables import DATA_MODELING_ALLOWED_SYSTEM_TABLES
+
+from ...logic.lineage import LineageSyncOutcome, sync_metric_lineage
+from ...models.metric import Metric
+
+logger = structlog.get_logger(__name__)
+
+METRIC_CHUNK_SIZE = 200
+
+
+@dataclass(frozen=False)
+class TeamResult:
+ seen: int = 0
+ synced: int = 0
+ unresolved: int = 0
+ removed: int = 0
+ degraded: int = 0
+ stranded: int = 0
+
+ def add(self, other: "TeamResult") -> None:
+ self.seen += other.seen
+ self.synced += other.synced
+ self.unresolved += other.unresolved
+ self.removed += other.removed
+ self.degraded += other.degraded
+ self.stranded += other.stranded
+
+ def __str__(self) -> str:
+ return (
+ f"{self.seen} seen, {self.synced} synced, {self.unresolved} unresolved, "
+ f"{self.removed} removed, {self.degraded} degraded, {self.stranded} stranded node(s) dropped"
+ )
+
+
+class Command(BaseCommand):
+ help = "Create lineage nodes for metrics written before the catalog started syncing them"
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, default=None, help="Only backfill this team")
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ default=False,
+ help="Only report how many metrics would be synced, without writing any node",
+ )
+
+ def handle(self, *args, **options) -> None:
+ team_id = options["team_id"]
+ dry_run = options["dry_run"]
+ total = TeamResult()
+ failed = 0
+ for team in self._teams(team_id):
+ try:
+ result = self._backfill_team(team, dry_run)
+ except Exception as error:
+ # The team's schema is built once for the whole team, outside the per-metric error
+ # boundary in `sync_metric_lineage`, so a team whose warehouse it cannot read would
+ # otherwise end the run and leave every later team without nodes.
+ failed += 1
+ logger.exception("Failed to backfill metric lineage for team", team_id=team.pk)
+ self.stdout.write(f"team {team.pk}: failed ({error})")
+ continue
+ total.add(result)
+ if result.seen or result.stranded:
+ logger.info("Backfilled metric lineage for team", team_id=team.pk, result=str(result), dry_run=dry_run)
+ self.stdout.write(f"team {team.pk}: {result}")
+ summary = f"{'would sync' if dry_run else 'done'}: {total}"
+ if failed:
+ summary = f"{summary}, {failed} team(s) failed"
+ self.stdout.write(summary)
+
+ def _teams(self, team_id: int | None):
+ """Project root teams only.
+
+ A metric canonicalizes to the project root, and its node is written there, so iterating a
+ child environment would sync the same metrics again against the child's schema.
+ """
+ roots = Team.objects.filter(Q(parent_team_id__isnull=True) | Q(parent_team_id=F("id")))
+ if team_id is not None:
+ roots = roots.filter(pk=self._root_team_id(team_id))
+ return roots.order_by("pk").iterator()
+
+ def _root_team_id(self, team_id: int) -> int:
+ """The project root of a team id, so `--team-id` given a child environment backfills its project."""
+ parent_id = Team.objects.filter(pk=team_id).values_list("parent_team_id", flat=True).first()
+ return parent_id or team_id
+
+ def _backfill_team(self, team: Team, dry_run: bool) -> TeamResult:
+ result = TeamResult()
+ with team_scope(team.pk):
+ metrics = Metric.objects.for_team(team.pk).filter(deleted=False)
+ if dry_run:
+ result.seen = metrics.count()
+ result.stranded = self._stranded_nodes(team).count()
+ return result
+ if metrics.exists():
+ # One schema for the whole team: building it per metric is the expensive part.
+ database = Database.create_for(
+ team=team,
+ bypass_warehouse_access_control=True,
+ allowed_system_tables=DATA_MODELING_ALLOWED_SYSTEM_TABLES,
+ )
+ for metric in metrics.select_related("team").iterator(chunk_size=METRIC_CHUNK_SIZE):
+ result.seen += 1
+ outcome = sync_metric_lineage(metric, database=database)
+ if outcome == LineageSyncOutcome.SYNCED:
+ result.synced += 1
+ elif outcome == LineageSyncOutcome.UNRESOLVED:
+ result.unresolved += 1
+ elif outcome == LineageSyncOutcome.REMOVED:
+ result.removed += 1
+ else:
+ result.degraded += 1
+ stranded_nodes = self._stranded_nodes(team)
+ result.stranded = stranded_nodes.count()
+ stranded_nodes.delete()
+ return result
+
+ def _stranded_nodes(self, team: Team):
+ """Metric nodes whose metric is deleted or gone.
+
+ A metric delete removes its node best effort, so a failure there leaves the node in the
+ graph with nothing to take it out again. This is that repair.
+ """
+ live_metric_ids = Metric.objects.for_team(team.pk).filter(deleted=False).values("id")
+ return Node.objects.filter(team=team, type=NodeType.METRIC).exclude(metric_id__in=live_metric_ids)
diff --git a/products/data_catalog/backend/tasks/__init__.py b/products/data_catalog/backend/tasks/__init__.py
index e69de29bb2d1..11ca12b5ab6c 100644
--- a/products/data_catalog/backend/tasks/__init__.py
+++ b/products/data_catalog/backend/tasks/__init__.py
@@ -0,0 +1,9 @@
+"""Celery tasks for data_catalog.
+
+Celery's autodiscovery imports this package, not the modules under it, so a task module that
+nothing else imports never registers in a worker and its messages are discarded as unknown.
+"""
+
+from . import tasks
+
+__all__ = ["tasks"]
diff --git a/products/data_catalog/backend/tasks/tasks.py b/products/data_catalog/backend/tasks/tasks.py
index f395f84f8179..53dd067e58fb 100644
--- a/products/data_catalog/backend/tasks/tasks.py
+++ b/products/data_catalog/backend/tasks/tasks.py
@@ -1,8 +1,27 @@
"""
Celery tasks for data_catalog.
-Async entrypoints that call the facade (facade/api.py).
-Keep task functions thin - only call facade methods.
+Async entrypoints that call the logic layer.
+Keep task functions thin - only call logic functions.
"""
-# from celery import shared_task
-# from ..facade import api
+
+from celery import shared_task
+
+from posthog.celery_queues import CeleryQueue
+from posthog.models.scoping import team_scope
+
+from ..logic.lineage import sync_metric_lineage
+from ..models.metric import Metric
+
+
+@shared_task(
+ name="posthog.tasks.data_catalog.sync_metric_lineage",
+ ignore_result=True,
+ queue=CeleryQueue.DEFAULT.value,
+)
+def sync_metric_lineage_task(metric_id: str, team_id: int) -> None:
+ with team_scope(team_id):
+ metric = Metric.objects.for_team(team_id).filter(pk=metric_id).select_related("team").first()
+ if metric is None:
+ return
+ sync_metric_lineage(metric)
diff --git a/products/data_catalog/backend/tests/test_lineage.py b/products/data_catalog/backend/tests/test_lineage.py
new file mode 100644
index 000000000000..7442520476ec
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_lineage.py
@@ -0,0 +1,344 @@
+import importlib
+from io import StringIO
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.hogql.database.database import Database
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.data_catalog.backend.logic.lineage import (
+ LineageSyncOutcome,
+ dependency_names,
+ has_executable_definition,
+ sync_metric_lineage,
+)
+from products.data_catalog.backend.logic.metrics import (
+ bulk_soft_delete_metrics,
+ soft_delete_metric,
+ update_metric,
+ upsert_metric,
+)
+from products.data_catalog.backend.models import Metric
+from products.data_catalog.backend.tasks.tasks import sync_metric_lineage_task
+from products.data_modeling.backend.facade.api import mark_metric_node_degraded
+from products.data_modeling.backend.facade.models import DAG, Edge, Node, NodeType
+
+_HOGQL_EVENTS = {"kind": "HogQLQuery", "query": "select count() from events"}
+_HOGQL_PERSONS = {"kind": "HogQLQuery", "query": "select count() from persons"}
+_HOGQL_SYSTEM = {"kind": "HogQLQuery", "query": "select count() from system.information_schema.metrics"}
+_HOGQL_VIEW = {"kind": "HogQLQuery", "query": "select count() from accounts_view"}
+_HOGQL_CTE_SHADOWING_A_TABLE = {
+ "kind": "HogQLQuery",
+ "query": "with events as (select * from persons) select count() from events",
+}
+_HOGQL_NUMBERS_SPINE = {
+ "kind": "HogQLQuery",
+ "query": "select count() from numbers(10) join events on 1",
+}
+_MARKDOWN = {"kind": "MarkdownDefinition", "markdown": "Count the accounts, then divide."}
+_TRENDS_EVENTS = {
+ "kind": "TrendsQuery",
+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],
+}
+
+
+class TestDependencyNames(BaseTest):
+ def _metric(self, definition: dict | None, referenced: list[str] | None = None) -> Metric:
+ metric = Metric(team=self.team, name="m", description="d", definition=definition)
+ metric.referenced_table_names = referenced or []
+ return metric
+
+ @parameterized.expand(
+ [
+ ("hogql_tables", _HOGQL_EVENTS, ["events"], ["events"]),
+ ("system_tables_dropped", _HOGQL_SYSTEM, ["system.information_schema.metrics"], []),
+ ("hogql_view_beats_its_resolved_sources", _HOGQL_VIEW, ["events", "persons"], ["accounts_view"]),
+ ("hogql_cte_does_not_shadow_a_table", _HOGQL_CTE_SHADOWING_A_TABLE, ["persons"], ["persons"]),
+ ("hogql_table_function_is_not_upstream", _HOGQL_NUMBERS_SPINE, ["events"], ["events"]),
+ ("events_node_adds_events", _TRENDS_EVENTS, [], ["events"]),
+ ("warehouse_series_keeps_both", _TRENDS_EVENTS, ["stripe_charges"], ["events", "stripe_charges"]),
+ ("markdown_reads_nothing", _MARKDOWN, [], []),
+ ]
+ )
+ def test_dependency_names(self, _name, definition, referenced, expected) -> None:
+ assert dependency_names(self._metric(definition, referenced)) == expected
+
+ @parameterized.expand(
+ [
+ ("hogql", _HOGQL_EVENTS, True),
+ ("markdown", _MARKDOWN, False),
+ ("no_definition", None, False),
+ ]
+ )
+ def test_has_executable_definition(self, _name, definition, expected) -> None:
+ assert has_executable_definition(self._metric(definition)) is expected
+
+
+class TestSyncMetricLineage(BaseTest):
+ def _upsert(self, name: str, **kwargs) -> Metric:
+ return upsert_metric(team=self.team, user=self.user, name=name, description="d", **kwargs)
+
+ def _node(self, metric: Metric) -> Node | None:
+ return Node.objects.filter(team=self.team, metric_id=metric.id).first()
+
+ def _sources(self, metric: Metric) -> set[str]:
+ node = self._node(metric)
+ assert node is not None
+ return {edge.source.name for edge in Edge.objects.filter(target=node).select_related("source")}
+
+ def _sync(self, metric: Metric) -> None:
+ with team_scope(self.team.id):
+ sync_metric_lineage(Metric.objects.for_team(self.team.id).select_related("team").get(pk=metric.pk))
+
+ def test_a_metric_with_a_query_gets_a_node_and_its_edges(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+
+ self._sync(metric)
+
+ node = self._node(metric)
+ assert node is not None
+ assert node.type == NodeType.METRIC
+ assert node.name == "mrr"
+ assert self._sources(metric) == {"events"}
+
+ def test_a_rename_follows_and_a_new_definition_replaces_the_edges(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._sync(metric)
+
+ renamed = update_metric(metric, team=self.team, user=self.user, name="revenue", definition=_HOGQL_PERSONS)
+ self._sync(renamed)
+
+ node = self._node(renamed)
+ assert node is not None
+ assert node.name == "revenue"
+ assert self._sources(renamed) == {"persons"}
+
+ @parameterized.expand([("markdown", _MARKDOWN), ("cleared", None)])
+ def test_a_metric_that_stops_being_executable_loses_its_node(self, _name, definition) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._sync(metric)
+
+ metric.definition = definition
+ metric.save(update_fields=["definition"])
+ self._sync(metric)
+
+ assert self._node(metric) is None
+
+ def test_a_failing_sync_leaves_a_marker_instead_of_raising(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+
+ with patch(
+ "products.data_catalog.backend.logic.lineage.sync_metric_to_dag",
+ side_effect=RuntimeError("schema build blew up"),
+ ):
+ self._sync(metric)
+
+ node = self._node(metric)
+ assert node is not None
+ assert node.properties["system"]["degraded_sync"]["error"] == "schema build blew up"
+
+ def test_soft_delete_removes_the_node(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._sync(metric)
+
+ soft_delete_metric(metric, self.user)
+
+ assert self._node(metric) is None
+
+ def test_a_failing_node_delete_does_not_fail_the_metric_delete(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._sync(metric)
+
+ with patch(
+ "products.data_catalog.backend.logic.lineage.delete_metric_node",
+ side_effect=RuntimeError("postgres went away"),
+ ):
+ soft_delete_metric(metric, self.user)
+
+ metric.refresh_from_db()
+ assert metric.deleted is True
+
+ def test_bulk_delete_removes_every_node(self) -> None:
+ first = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ second = self._upsert("arr", definition=_HOGQL_EVENTS)
+ self._sync(first)
+ self._sync(second)
+
+ bulk_soft_delete_metrics([first, second], self.user)
+
+ assert not Node.objects.filter(team=self.team, type=NodeType.METRIC).exists()
+
+ def test_a_sync_that_lands_after_a_delete_leaves_no_node(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._sync(metric)
+ assert self._node(metric) is not None
+ with team_scope(self.team.id):
+ in_flight = Metric.objects.for_team(self.team.id).select_related("team").get(pk=metric.pk)
+
+ soft_delete_metric(metric, self.user)
+ outcome = sync_metric_lineage(in_flight)
+
+ assert outcome == LineageSyncOutcome.REMOVED
+ assert self._node(metric) is None
+
+ def test_a_write_dispatches_the_sync_only_when_it_can_change_the_lineage(self) -> None:
+ with patch("products.data_catalog.backend.logic.metrics.sync_metric_lineage_task") as task:
+ with self.captureOnCommitCallbacks(execute=True):
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+
+ task.delay.assert_called_once_with(str(metric.id), self.team.id)
+ task.delay.reset_mock()
+
+ with self.captureOnCommitCallbacks(execute=True):
+ upsert_metric(team=self.team, user=self.user, name="mrr", description="what it counts")
+
+ task.delay.assert_not_called()
+
+ def test_metric_nodes_live_in_the_teams_default_dag(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+
+ self._sync(metric)
+
+ node = self._node(metric)
+ assert node is not None
+ assert node.dag_id == DAG.get_or_create_default(self.team).id
+
+
+class TestBackfillMetricLineage(BaseTest):
+ def _upsert(self, name: str, **kwargs) -> Metric:
+ return upsert_metric(team=self.team, user=self.user, name=name, description="d", **kwargs)
+
+ def test_backfill_creates_nodes_and_builds_one_schema_per_team(self) -> None:
+ self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._upsert("arr", definition=_HOGQL_EVENTS)
+ deleted = self._upsert("gone", definition=_HOGQL_EVENTS)
+ soft_delete_metric(deleted, self.user)
+
+ with patch(
+ "products.data_catalog.backend.management.commands.backfill_metric_lineage.Database"
+ ) as database_class:
+ database_class.create_for.return_value = Database.create_for(
+ team=self.team, bypass_warehouse_access_control=True
+ )
+ call_command("backfill_metric_lineage", "--team-id", str(self.team.pk))
+
+ assert database_class.create_for.call_count == 1
+ assert Node.objects.filter(team=self.team, type=NodeType.METRIC).count() == 2
+
+ def test_dry_run_writes_nothing(self) -> None:
+ self._upsert("mrr", definition=_HOGQL_EVENTS)
+
+ call_command("backfill_metric_lineage", "--team-id", str(self.team.pk), "--dry-run")
+
+ assert not Node.objects.filter(team=self.team, type=NodeType.METRIC).exists()
+
+ def test_backfill_drops_a_node_whose_metric_is_gone(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ with team_scope(self.team.id):
+ sync_metric_lineage(Metric.objects.for_team(self.team.id).select_related("team").get(pk=metric.pk))
+ # A delete whose node removal failed leaves exactly this: a node with no live metric.
+ Metric.objects.for_team(self.team.id).filter(pk=metric.pk).update(deleted=True)
+
+ call_command("backfill_metric_lineage", "--team-id", str(self.team.pk))
+
+ assert not Node.objects.filter(team=self.team, type=NodeType.METRIC).exists()
+
+ @parameterized.expand(
+ [
+ ("a_failed_sync", {"side_effect": RuntimeError("schema build blew up")}, "1 degraded"),
+ ("a_missing_dependency_node", {"return_value": ["accounts_view"]}, "1 unresolved"),
+ ]
+ )
+ def test_backfill_reports_what_the_sync_reported_not_a_success(self, _name, patched, expected) -> None:
+ self._upsert("mrr", definition=_HOGQL_EVENTS)
+ output = StringIO()
+
+ with patch("products.data_catalog.backend.logic.lineage.sync_metric_to_dag", **patched):
+ call_command("backfill_metric_lineage", "--team-id", str(self.team.pk), stdout=output)
+
+ assert expected in output.getvalue()
+ assert "0 synced" in output.getvalue()
+
+ def _child_environment(self) -> Team:
+ return Team.objects.create(
+ organization=self.organization, project=self.team.project, parent_team=self.team, name="staging"
+ )
+
+ def _patched_database(self):
+ patcher = patch("products.data_catalog.backend.management.commands.backfill_metric_lineage.Database")
+ database_class = patcher.start()
+ self.addCleanup(patcher.stop)
+ database_class.create_for.return_value = Database.create_for(
+ team=self.team, bypass_warehouse_access_control=True
+ )
+ return database_class
+
+ def test_a_team_whose_schema_fails_does_not_end_the_run(self) -> None:
+ self._upsert("mrr", definition=_HOGQL_EVENTS)
+ later_team = Team.objects.create(organization=self.organization, name="second project")
+ later_metric = upsert_metric(
+ team=later_team, user=self.user, name="arr", description="d", definition=_HOGQL_EVENTS
+ )
+ output = StringIO()
+ database_class = self._patched_database()
+ schema = database_class.create_for.return_value
+
+ def build_schema(**kwargs) -> Database:
+ if kwargs["team"].pk == self.team.pk:
+ raise RuntimeError("schema build blew up")
+ return schema
+
+ database_class.create_for.side_effect = build_schema
+
+ call_command("backfill_metric_lineage", stdout=output)
+
+ assert "1 team(s) failed" in output.getvalue()
+ assert Node.objects.filter(team=later_team, metric_id=later_metric.id).exists()
+
+ def test_a_child_environment_does_not_repeat_its_projects_backfill(self) -> None:
+ self._upsert("mrr", definition=_HOGQL_EVENTS)
+ self._child_environment()
+ database_class = self._patched_database()
+
+ call_command("backfill_metric_lineage")
+
+ assert database_class.create_for.call_count == 1
+ assert Node.objects.filter(type=NodeType.METRIC).count() == 1
+
+ def test_a_child_environment_id_backfills_its_project(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ child = self._child_environment()
+ database_class = self._patched_database()
+
+ call_command("backfill_metric_lineage", "--team-id", str(child.pk))
+
+ assert database_class.create_for.call_args.kwargs["team"] == self.team
+ assert Node.objects.filter(team=self.team, metric_id=metric.id).exists()
+
+ def test_backfill_repairs_a_degraded_node(self) -> None:
+ metric = self._upsert("mrr", definition=_HOGQL_EVENTS)
+ with team_scope(self.team.id):
+ mark_metric_node_degraded(self.team, metric.id, metric.name, "schema build blew up")
+
+ call_command("backfill_metric_lineage", "--team-id", str(self.team.pk))
+
+ node = Node.objects.get(team=self.team, metric_id=metric.id)
+ assert "system" not in node.properties
+
+
+class TestLineageTaskRegistration(SimpleTestCase):
+ def test_the_sync_task_is_registered_from_the_tasks_package(self) -> None:
+ # Celery autodiscovery imports the package, not the modules under it. Without the re-export
+ # in tasks/__init__.py a worker never registers this task and discards every message.
+ package = importlib.import_module("products.data_catalog.backend.tasks")
+
+ assert getattr(package, "tasks", None) is not None
+ assert sync_metric_lineage_task.name == "posthog.tasks.data_catalog.sync_metric_lineage"
diff --git a/products/data_catalog/backend/tests/test_logic.py b/products/data_catalog/backend/tests/test_logic.py
index dba3dbc8a068..e4f30bcd1f72 100644
--- a/products/data_catalog/backend/tests/test_logic.py
+++ b/products/data_catalog/backend/tests/test_logic.py
@@ -171,6 +171,11 @@ class TestValidateMetricDefinition(BaseTest):
"with events as (select uuid from events) select uuid from events",
["events"],
),
+ (
+ "table_function_still_reaches_the_denied_table_filter",
+ "select count() from numbers(10) join events on 1",
+ ["events", "numbers"],
+ ),
(
"join_constraint_subquery",
"select count() from persons join groups on persons.id in (select person_id from events)",
diff --git a/products/data_modeling/backend/logic/metric_dag_sync.py b/products/data_modeling/backend/logic/metric_dag_sync.py
index 6d9755f5c273..3344400bebf7 100644
--- a/products/data_modeling/backend/logic/metric_dag_sync.py
+++ b/products/data_modeling/backend/logic/metric_dag_sync.py
@@ -25,12 +25,14 @@ def sync_metric_to_dag(
name: str,
dependency_names: Sequence[str],
database: Database | None = None,
-) -> None:
+) -> list[str]:
"""Create or update the node for a data catalog metric and rebuild its incoming edges.
A metric is a leaf: it reads tables and views and nothing reads it, so nothing schedulable
changes and no reconcile follows. A dependency name that resolves to no node is skipped and
recorded on the node, because one renamed table should not cost the metric every other edge.
+ Those names are returned as well, so a caller reporting many metrics can separate a metric that
+ synced with every edge from one that is missing some.
`database` lets a caller syncing many metrics for one team build the schema once.
"""
@@ -67,6 +69,8 @@ def sync_metric_to_dag(
node.mark_lineage_unresolved(unresolved)
node.save(update_fields=["name", "properties"])
+ return unresolved
+
def mark_metric_node_degraded(team: "Team", metric_id: UUID, name: str, error: str) -> None:
"""Record on the metric's node that its last lineage refresh failed, so the graph can say so."""
diff --git a/products/data_modeling/backend/test/test_metric_dag_sync.py b/products/data_modeling/backend/test/test_metric_dag_sync.py
index 46ba963a03c5..46b4d913a461 100644
--- a/products/data_modeling/backend/test/test_metric_dag_sync.py
+++ b/products/data_modeling/backend/test/test_metric_dag_sync.py
@@ -61,8 +61,11 @@ class TestSyncMetricToDag(BaseTest):
self.assertEqual(Node.objects.filter(team=self.team, type=NodeType.METRIC).count(), 1)
def test_an_unresolvable_name_is_skipped_and_recorded(self):
- sync_metric_to_dag(self.team, self.metric_id, "weekly_active_accounts", ["events", "table_that_went_away"])
+ unresolved = sync_metric_to_dag(
+ self.team, self.metric_id, "weekly_active_accounts", ["events", "table_that_went_away"]
+ )
+ self.assertEqual(unresolved, ["table_that_went_away"])
self.assertEqual(self._sources(), {"events"})
marker = self._node().properties["system"][UNRESOLVED_DEPENDENCIES_KEY]
self.assertEqual(marker["names"], ["table_that_went_away"])