: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
fix(data-warehouse): only trigger table metadata workflows when needed (#67086)
Tom Owers4346bf4848c6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.pyindex e8590bd2f6c7..f491b5f1372d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py@@ -372,8 +372,8 @@ class ExternalDataJobWorkflow(PostHogWorkflow):if isinstance(create_job_result, tuple):job_id, incremental_or_append, source_type = create_job_resultschema_name, last_synced_at, emit_signals_enabled = None, None, False- enrichment_enabled = False- statistics_enabled = False+ enrichment_needed = False+ statistics_needed = Falseelse:job_id = create_job_result.job_idincremental_or_append = create_job_result.incremental_or_append@@ -381,8 +381,8 @@ class ExternalDataJobWorkflow(PostHogWorkflow):schema_name = create_job_result.schema_namelast_synced_at = create_job_result.last_synced_atemit_signals_enabled = create_job_result.emit_signals_enabled- enrichment_enabled = create_job_result.enrichment_enabled- statistics_enabled = create_job_result.statistics_enabled+ enrichment_needed = create_job_result.enrichment_needed+ statistics_needed = create_job_result.statistics_neededupdate_inputs.job_id = str(job_id) if job_id is not None else None# Check billing limits@@ -526,32 +526,40 @@ class ExternalDataJobWorkflow(PostHogWorkflow):execution_timeout=dt.timedelta(hours=2),)- # Generate semantic descriptions for the synced table. Gated up front (feature flag + AI- # data-processing consent, resolved in create_external_data_job_model_activity) so we don't- # spawn a child that would immediately no-op; the activity re-checks as a safety net and is- # idempotent. Fire-and-forget child on the dedicated metadata queue; ABANDON means it never- # blocks or fails the import.- if enrichment_enabled:- await workflow.start_child_workflow(- EnrichTableSemanticsWorkflow.run,- EnrichTableSemanticsInputs(- team_id=inputs.team_id,- schema_id=inputs.external_data_schema_id,- ),- id=f"enrich-warehouse-table-semantics-{job_id}",- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,- task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,- parent_close_policy=ParentClosePolicy.ABANDON,- execution_timeout=dt.timedelta(minutes=30),- )+ # Generate semantic descriptions for the synced table. Gated up front on actual need+ # (feature flag + AI consent AND unannotated columns / missing table description, resolved in+ # create_external_data_job_model_activity) so a steady-state sync — which re-fires every few+ # minutes — doesn't spawn a child that immediately no-ops; the activity re-checks as a safety+ # net and is idempotent. Keyed per schema so only one runs per schema at a time: a concurrent+ # sync gets WorkflowAlreadyStartedError, which we swallow. Fire-and-forget child on the+ # dedicated metadata queue; ABANDON means it never blocks or fails the import.+ if enrichment_needed:+ try:+ await workflow.start_child_workflow(+ EnrichTableSemanticsWorkflow.run,+ EnrichTableSemanticsInputs(+ team_id=inputs.team_id,+ schema_id=inputs.external_data_schema_id,+ ),+ id=f"enrich-warehouse-table-semantics-{inputs.external_data_schema_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,+ parent_close_policy=ParentClosePolicy.ABANDON,+ execution_timeout=dt.timedelta(minutes=30),+ )+ except WorkflowAlreadyStartedError:+ workflow.logger.info(+ "Semantic enrichment already running for schema, skipping",+ extra={"schema_id": str(inputs.external_data_schema_id)},+ )# Profile the synced table's columns (null %, min/max, row count) from the Delta log. Gated up- # front (feature flag only — no data leaves our infra). Keyed per schema so only one runs per- # schema at a time: a concurrent sync that tries to start a second one gets- # WorkflowAlreadyStartedError, which we swallow (the running one already covers this schema).- # The activity itself caps recompute to once a day. Fire-and-forget metadata queue; ABANDON so- # it never blocks or fails the import.- if statistics_enabled:+ # front on staleness (feature flag AND stats older than the recompute interval — no data leaves+ # our infra). Keyed per schema so only one runs per schema at a time: a concurrent sync that+ # tries to start a second one gets WorkflowAlreadyStartedError, which we swallow (the running+ # one already covers this schema). The activity itself re-checks recency. Fire-and-forget+ # metadata queue; ABANDON so it never blocks or fails the import.+ if statistics_needed:try:await workflow.start_child_workflow(ComputeTableStatisticsWorkflow.run,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 6719ada2d71b..e5d994fe7e42 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -4,6 +4,8 @@ import dataclassesfrom typing import Anyfrom django.db import close_old_connections+from django.db.models import Max+from django.utils import timezoneimport posthoganalyticsfrom structlog.contextvars import bind_contextvars@@ -14,9 +16,12 @@ from posthog.models.team.team import Teamfrom posthog.temporal.common.logger import get_loggerfrom products.data_warehouse.backend.facade.api import delete_external_data_schedule+from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation+from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatisticsfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import HIDDEN_COLUMNS, DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.external_product_hooks import emit_signals_enabled_forWAREHOUSE_PIPELINES_V3_FLAG = "warehouse-pipelines-v3"@@ -53,6 +58,48 @@ def is_pipeline_v3_enabled(team_id: int, source_type: str) -> bool:LOGGER = get_logger(__name__)+def _statistics_stale(team_id: int, table: DataWarehouseTable | None) -> bool:+ """Whether column statistics need recomputing: no stats yet, or the freshest column row is older+ than the recompute interval. Mirrors compute_table_statistics' own skip check so we don't spawn a+ child that would immediately no-op on every sync."""+ if table is None:+ # First-ever sync — the table is created during it, so let the (post-sync) profiling run once.+ return True+ # Lazy: compute_table_statistics drags deltalake/pyarrow; keep it off this activity's import path.+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import ( # noqa: PLC0415+ MIN_RECOMPUTE_INTERVAL,+ )++ latest = (+ WarehouseColumnStatistics.objects.for_team(team_id)+ .filter(table_id=table.id)+ .aggregate(latest=Max("computed_at"))["latest"]+ )+ return latest is None or (timezone.now() - latest) >= MIN_RECOMPUTE_INTERVAL+++def _enrichment_pending(team_id: int, table: DataWarehouseTable | None, schema: ExternalDataSchema) -> bool:+ """Whether semantic enrichment has work to do: any column without an annotation, or a missing+ table-level description. Mirrors enrich_table_semantics' skip check. Computed from pre-sync state,+ so columns added by this sync are picked up on the next one (matching the activity's re-sync+ behaviour) rather than re-running enrichment on every sync."""+ if table is None:+ # First-ever sync — nothing is annotated yet, so there is work to do.+ return True+ # Hidden plumbing columns (_dlt_id, partition key, …) are never enriched, so they'd otherwise+ # show up perpetually in `columns - annotated` and keep this returning True on every sync.+ columns = set((table.columns or {}).keys()) - HIDDEN_COLUMNS+ annotated = set(+ WarehouseColumnAnnotation.objects.for_team(team_id)+ .filter(table_id=table.id)+ .values_list("column_name", flat=True)+ )+ new_columns = columns - annotated+ # "" is the table-level annotation; absent description on both schema and annotations means work.+ table_needs_description = not bool(schema.description) and "" not in annotated+ return bool(new_columns or table_needs_description)++def _build_schema_snapshot(schema: ExternalDataSchema) -> dict[str, Any]:return {"name": schema.name,@@ -98,12 +145,17 @@ class CreateExternalDataJobModelActivityOutputs:# ISO timestamp of when the previous sync completed, used to detect new recordslast_synced_at: str | None = Noneemit_signals_enabled: bool = False- # True when semantic enrichment should run (feature flag on AND AI data processing approved), so the- # workflow can skip starting the enrichment child entirely instead of spawning a no-op.+ # True when semantic enrichment is permitted (feature flag on AND AI data processing approved).enrichment_enabled: bool = False- # True when column-statistics profiling should run (feature flag on). No AI-data-processing consent+ # True when column-statistics profiling is permitted (feature flag on). No AI-data-processing consent# term: it reads only the Delta log and writes to our own DB — nothing leaves our infra.statistics_enabled: bool = False+ # True when enrichment is permitted AND there is actually work to do (unannotated columns or a missing+ # table description). The workflow gates the child on this so a steady-state sync — which re-fires+ # every few minutes — doesn't spawn a workflow + activity that just no-ops.+ enrichment_needed: bool = False+ # True when statistics are permitted AND stale (no row yet, or older than the recompute interval).+ statistics_needed: bool = False@activity.defn@@ -183,6 +235,12 @@ def create_external_data_job_model_activity(statistics_should_run = bool(team is not None and statistics_enabled(team))+ # Narrow "permitted" down to "permitted AND has work to do" so steady-state syncs don't spawn+ # no-op metadata workflows. The activities re-check this themselves as a safety net.+ table = schema.table+ enrichment_needed = enrichment_should_run and _enrichment_pending(inputs.team_id, table, schema)+ statistics_needed = statistics_should_run and _statistics_stale(inputs.team_id, table)+return CreateExternalDataJobModelActivityOutputs(job_id=str(job.id),incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,@@ -192,6 +250,8 @@ def create_external_data_job_model_activity(emit_signals_enabled=emit_signals_enabled,enrichment_enabled=enrichment_should_run,statistics_enabled=statistics_should_run,+ enrichment_needed=enrichment_needed,+ statistics_needed=statistics_needed,)except Exception as e:logger.exception(diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pynew file mode 100644index 000000000000..1a1b19dc06f2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -0,0 +1,131 @@+import datetime as dt++import pytest++from django.utils import timezone++from parameterized import parameterized++from posthog.models import Organization, Team++from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation+from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics+from products.warehouse_sources.backend.models.credential import DataWarehouseCredential+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (+ _enrichment_pending,+ _statistics_stale,+)+++def _team() -> Team:+ org = Organization.objects.create(name="org")+ return Team.objects.create(organization=org, name="t")+++def _table(team: Team, *, columns: dict | None = None) -> DataWarehouseTable:+ credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=team)+ return DataWarehouseTable.objects.create(+ name="stripe_charge",+ format="Parquet",+ team=team,+ credential=credential,+ url_pattern="https://bucket.s3/data/*",+ columns=columns or {"amount": {"clickhouse": "Nullable(Int64)"}},+ )+++def _schema(team: Team, table: DataWarehouseTable | None, *, description: str | None = None) -> ExternalDataSchema:+ source = ExternalDataSource.objects.create(source_id="src", connection_id="conn", team=team, source_type="Stripe")+ return ExternalDataSchema.objects.create(+ name="Charge", team=team, source=source, table=table, description=description+ )+++class TestStatisticsStale:+ def test_stale_when_table_is_none(self) -> None:+ # First-ever sync: the table is created during the sync, so the (post-sync) profiling should run.+ team = _team()+ assert _statistics_stale(team.id, None) is True++ def test_stale_when_no_stats_rows(self) -> None:+ team = _team()+ table = _table(team)+ assert _statistics_stale(team.id, table) is True++ @parameterized.expand(+ [+ # Guards against re-profiling a freshly-computed table on every sync (the bug we're fixing).+ ("recent_not_stale", dt.timedelta(hours=1), False),+ # Guards against never recomputing once a row exists.+ ("older_than_interval_stale", dt.timedelta(hours=25), True),+ ]+ )+ def test_staleness_by_recency(self, _name: str, age: dt.timedelta, expected: bool) -> None:+ team = _team()+ table = _table(team)+ WarehouseColumnStatistics.objects.for_team(team.id).create(+ team=team, table=table, column_name="amount", computed_at=timezone.now() - age+ )+ assert _statistics_stale(team.id, table) is expected+++class TestEnrichmentPending:+ def _annotate(self, team: Team, table: DataWarehouseTable, column_name: str) -> None:+ WarehouseColumnAnnotation.objects.for_team(team.id).create(+ team=team,+ table=table,+ column_name=column_name,+ description="desc",+ description_source=WarehouseColumnAnnotation.DescriptionSource.AI_GENERATED,+ )++ def test_pending_when_table_is_none(self) -> None:+ # First-ever sync: nothing is annotated yet, so there is work to do.+ team = _team()+ assert _enrichment_pending(team.id, None, _schema(team, None)) is True++ def test_pending_when_a_column_is_unannotated(self) -> None:+ # New/undescribed column must re-trigger enrichment, else added columns never get described.+ team = _team()+ table = _table(team, columns={"amount": {}, "currency": {}})+ self._annotate(team, table, "amount")+ # currency has no annotation+ assert _enrichment_pending(team.id, table, _schema(team, table, description="present")) is True++ def test_not_pending_when_all_columns_annotated_and_table_described(self) -> None:+ # The steady state: nothing new to do — must NOT spawn a workflow every sync.+ team = _team()+ table = _table(team, columns={"amount": {}})+ self._annotate(team, table, "amount")+ assert _enrichment_pending(team.id, table, _schema(team, table, description="present")) is False++ def test_not_pending_when_only_hidden_columns_unannotated(self) -> None:+ # Hidden plumbing columns (_dlt_id, partition key, …) are never enriched, so they must not+ # count as pending work — otherwise enrichment re-fires on every steady-state sync.+ team = _team()+ table = _table(+ team,+ columns={"amount": {}, "_dlt_id": {}, "_dlt_load_id": {}, "_ph_debug": {}, "_ph_partition_key": {}},+ )+ self._annotate(team, table, "amount")+ assert _enrichment_pending(team.id, table, _schema(team, table, description="present")) is False++ def test_pending_when_table_description_missing(self) -> None:+ # Columns all annotated, but neither a schema description nor a table-level ("") annotation exists.+ team = _team()+ table = _table(team, columns={"amount": {}})+ self._annotate(team, table, "amount")+ assert _enrichment_pending(team.id, table, _schema(team, table, description=None)) is True++ def test_not_pending_when_table_level_annotation_exists(self) -> None:+ # A table-level annotation ("" column) satisfies the table-description requirement.+ team = _team()+ table = _table(team, columns={"amount": {}})+ self._annotate(team, table, "amount")+ self._annotate(team, table, "")+ assert _enrichment_pending(team.id, table, _schema(team, table, description=None)) is False