:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): backfill semantic descriptions for existing views (#69007)
Thiago Salvatore44db0c002874
diff --git a/products/data_modeling/backend/logic/enrich_view_semantics.py b/products/data_modeling/backend/logic/enrich_view_semantics.pyindex 2055f0f8b186..6992d46ca27f 100644--- a/products/data_modeling/backend/logic/enrich_view_semantics.py+++ b/products/data_modeling/backend/logic/enrich_view_semantics.py@@ -458,32 +458,55 @@ def enrichment_gates_pass(saved_query: DataWarehouseSavedQuery) -> bool:)-def maybe_dispatch_enrichment(saved_query: DataWarehouseSavedQuery) -> None:- """Dispatch view enrichment for a just-saved view, if it plausibly needs it.+def view_ready_for_enrichment(saved_query: DataWarehouseSavedQuery) -> bool:+ """The content half of the dispatch decision: enrichable view whose descriptions could have changed.- Query-free gates plus a hash pre-check against the in-hand instance keep steady-state saves (status- flips, `last_run_at` updates) off Temporal entirely. The activity re-checks every gate, so this is a- cheap best-effort filter, not the source of truth.+ Not deleted/test/managed, has a query and columns, and its enrichment hash differs from the stored one.+ The team half (flag + AI consent) is `enrichment_gates_pass`. Split out so a backfill can check the+ team gate once per team and this once per view."""if saved_query.deleted or saved_query.is_test or saved_query.managed_viewset_id:- return+ return Falsequery = saved_query.query or {}if not (isinstance(query, dict) and query.get("query")):- return+ return Falseif not saved_query.columns:- return- if compute_enrichment_hash(saved_query) == saved_query.semantic_enrichment_hash:- return- if not enrichment_gates_pass(saved_query):- return-- # The serializer saves inside transaction.atomic(), so dispatch must wait for commit; on_commit runs- # immediately when no transaction is open.+ return False+ return compute_enrichment_hash(saved_query) != saved_query.semantic_enrichment_hash+++def enrichment_dispatch_pending(saved_query: DataWarehouseSavedQuery) -> bool:+ """Whether a saved view passes every query-free gate + hash pre-check and should enqueue enrichment.++ Shared by the save-signal dispatch path and the backfill command. The activity re-checks every gate,+ so this is a cheap best-effort filter, not the source of truth.+ """+ return view_ready_for_enrichment(saved_query) and enrichment_gates_pass(saved_query)+++def dispatch_view_enrichment(team_id: int, saved_query_id: str) -> None:+ """Enqueue the enrichment workflow once the current transaction commits (immediately when none is open).++ The serializer saves inside transaction.atomic(), so dispatch must wait for commit; management commands+ run outside a transaction, so on_commit fires the workflow start inline.+ """from functools import partial # noqa: PLC0415 — trivial, keep it next to the only usefrom django.db import transaction # noqa: PLC0415- transaction.on_commit(partial(_start_enrichment_workflow, saved_query.team_id, str(saved_query.id)))+ transaction.on_commit(partial(_start_enrichment_workflow, team_id, saved_query_id))+++def maybe_dispatch_enrichment(saved_query: DataWarehouseSavedQuery) -> bool:+ """Dispatch view enrichment for a just-saved view, if it plausibly needs it. Returns whether it did.++ Query-free gates plus a hash pre-check against the in-hand instance keep steady-state saves (status+ flips, `last_run_at` updates) off Temporal entirely.+ """+ if not enrichment_dispatch_pending(saved_query):+ return False+ dispatch_view_enrichment(saved_query.team_id, str(saved_query.id))+ return Truedef _start_enrichment_workflow(team_id: int, saved_query_id: str) -> None:diff --git a/products/data_modeling/backend/management/commands/backfill_view_semantic_enrichment.py b/products/data_modeling/backend/management/commands/backfill_view_semantic_enrichment.pynew file mode 100644index 000000000000..f4e07f93d28b--- /dev/null+++ b/products/data_modeling/backend/management/commands/backfill_view_semantic_enrichment.py@@ -0,0 +1,145 @@+import time+from collections import Counter+from typing import Any++from django.core.management.base import BaseCommand, CommandError++import structlog++from products.data_modeling.backend.logic.enrich_view_semantics import (+ dispatch_view_enrichment,+ enrichment_gates_pass,+ view_ready_for_enrichment,+)+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery++logger = structlog.get_logger(__name__)++DEFAULT_SLEEP_SECONDS = 0.2+++class Command(BaseCommand):+ help = (+ "Backfill AI semantic descriptions for existing data-modeling views by dispatching the same "+ "enrichment workflow the save signal uses. Views only re-enrich on save/materialization, so views "+ "that predate the feature never get descriptions. Dry-run by default; pass --live-run to dispatch."+ )++ def add_arguments(self, parser: Any) -> None:+ target = parser.add_mutually_exclusive_group(required=True)+ target.add_argument(+ "--team-ids",+ type=int,+ nargs="+",+ help="Only backfill views for these team IDs (space-separated).",+ )+ target.add_argument(+ "--all",+ action="store_true",+ help="Backfill views across every team. Use with --limit / --sleep to avoid overload.",+ )+ parser.add_argument(+ "--live-run",+ action="store_true",+ help="Actually dispatch enrichment workflows. Without it, the command only reports what it would do.",+ )+ parser.add_argument(+ "--limit",+ type=int,+ default=None,+ help="Stop after dispatching this many workflows (safety cap for fleet-wide runs).",+ )+ parser.add_argument(+ "--sleep",+ type=float,+ default=DEFAULT_SLEEP_SECONDS,+ help=f"Seconds to sleep after each dispatch to spread queue load (default {DEFAULT_SLEEP_SECONDS}).",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ team_ids: list[int] | None = options["team_ids"]+ live_run: bool = options["live_run"]+ limit: int | None = options["limit"]+ sleep_seconds: float = options["sleep"]++ if limit is not None and limit <= 0:+ raise CommandError("--limit must be a positive integer")++ queryset = (+ DataWarehouseSavedQuery.objects.filter(deleted=False, is_test=False, managed_viewset__isnull=True)+ .select_related("team", "team__organization")+ .order_by("team_id", "id")+ )+ if team_ids:+ queryset = queryset.filter(team_id__in=team_ids)++ # Flag + AI-consent are per team, not per view, so evaluate the team gate once and reuse it for+ # every view that team owns (the queryset is ordered by team_id).+ team_gate: dict[int, bool] = {}+ per_team_dispatched: Counter[int] = Counter()+ scanned = 0+ dispatched = 0+ truncated = False++ for saved_query in queryset.iterator(chunk_size=500):+ if limit is not None and dispatched >= limit:+ truncated = True+ break++ scanned += 1+ team_id = saved_query.team_id+ if team_id not in team_gate:+ team_gate[team_id] = enrichment_gates_pass(saved_query)+ if not team_gate[team_id]:+ continue+ if not view_ready_for_enrichment(saved_query):+ continue++ if live_run:+ dispatch_view_enrichment(team_id, str(saved_query.id))+ if sleep_seconds > 0:+ time.sleep(sleep_seconds)++ dispatched += 1+ per_team_dispatched[team_id] += 1++ self._report(+ live_run=live_run,+ scanned=scanned,+ dispatched=dispatched,+ per_team_dispatched=per_team_dispatched,+ truncated=truncated,+ limit=limit,+ )++ def _report(+ self,+ *,+ live_run: bool,+ scanned: int,+ dispatched: int,+ per_team_dispatched: "Counter[int]",+ truncated: bool,+ limit: int | None,+ ) -> None:+ verb = "dispatched" if live_run else "would dispatch"+ logger.info(+ "view_enrichment_backfill.done",+ live_run=live_run,+ scanned=scanned,+ dispatched=dispatched,+ teams=len(per_team_dispatched),+ truncated=truncated,+ )+ self.stdout.write(f"Scanned {scanned} view(s); {verb} {dispatched} across {len(per_team_dispatched)} team(s).")+ for team_id, count in sorted(per_team_dispatched.items()):+ self.stdout.write(f" team {team_id}: {count}")+ if not live_run:+ self.stdout.write("Dry run: nothing was dispatched. Re-run with --live-run to enqueue workflows.")+ if truncated:+ self.stdout.write(+ self.style.WARNING(+ f"Stopped at --limit {limit}; more views remain. Re-run to continue (already-enriched "+ "views are skipped)."+ )+ )diff --git a/products/data_modeling/backend/tests/test_backfill_view_semantic_enrichment.py b/products/data_modeling/backend/tests/test_backfill_view_semantic_enrichment.pynew file mode 100644index 000000000000..0fcbbf8fcbfd--- /dev/null+++ b/products/data_modeling/backend/tests/test_backfill_view_semantic_enrichment.py@@ -0,0 +1,126 @@+from io import StringIO+from typing import Any++import pytest+from unittest.mock import patch++from django.core.management import call_command++from parameterized import parameterized++from posthog.models import Organization, Team++from products.data_modeling.backend.logic import enrich_view_semantics as enrich+from products.data_modeling.backend.logic.enrich_view_semantics import compute_enrichment_hash+from products.data_modeling.backend.models.datawarehouse_managed_viewset import DataWarehouseManagedViewSet+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.warehouse_sources.backend.facade.types import DataWarehouseManagedViewSetKind++pytestmark = pytest.mark.django_db++COMMAND = "backfill_view_semantic_enrichment"+DISPATCH = (+ "products.data_modeling.backend.management.commands.backfill_view_semantic_enrichment.dispatch_view_enrichment"+)+++def _team() -> Team:+ return Team.objects.create(organization=Organization.objects.create(name="org"), name="t")+++def _columns(*names: str) -> dict[str, Any]:+ return {name: {"clickhouse": "String", "hogql": "StringDatabaseField"} for name in names}+++def _saved_query(team: Team, **extra: Any) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ team=team,+ name=extra.pop("name", "my_view"),+ query={"query": extra.pop("query", "SELECT amount FROM events")},+ columns=extra.pop("columns", _columns("amount")),+ **extra,+ )+++def _run(*, enabled: bool = True, **options: Any) -> tuple[Any, str]:+ with (+ patch.object(enrich, "enrichment_enabled", return_value=enabled),+ patch(DISPATCH) as dispatch,+ ):+ out = StringIO()+ call_command(COMMAND, sleep=0, stdout=out, **options)+ return dispatch, out.getvalue()+++class TestBackfillViewSemanticEnrichment:+ def test_live_run_dispatches_eligible_view(self):+ team = _team()+ sq = _saved_query(team)++ dispatch, _ = _run(team_ids=[team.id], live_run=True)++ dispatch.assert_called_once_with(team.id, str(sq.id))++ def test_dry_run_is_default_and_dispatches_nothing(self):+ team = _team()+ _saved_query(team)++ dispatch, output = _run(team_ids=[team.id])++ dispatch.assert_not_called()+ assert "would dispatch 1" in output++ def test_team_ids_excludes_other_teams(self):+ targeted, other = _team(), _team()+ sq = _saved_query(targeted)+ _saved_query(other)++ dispatch, _ = _run(team_ids=[targeted.id], live_run=True)++ dispatch.assert_called_once_with(targeted.id, str(sq.id))++ def test_all_covers_every_team(self):+ team_a, team_b = _team(), _team()+ _saved_query(team_a)+ _saved_query(team_b)++ dispatch, _ = _run(all=True, live_run=True)++ assert dispatch.call_count == 2++ def test_limit_caps_dispatches(self):+ team = _team()+ for i in range(3):+ _saved_query(team, name=f"view_{i}")++ dispatch, output = _run(all=True, live_run=True, limit=2)++ assert dispatch.call_count == 2+ assert "--limit 2" in output++ @parameterized.expand(+ [+ ("flag_disabled", False, {}),+ ("deleted", True, {"deleted": True}),+ ("is_test", True, {"is_test": True}),+ ("empty_columns", True, {"columns": {}}),+ ("already_enriched", True, {"enriched": True}),+ ("managed_viewset", True, {"managed": True}),+ ]+ )+ def test_skips_gated_or_ineligible_views(self, _name, enabled, mods):+ team = _team()+ if mods.pop("managed", False):+ mods["managed_viewset"] = DataWarehouseManagedViewSet.objects.create(+ team=team, kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS+ )+ enriched = mods.pop("enriched", False)+ sq = _saved_query(team, **mods)+ if enriched:+ DataWarehouseSavedQuery.objects.filter(id=sq.id).update(+ semantic_enrichment_hash=compute_enrichment_hash(sq)+ )++ dispatch, _ = _run(team_ids=[team.id], live_run=True, enabled=enabled)++ dispatch.assert_not_called()