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-warehouse): add per-column data statistics for warehouse sources (#66074)

Tom Owers88ed1108ad28
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index 33eb15689bcd..30199a13dc95 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -838,6 +838,27 @@ jobs:
"timestamp": "${{ github.event.head_commit.timestamp }}"
}
+ - name: Trigger Data Warehouse Metadata Temporal Worker Cloud deployment
+ if: steps.check_changes_data_warehouse_temporal_worker.outputs.changed == 'true'
+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1
+ with:
+ token: ${{ steps.deployer.outputs.token }}
+ repository: PostHog/charts
+ event-type: commit_state_update
+ client-payload: |
+ {
+ "values": {
+ "image": {
+ "sha": "${{ github.sha }}@${{ steps.build_retry.outputs.digest || steps.build.outputs.digest }}"
+ }
+ },
+ "release": "temporal-worker-data-warehouse-metadata",
+ "commit": ${{ toJson(github.event.head_commit) }},
+ "repository": ${{ toJson(github.repository) }},
+ "labels": ${{ steps.labels.outputs.labels }},
+ "timestamp": "${{ github.event.head_commit.timestamp }}"
+ }
+
- name: Check for changes that affect warehouse-sources-load
id: check_changes_warehouse_sources_load
run: |
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 5f2ead32ee4b..0d8490ff09f2 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -260,6 +260,7 @@ rules:
|VisionAction
|VisionActionRun
|WarehouseColumnAnnotation
+ |WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
@@ -522,6 +523,7 @@ rules:
|VisionAction
|VisionActionRun
|WarehouseColumnAnnotation
+ |WarehouseColumnStatistics
|WebAnalyticsAchievementProgress
|WebAnalyticsFilterPreset
|WebAnalyticsInteraction
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 6be1cb207bfa..669e3f9f00bb 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -279,6 +279,7 @@ export const FEATURE_FLAGS = {
DATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modeling
DATA_MODELING_MULTI_DAG: 'data-modeling-multi-dag', // owner: #team-data-modeling
DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling
+ DATA_WAREHOUSE_COLUMN_STATISTICS: 'data-warehouse-column-statistics', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
DATA_WAREHOUSE_SEMANTIC_ENRICHMENT: 'data-warehouse-semantic-enrichment', // owner: #team-warehouse-sources
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 77942c027a16..5ae30cc00634 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -215,6 +215,10 @@ from products.warehouse_sources.backend.facade.temporal import (
WORKFLOWS as DATA_SYNC_WORKFLOWS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources import load_all_sources
+from products.warehouse_sources.backend.temporal.data_imports.table_metadata_settings import (
+ ACTIVITIES as DATA_WAREHOUSE_METADATA_ACTIVITIES,
+ WORKFLOWS as DATA_WAREHOUSE_METADATA_WORKFLOWS,
+)
from products.web_analytics.backend.temporal import (
ACTIVITIES as WA_DIGEST_ACTIVITIES,
WORKFLOWS as WA_DIGEST_WORKFLOWS,
@@ -243,6 +247,11 @@ _task_queue_specs = [
DATA_SYNC_WORKFLOWS,
DATA_SYNC_ACTIVITIES,
),
+ (
+ settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
+ DATA_WAREHOUSE_METADATA_WORKFLOWS,
+ DATA_WAREHOUSE_METADATA_ACTIVITIES,
+ ),
(
settings.DATA_MODELING_TASK_QUEUE,
DATA_MODELING_WORKFLOWS,
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 5c665dab7590..5fe05c960e1e 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -98,6 +98,9 @@ default_task_queue = os.getenv("TEMPORAL_TASK_QUEUE", "general-purpose-task-queu
TEMPORAL_TASK_QUEUE: str = _set_temporal_task_queue(default_task_queue)
DATA_WAREHOUSE_TASK_QUEUE = _set_temporal_task_queue("data-warehouse-task-queue")
DATA_WAREHOUSE_CDP_PRODUCER_TASK_QUEUE = _set_temporal_task_queue("data-warehouse-cdp-producer-task-queue")
+# Post-sync table metadata (semantic enrichment + column statistics) runs on its own worker so this
+# best-effort work can't starve the import pipeline.
+DATA_WAREHOUSE_METADATA_TASK_QUEUE = _set_temporal_task_queue("data-warehouse-metadata-task-queue")
MAX_AI_TASK_QUEUE = _set_temporal_task_queue("max-ai-task-queue")
BATCH_EXPORTS_TASK_QUEUE = _set_temporal_task_queue("batch-exports-task-queue")
DATA_MODELING_TASK_QUEUE = _set_temporal_task_queue("data-modeling-task-queue")
diff --git a/products/data_warehouse/backend/presentation/views/column_statistics.py b/products/data_warehouse/backend/presentation/views/column_statistics.py
new file mode 100644
index 000000000000..4e2b32ba90d5
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/column_statistics.py
@@ -0,0 +1,123 @@
+import uuid
+from typing import Any
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema
+from rest_framework import serializers, viewsets
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+
+
+class WarehouseColumnStatisticsSerializer(serializers.ModelSerializer):
+ table = serializers.UUIDField(
+ source="table_id", read_only=True, help_text="ID of the data warehouse table this column belongs to."
+ )
+ column_name = serializers.CharField(read_only=True, help_text="Name of the column these statistics describe.")
+ column_type = serializers.CharField(
+ read_only=True, help_text="ClickHouse type the statistics were computed against (e.g. Int64, DateTime64)."
+ )
+ row_count = serializers.IntegerField(
+ read_only=True, help_text="Total number of rows in the table when these statistics were computed."
+ )
+ null_count = serializers.IntegerField(
+ read_only=True, help_text="Number of NULL values in this column, or null if the Delta log carried no count."
+ )
+ null_fraction = serializers.FloatField(
+ read_only=True, help_text="Fraction of values that are NULL (null_count / row_count), between 0 and 1."
+ )
+ min_value = serializers.CharField(
+ read_only=True,
+ help_text=(
+ "Minimum value in the column, as a string. Null when unavailable. For string columns this may be "
+ "truncated by the underlying Delta statistics, so treat string bounds as approximate."
+ ),
+ )
+ max_value = serializers.CharField(
+ read_only=True, help_text="Maximum value in the column, as a string. Null when unavailable (see min_value)."
+ )
+ has_min_max = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether the Delta log carried min/max statistics for this column (false for some nested/binary types).",
+ )
+ computed_at = serializers.DateTimeField(read_only=True, help_text="When these statistics were last computed.")
+ computed_for_delta_version = serializers.IntegerField(
+ read_only=True, help_text="Delta table version the statistics were computed against."
+ )
+ stats_basis = serializers.CharField(
+ read_only=True, help_text="How the statistics were produced. Currently always 'delta_log'."
+ )
+
+ class Meta:
+ model = WarehouseColumnStatistics
+ fields = [
+ "id",
+ "table",
+ "column_name",
+ "column_type",
+ "row_count",
+ "null_count",
+ "null_fraction",
+ "min_value",
+ "max_value",
+ "has_min_max",
+ "computed_at",
+ "computed_for_delta_version",
+ "stats_basis",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = fields
+
+
+class WarehouseColumnStatisticsViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
+ """Read per-column data statistics (null fraction, min/max, row count) for warehouse tables.
+
+ Statistics are computed automatically after a sync and surfaced to the AI agent so it can write
+ better queries. They are system-owned and read-only here. List can be filtered to one table with
+ `?table_id=<uuid>`.
+ """
+
+ # Statistics describe `DataWarehouseTable` rows, so they live under the warehouse table family — both
+ # the resource-level scope and the per-object filtering below key off `warehouse_table`.
+ scope_object = "warehouse_table"
+ scope_object_read_actions = ["list", "retrieve"]
+ # `.unscoped()` is import-safe (the fail-closed manager raises on `.all()` without team context);
+ # the mixin scopes every request by team_id via the parent lookup.
+ queryset = WarehouseColumnStatistics.objects.unscoped()
+ serializer_class = WarehouseColumnStatisticsSerializer
+ ordering = "column_name"
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ name="table_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.QUERY,
+ description="Only return statistics for this data warehouse table.",
+ )
+ ]
+ )
+ def list(self, request: Any, *args: Any, **kwargs: Any) -> Any:
+ return super().list(request, *args, **kwargs)
+
+ def safely_get_queryset(self, queryset: Any) -> Any:
+ # Statistics inherit their table's access: only expose those whose table the user can reach.
+ # Applied for every action so retrieve on stats for an inaccessible table 404s through the
+ # queryset rather than slipping past object-level checks.
+ accessible_tables = self.user_access_control.filter_queryset_by_access_level(
+ DataWarehouseTable.objects.filter(team_id=self.team_id)
+ )
+ queryset = queryset.filter(table__in=accessible_tables)
+ table_id = self.request.query_params.get("table_id")
+ if table_id:
+ # Guard the UUID cast: a malformed table_id would otherwise raise ValueError deep in the ORM
+ # and surface as a 500. Treat an unparseable id as "no such table" (empty result).
+ try:
+ uuid.UUID(table_id)
+ except ValueError:
+ return queryset.none()
+ queryset = queryset.filter(table_id=table_id)
+ return queryset.order_by(self.ordering)
diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.py
index 8bc5f4b79d90..e71792880e32 100644
--- a/products/data_warehouse/backend/routes.py
+++ b/products/data_warehouse/backend/routes.py
@@ -3,6 +3,7 @@ from posthog.api.routing import RouterRegistry
import products.data_warehouse.backend.presentation.views.fix_hogql as fix_hogql
from products.data_warehouse.backend.presentation.views import (
column_annotation,
+ column_statistics,
data_modeling_job,
data_warehouse,
external_data_schema,
@@ -87,3 +88,9 @@ def register_routes(routers: RouterRegistry) -> None:
"project_warehouse_column_annotations",
["team_id"],
)
+ routers.projects.register(
+ r"warehouse_column_statistics",
+ column_statistics.WarehouseColumnStatisticsViewSet,
+ "project_warehouse_column_statistics",
+ ["team_id"],
+ )
diff --git a/products/data_warehouse/backend/tests/api/test_column_statistics.py b/products/data_warehouse/backend/tests/api/test_column_statistics.py
new file mode 100644
index 000000000000..5ecba4e51e59
--- /dev/null
+++ b/products/data_warehouse/backend/tests/api/test_column_statistics.py
@@ -0,0 +1,60 @@
+from posthog.test.base import APIBaseTest
+
+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.table import DataWarehouseTable
+
+
+class TestWarehouseColumnStatistics(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=self.team)
+ self.table = DataWarehouseTable.objects.create(
+ name="stripe_charges",
+ format="Parquet",
+ team=self.team,
+ credential=self.credential,
+ url_pattern="https://bucket.s3/data/*",
+ )
+
+ def _url(self, suffix: str = "") -> str:
+ return f"/api/projects/{self.team.pk}/warehouse_column_statistics/{suffix}"
+
+ def _make_stat(self, table: DataWarehouseTable, column_name: str, **kwargs) -> WarehouseColumnStatistics:
+ return WarehouseColumnStatistics.objects.for_team(self.team.pk).create(
+ team=self.team, table=table, column_name=column_name, **kwargs
+ )
+
+ def test_list_filters_by_table_id(self):
+ other_table = DataWarehouseTable.objects.create(
+ name="stripe_customers",
+ format="Parquet",
+ team=self.team,
+ credential=self.credential,
+ url_pattern="https://bucket.s3/data/*",
+ )
+ self._make_stat(self.table, "amount", row_count=100, null_count=5, null_fraction=0.05, min_value="1")
+ self._make_stat(other_table, "email", row_count=50)
+
+ response = self.client.get(self._url(f"?table_id={self.table.id}"))
+ assert response.status_code == 200, response.json()
+ results = response.json()["results"]
+ assert len(results) == 1
+ assert results[0]["column_name"] == "amount"
+ assert results[0]["row_count"] == 100
+ assert results[0]["null_fraction"] == 0.05
+ assert results[0]["min_value"] == "1"
+
+ def test_invalid_table_id_returns_empty_not_500(self):
+ # A malformed table_id must not 500 (ValueError from the UUID cast) — it should filter to nothing.
+ self._make_stat(self.table, "amount", row_count=1)
+ response = self.client.get(self._url("?table_id=not-a-uuid"))
+ assert response.status_code == 200, response.json()
+ assert response.json()["results"] == []
+
+ def test_read_only_rejects_writes(self):
+ # Statistics are system-owned: the endpoint must never accept create/update/delete.
+ stat = self._make_stat(self.table, "amount", row_count=1)
+ assert self.client.post(self._url(), {"table": str(self.table.id), "column_name": "x"}).status_code == 405
+ assert self.client.patch(self._url(f"{stat.id}/"), {"row_count": 9}).status_code == 405
+ assert self.client.delete(self._url(f"{stat.id}/")).status_code == 405
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 4aec02747e88..0a513f184d00 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -365,6 +365,46 @@ export interface PatchedWarehouseColumnAnnotationApi {
readonly updated_at?: string | null
}
+export interface WarehouseColumnStatisticsApi {
+ readonly id: string
+ /** ID of the data warehouse table this column belongs to. */
+ readonly table: string
+ /** Name of the column these statistics describe. */
+ readonly column_name: string
+ /** ClickHouse type the statistics were computed against (e.g. Int64, DateTime64). */
+ readonly column_type: string
+ /** Total number of rows in the table when these statistics were computed. */
+ readonly row_count: number
+ /** Number of NULL values in this column, or null if the Delta log carried no count. */
+ readonly null_count: number
+ /** Fraction of values that are NULL (null_count / row_count), between 0 and 1. */
+ readonly null_fraction: number
+ /** Minimum value in the column, as a string. Null when unavailable. For string columns this may be truncated by the underlying Delta statistics, so treat string bounds as approximate. */
+ readonly min_value: string
+ /** Maximum value in the column, as a string. Null when unavailable (see min_value). */
+ readonly max_value: string
+ /** Whether the Delta log carried min/max statistics for this column (false for some nested/binary types). */
+ readonly has_min_max: boolean
+ /** When these statistics were last computed. */
+ readonly computed_at: string
+ /** Delta table version the statistics were computed against. */
+ readonly computed_for_delta_version: number
+ /** How the statistics were produced. Currently always 'delta_log'. */
+ readonly stats_basis: string
+ readonly created_at: string
+ /** @nullable */
+ readonly updated_at: string | null
+}
+
+export interface PaginatedWarehouseColumnStatisticsListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: WarehouseColumnStatisticsApi[]
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -2419,6 +2459,21 @@ export type WarehouseColumnAnnotationsListParams = {
table_id?: string
}
+export type WarehouseColumnStatisticsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Only return statistics for this data warehouse table.
+ */
+ table_id?: string
+}
+
export type WarehouseModelPathsListParams = {
/**
* Number of results to return per page.
diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.ts
index 8d8204eb3fc7..09178ec1f114 100644
--- a/products/data_warehouse/frontend/generated/api.ts
+++ b/products/data_warehouse/frontend/generated/api.ts
@@ -32,6 +32,7 @@ import type {
PaginatedTableListApi,
PaginatedViewLinkListApi,
PaginatedWarehouseColumnAnnotationListApi,
+ PaginatedWarehouseColumnStatisticsListApi,
PatchedDataWarehouseSavedQueryApi,
PatchedDataWarehouseSavedQueryDraftApi,
PatchedDataWarehouseSavedQueryFolderApi,
@@ -50,6 +51,8 @@ import type {
ViewLinkValidationApi,
WarehouseColumnAnnotationApi,
WarehouseColumnAnnotationsListParams,
+ WarehouseColumnStatisticsApi,
+ WarehouseColumnStatisticsListParams,
WarehouseModelPathsListParams,
WarehouseSavedQueriesListParams,
WarehouseSavedQueryDraftsListParams,
@@ -933,6 +936,68 @@ export const warehouseColumnAnnotationsDestroy = async (
})
}
+export const getWarehouseColumnStatisticsListUrl = (
+ projectId: string,
+ params?: WarehouseColumnStatisticsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/warehouse_column_statistics/?${stringifiedParams}`
+ : `/api/projects/${projectId}/warehouse_column_statistics/`
+}
+
+/**
+ * Read per-column data statistics (null fraction, min/max, row count) for warehouse tables.
+ *
+ * Statistics are computed automatically after a sync and surfaced to the AI agent so it can write
+ * better queries. They are system-owned and read-only here. List can be filtered to one table with
+ * `?table_id=<uuid>`.
+ */
+export const warehouseColumnStatisticsList = async (
+ projectId: string,
+ params?: WarehouseColumnStatisticsListParams,
+ options?: RequestInit
+): Promise<PaginatedWarehouseColumnStatisticsListApi> => {
+ return apiMutator<PaginatedWarehouseColumnStatisticsListApi>(
+ getWarehouseColumnStatisticsListUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getWarehouseColumnStatisticsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/warehouse_column_statistics/${id}/`
+}
+
+/**
+ * Read per-column data statistics (null fraction, min/max, row count) for warehouse tables.
+ *
+ * Statistics are computed automatically after a sync and surfaced to the AI agent so it can write
+ * better queries. They are system-owned and read-only here. List can be filtered to one table with
+ * `?table_id=<uuid>`.
+ */
+export const warehouseColumnStatisticsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<WarehouseColumnStatisticsApi> => {
+ return apiMutator<WarehouseColumnStatisticsApi>(getWarehouseColumnStatisticsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getWarehouseDagListUrl = (projectId: string) => {
return `/api/projects/${projectId}/warehouse_dag/`
}
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 0202fc1aa573..e3a97533830a 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -390,6 +390,12 @@ tools:
warehouse-column-annotations-update:
operation: warehouse_column_annotations_update
enabled: false
+ warehouse-column-statistics-list:
+ operation: warehouse_column_statistics_list
+ enabled: false
+ warehouse-column-statistics-retrieve:
+ operation: warehouse_column_statistics_retrieve
+ enabled: false
warehouse-dag-list:
operation: warehouse_dag_list
enabled: false
diff --git a/products/warehouse_sources/backend/migrations/0051_warehousecolumnstatistics.py b/products/warehouse_sources/backend/migrations/0051_warehousecolumnstatistics.py
new file mode 100644
index 000000000000..422c78873eae
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0051_warehousecolumnstatistics.py
@@ -0,0 +1,71 @@
+# Generated by Django 5.2.14 on 2026-06-25 13:01
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1238_ducklakebackfill_earliest_event_date"),
+ ("warehouse_sources", "0050_alter_externaldatasource_source_type_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="WarehouseColumnStatistics",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ ("column_name", models.CharField(max_length=400)),
+ ("column_type", models.CharField(blank=True, default="", max_length=400)),
+ ("row_count", models.BigIntegerField(null=True)),
+ ("null_count", models.BigIntegerField(null=True)),
+ ("null_fraction", models.FloatField(null=True)),
+ ("min_value", models.TextField(blank=True, null=True)),
+ ("max_value", models.TextField(blank=True, null=True)),
+ ("has_min_max", models.BooleanField(default=False)),
+ ("computed_at", models.DateTimeField(null=True)),
+ ("computed_for_delta_version", models.BigIntegerField(null=True)),
+ ("stats_basis", models.CharField(default="delta_log", max_length=32)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "table",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="column_statistics",
+ to="warehouse_sources.datawarehousetable",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"
+ ),
+ ),
+ ],
+ options={
+ "constraints": [
+ models.UniqueConstraint(fields=("table", "column_name"), name="unique_table_column_statistics")
+ ],
+ },
+ ),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 0c07e6051027..4b25fc5745ab 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0050_alter_externaldatasource_source_type_and_more
+0051_warehousecolumnstatistics
diff --git a/products/warehouse_sources/backend/models/__init__.py b/products/warehouse_sources/backend/models/__init__.py
index df1fc97c2b8e..1e223c01ba47 100644
--- a/products/warehouse_sources/backend/models/__init__.py
+++ b/products/warehouse_sources/backend/models/__init__.py
@@ -1,4 +1,5 @@
from .column_annotation import WarehouseColumnAnnotation
+from .column_statistics import WarehouseColumnStatistics
from .credential import DataWarehouseCredential
from .external_data_job import ExternalDataJob
from .external_data_schema import ExternalDataSchema
@@ -14,4 +15,5 @@ __all__ = [
"ExternalDataSource",
"PendingSourceCredential",
"WarehouseColumnAnnotation",
+ "WarehouseColumnStatistics",
]
diff --git a/products/warehouse_sources/backend/models/column_statistics.py b/products/warehouse_sources/backend/models/column_statistics.py
new file mode 100644
index 000000000000..9ebd53659901
--- /dev/null
+++ b/products/warehouse_sources/backend/models/column_statistics.py
@@ -0,0 +1,56 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel, sane_repr
+
+
+class WarehouseColumnStatistics(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
+ """Per-column data profile for a synced warehouse table, surfaced to the AI agent.
+
+ One row per (table, column). Stats are derived from the Delta transaction log's per-file statistics
+ (`num_records`, `null_count`, `min`, `max`) — aggregated across the snapshot's live files, so they
+ reflect the whole current table without scanning any data and are correct for full-refresh, append and
+ incremental-upsert syncs alike. Unlike [[WarehouseColumnAnnotation]] these are wholly system-owned and
+ overwritten on every recompute (never user-edited), so there is no table-level row — `row_count` and
+ `computed_at` are denormalised onto every column row.
+
+ `min`/`max` are stored as strings because a column can be int, datetime, decimal, etc.; `column_type`
+ records what they were computed against. delta-rs may omit log stats for some types (`has_min_max`
+ is then False) and truncates long-string min/max, so treat string bounds as approximate.
+ """
+
+ # db_constraint=False on the FKs to hot tables (posthog_team, posthog_user): creating a real FK
+ # constraint takes a SHARE ROW EXCLUSIVE lock on the parent, which stalls under write traffic. Team
+ # scoping is enforced at the app level by TeamScopedRootMixin, and these are derived rows, so we don't
+ # need DB-level referential integrity here. The table FK targets a non-hot table, so it keeps its constraint.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+ table = models.ForeignKey(
+ "warehouse_sources.DataWarehouseTable", on_delete=models.CASCADE, related_name="column_statistics"
+ )
+ column_name = models.CharField(max_length=400)
+ column_type = models.CharField(max_length=400, blank=True, default="")
+
+ # Denormalised onto every column row — one recompute writes them all atomically.
+ row_count = models.BigIntegerField(null=True)
+ null_count = models.BigIntegerField(null=True)
+ null_fraction = models.FloatField(null=True)
+ min_value = models.TextField(null=True, blank=True)
+ max_value = models.TextField(null=True, blank=True)
+ # False when the Delta log carried no min/max for this column (e.g. nested/binary types).
+ has_min_max = models.BooleanField(default=False)
+
+ computed_at = models.DateTimeField(null=True)
+ # Delta table version the stats were computed against; provenance + lets us spot staleness.
+ computed_for_delta_version = models.BigIntegerField(null=True)
+ # How the stats were produced. "delta_log" today; reserved for a future scan/sample basis.
+ stats_basis = models.CharField(max_length=32, default="delta_log")
+
+ __repr__ = sane_repr("table_id", "column_name", "computed_at")
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(fields=["table", "column_name"], name="unique_table_column_statistics"),
+ ]
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.py
index 9b9be7efe6f6..ea933a6682cd 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
@@ -56,6 +56,10 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
CheckBillingLimitsActivityInputs,
check_billing_limits_activity,
)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import (
+ ComputeTableStatisticsInputs,
+ ComputeTableStatisticsWorkflow,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (
CreateExternalDataJobModelActivityInputs,
create_external_data_job_model_activity,
@@ -365,6 +369,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
job_id, incremental_or_append, source_type = create_job_result
schema_name, last_synced_at, emit_signals_enabled = None, None, False
enrichment_enabled = False
+ statistics_enabled = False
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -373,6 +378,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
last_synced_at = create_job_result.last_synced_at
emit_signals_enabled = create_job_result.emit_signals_enabled
enrichment_enabled = create_job_result.enrichment_enabled
+ statistics_enabled = create_job_result.statistics_enabled
update_inputs.job_id = str(job_id) if job_id is not None else None
# Check billing limits
@@ -496,7 +502,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
# 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 data-warehouse queue; ABANDON means it never
+ # 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(
@@ -507,11 +513,37 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
),
id=f"enrich-warehouse-table-semantics-{job_id}",
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- task_queue=settings.DATA_WAREHOUSE_TASK_QUEUE,
+ task_queue=settings.DATA_WAREHOUSE_METADATA_TASK_QUEUE,
parent_close_policy=ParentClosePolicy.ABANDON,
execution_timeout=dt.timedelta(minutes=30),
)
+ # 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:
+ try:
+ await workflow.start_child_workflow(
+ ComputeTableStatisticsWorkflow.run,
+ ComputeTableStatisticsInputs(
+ team_id=inputs.team_id,
+ schema_id=inputs.external_data_schema_id,
+ ),
+ id=f"compute-warehouse-table-statistics-{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(
+ "Column statistics already running for schema, skipping",
+ extra={"schema_id": str(inputs.external_data_schema_id)},
+ )
+
# Create source templates
await workflow.execute_activity(
create_source_templates,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/settings.py b/products/warehouse_sources/backend/temporal/data_imports/settings.py
index b772ccb2d5e7..e72f36398ae0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/settings.py
@@ -27,21 +27,18 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
check_pipeline_version_activity,
release_v3_pipeline_lock_activity,
)
-from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.enrich_table_semantics import (
- EnrichTableSemanticsWorkflow,
- enrich_table_semantics_activity,
-)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.sync_new_schemas import (
sync_new_schemas_activity,
)
+# NOTE: post-sync table-metadata workflows (semantic enrichment, column statistics) intentionally live on
+# their own worker — see table_metadata_settings.py / DATA_WAREHOUSE_METADATA_TASK_QUEUE — not here.
WORKFLOWS = [
ExternalDataJobWorkflow,
CDPProducerJobWorkflow,
CDCExtractionWorkflow,
CDCSlotCleanupWorkflow,
DiscoverSchemasWorkflow,
- EnrichTableSemanticsWorkflow,
]
ACTIVITIES = [
@@ -60,5 +57,4 @@ ACTIVITIES = [
check_pipeline_version_activity,
acquire_v3_pipeline_lock_activity,
release_v3_pipeline_lock_activity,
- enrich_table_semantics_activity,
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/table_metadata_settings.py b/products/warehouse_sources/backend/temporal/data_imports/table_metadata_settings.py
new file mode 100644
index 000000000000..a79e3cd84941
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/table_metadata_settings.py
@@ -0,0 +1,25 @@
+"""Workflows/activities for the dedicated table-metadata worker.
+
+Post-sync, best-effort enrichment + profiling of synced tables — semantic descriptions and per-column
+statistics. They run on their own worker (DATA_WAREHOUSE_METADATA_TASK_QUEUE) so they can't contend with
+the import pipeline. The import workflow starts them as fire-and-forget children on this queue.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import (
+ ComputeTableStatisticsWorkflow,
+ compute_table_statistics_activity,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.enrich_table_semantics import (
+ EnrichTableSemanticsWorkflow,
+ enrich_table_semantics_activity,
+)
+
+WORKFLOWS = [
+ EnrichTableSemanticsWorkflow,
+ ComputeTableStatisticsWorkflow,
+]
+
+ACTIVITIES = [
+ enrich_table_semantics_activity,
+ compute_table_statistics_activity,
+]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
new file mode 100644
index 000000000000..e1ab450872b6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/compute_table_statistics.py
@@ -0,0 +1,308 @@
+"""Compute per-column data statistics for a synced warehouse table.
+
+Runs as a fire-and-forget child workflow after a sync completes. It gives the AI agent a quantitative
+profile of each column — how null-heavy it is, its value range, and the table's size — so it writes
+better queries (handles/avoids null-heavy columns, bounds filters and time windows correctly).
+
+Stats come from the Delta transaction log's per-file statistics (`num_records`, `null_count`, `min`,
+`max`), aggregated across the snapshot's live files. This reads the *log*, never the data, so it is
+exact, whole-table, correct for full-refresh/append/incremental-upsert (live add-actions reflect the
+current files), and scales to any table size. Results land in `WarehouseColumnStatistics`, fully
+system-owned and overwritten on each run. To avoid re-profiling an hourly-syncing table every hour,
+a row computed within `MIN_RECOMPUTE_INTERVAL` is left alone.
+"""
+
+import os
+import json
+import uuid
+import dataclasses
+from datetime import timedelta
+from typing import TYPE_CHECKING, Any
+
+from django.utils import timezone
+
+import structlog
+import posthoganalytics
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models import Team
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.heartbeat import LivenessHeartbeater as Heartbeater
+
+from products.warehouse_sources.backend.models.column_statistics import WarehouseColumnStatistics
+from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.models.util import clean_type
+
+if TYPE_CHECKING:
+ import pyarrow as pa
+
+logger = structlog.get_logger(__name__)
+
+STATISTICS_FEATURE_FLAG = "data-warehouse-column-statistics"
+# Cap profiling to once a day per table — an hourly-syncing table doesn't need re-profiling every hour,
+# and Delta-log stats only move materially over longer windows. Env-overridable for ops.
+MIN_RECOMPUTE_INTERVAL = timedelta(hours=int(os.getenv("WAREHOUSE_STATS_MIN_RECOMPUTE_INTERVAL_HOURS", "24")))
+
+# Product-analytics events — query these to track statistics volume, columns profiled, skips, and errors.
+EVENT_STARTED = "data warehouse table statistics started"
+EVENT_COMPLETED = "data warehouse table statistics completed"
+EVENT_ERROR = "data warehouse table statistics error"
+
+
[email protected](frozen=True)
+class ComputeTableStatisticsInputs:
+ team_id: int
+ schema_id: uuid.UUID
+
+ @property
+ def properties_to_log(self) -> dict[str, Any]:
+ return {"team_id": self.team_id, "schema_id": str(self.schema_id)}
+
+
+def statistics_enabled(team: Team) -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ STATISTICS_FEATURE_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={
+ "organization": {"id": str(team.organization_id)},
+ "project": {"id": str(team.id)},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ capture_exception(e)
+ return False
+
+
+def capture_statistics_event(team: Team, event: str, properties: dict[str, Any]) -> None:
+ """Best-effort product-analytics capture, attributed to the team's org/project groups.
+
+ Telemetry must never break the activity, so all failures are swallowed (and reported to Sentry).
+ """
+ try:
+ posthoganalytics.capture(
+ distinct_id=str(team.uuid),
+ event=event,
+ properties={**properties, "team_id": team.id},
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ )
+ except Exception as e:
+ capture_exception(e)
+
+
+def _column_type(definition: Any) -> str:
+ """Source-agnostic ClickHouse type string from a `DataWarehouseTable.columns` entry.
+
+ Handles both the dict shape (`{"clickhouse": ...}`) and the legacy plain-string shape.
+ """
+ if isinstance(definition, dict):
+ return definition.get("clickhouse") or definition.get("hogql") or ""
+ return definition or ""
+
+
+class _ColumnStat:
+ column_type: str
+ null_count: int | None
+ min_value: str | None
+ max_value: str | None
+ has_min_max: bool
+
+
+def _aggregate_add_action_stats(add_actions: "pa.Table", columns: dict[str, Any]) -> tuple[int, dict[str, _ColumnStat]]:
+ """Aggregate the Delta log's per-file stats into per-column whole-table stats.
+
+ `add_actions` is `DeltaTable.get_add_actions(flatten=True)` — one row per live file, with
+ `num_records` and (where the log carries stats) `null_count.<col>`, `min.<col>`, `max.<col>`.
+ Returns `(row_count, {column_name: _ColumnStat})`. Columns with no log stats get `has_min_max=False`.
+ """
+ data = add_actions.to_pydict()
+ row_count = sum(n for n in data.get("num_records", []) if n is not None)
+
+ result: dict[str, _ColumnStat] = {}
+ for name, definition in (columns or {}).items():
+ null_key, min_key, max_key = f"null_count.{name}", f"min.{name}", f"max.{name}"
+
+ # `null_count = None` (unknown) when the log carried no per-file null counts — either the key is
+ # absent or every file's value is None. Mirrors the min/max guard below; a real zero stays 0.
+ null_values = [v for v in data.get(null_key, []) if v is not None] if null_key in data else []
+ null_count = sum(null_values) if null_values else None
+
+ mins = [v for v in data.get(min_key, []) if v is not None] if min_key in data else []
+ maxs = [v for v in data.get(max_key, []) if v is not None] if max_key in data else []
+ min_value = str(min(mins)) if mins else None
+ max_value = str(max(maxs)) if maxs else None
+ has_min_max = bool(mins or maxs)
+
+ result[name] = _ColumnStat(
+ column_type=clean_type(_column_type(definition)) or "unknown",
+ null_count=null_count,
+ min_value=min_value,
+ max_value=max_value,
+ has_min_max=has_min_max,
+ )
+ return row_count, result
+
+
+def _most_recent_computed_at(existing: dict[str, WarehouseColumnStatistics]) -> Any | None:
+ times = [s.computed_at for s in existing.values() if s.computed_at is not None]
+ return max(times) if times else None
+
+
+def compute_table_statistics_sync(team_id: int, schema_id: uuid.UUID) -> dict[str, Any]:
+ """Compute and persist per-column statistics for one warehouse table. Safe to re-run."""
+ # Lazy: DeltaTableHelper drags deltalake/pyarrow/dlt — keep them off the flag-check import path that
+ # create_external_data_job_model_activity uses (it only imports statistics_enabled).
+ from asgiref.sync import async_to_sync # noqa: PLC0415
+
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper import ( # noqa: PLC0415
+ DeltaTableHelper,
+ )
+
+ log = logger.bind(team_id=team_id, schema_id=str(schema_id))
+
+ team = Team.objects.select_related("organization").only("id", "uuid", "organization_id").get(id=team_id)
+ event_props: dict[str, Any] = {"schema_id": str(schema_id)}
+
+ def emit_completed(status: str, **props: Any) -> None:
+ capture_statistics_event(team, EVENT_COMPLETED, {"status": status, **event_props, **props})
+
+ if not statistics_enabled(team):
+ emit_completed("skipped", reason="flag_disabled")
+ return {"status": "skipped", "reason": "flag_disabled"}
+
+ schema = (
+ ExternalDataSchema.objects.select_related("source", "table")
+ .filter(team_id=team_id, deleted=False)
+ .get(id=schema_id)
+ )
+ table = schema.table
+ event_props["source_type"] = schema.source.source_type
+ event_props["schema_name"] = schema.name
+ if table is None:
+ emit_completed("skipped", reason="no_table")
+ return {"status": "skipped", "reason": "no_table"}
+ event_props["table_id"] = str(table.id)
+
+ existing = {
+ stat.column_name: stat for stat in WarehouseColumnStatistics.objects.for_team(team_id).filter(table_id=table.id)
+ }
+ latest = _most_recent_computed_at(existing)
+ if latest is not None and timezone.now() - latest < MIN_RECOMPUTE_INTERVAL:
+ emit_completed("skipped", reason="computed_recently")
+ return {"status": "skipped", "reason": "computed_recently"}
+
+ capture_statistics_event(team, EVENT_STARTED, event_props)
+
+ # Locate the committed Delta table. folder_path is schema-derived, so any job for this schema works;
+ # resource_name mirrors what the pipeline used to name the Delta folder.
+ job = ExternalDataJob.objects.filter(team_id=team_id, schema_id=schema_id).order_by("-created_at").first()
+ if job is None:
+ emit_completed("skipped", reason="no_job")
+ return {"status": "skipped", "reason": "no_job"}
+
+ resource_name = schema.resolved_s3_folder_name or schema.name
+ delta_table_helper = DeltaTableHelper(resource_name=resource_name, job=job, logger=log)
+ delta_table = async_to_sync(delta_table_helper.get_delta_table)()
+ if delta_table is None:
+ emit_completed("skipped", reason="no_delta_table")
+ return {"status": "skipped", "reason": "no_delta_table"}
+
+ delta_version = delta_table.version()
+ add_actions = delta_table.get_add_actions(flatten=True)
+ if add_actions.num_rows == 0:
+ emit_completed("skipped", reason="no_files")
+ return {"status": "skipped", "reason": "no_files"}
+
+ columns = table.columns or {}
+ if not columns:
+ emit_completed("skipped", reason="no_columns")
+ return {"status": "skipped", "reason": "no_columns"}
+
+ row_count, stats_by_column = _aggregate_add_action_stats(add_actions, columns)
+
+ for column_name, stat in stats_by_column.items():
+ _upsert_statistics(team, table, column_name, row_count, stat, delta_version)
+
+ log.info("warehouse_statistics.done", columns=len(stats_by_column), row_count=row_count)
+ emit_completed("done", columns=len(stats_by_column), row_count=row_count, delta_version=delta_version)
+ return {"status": "done", "columns": len(stats_by_column), "row_count": row_count}
+
+
+def _upsert_statistics(
+ team: Team,
+ table: DataWarehouseTable,
+ column_name: str,
+ row_count: int,
+ stat: _ColumnStat,
+ delta_version: int,
+) -> None:
+ """Persist (overwrite) one column's stats. Stats are wholly system-owned, so a plain upsert is correct."""
+ null_fraction = (stat.null_count / row_count) if (stat.null_count is not None and row_count > 0) else None
+ WarehouseColumnStatistics.objects.for_team(team.id).update_or_create(
+ table=table,
+ column_name=column_name,
+ defaults={
+ "team": team,
+ "column_type": stat.column_type,
+ "row_count": row_count,
+ "null_count": stat.null_count,
+ "null_fraction": null_fraction,
+ "min_value": stat.min_value,
+ "max_value": stat.max_value,
+ "has_min_max": stat.has_min_max,
+ "computed_at": timezone.now(),
+ "computed_for_delta_version": delta_version,
+ "stats_basis": "delta_log",
+ },
+ )
+
+
+async def compute_table_statistics_activity(inputs: ComputeTableStatisticsInputs) -> dict[str, Any]:
+ """Activity wrapper. Heartbeats and runs the (sync) computation off the event loop."""
+ async with Heartbeater():
+ try:
+ return await database_sync_to_async(compute_table_statistics_sync, thread_sensitive=False)(
+ inputs.team_id, inputs.schema_id
+ )
+ except Exception as e:
+ capture_exception(e)
+ try:
+ posthoganalytics.capture(
+ distinct_id=f"team-{inputs.team_id}",
+ event=EVENT_ERROR,
+ properties={"team_id": inputs.team_id, "schema_id": str(inputs.schema_id), "error": str(e)},
+ groups={"project": str(inputs.team_id)},
+ )
+ except Exception as capture_error:
+ capture_exception(capture_error)
+ raise
+
+
[email protected](name="compute-warehouse-table-statistics")
+class ComputeTableStatisticsWorkflow(PostHogWorkflow):
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ComputeTableStatisticsInputs:
+ loaded = json.loads(inputs[0])
+ return ComputeTableStatisticsInputs(team_id=loaded["team_id"], schema_id=uuid.UUID(loaded["schema_id"]))
+
+ @workflow.run
+ async def run(self, inputs: ComputeTableStatisticsInputs) -> None:
+ await workflow.execute_activity(
+ compute_table_statistics_activity,
+ inputs,
+ start_to_close_timeout=timedelta(minutes=15),
+ heartbeat_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
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.py
index c3e440a80848..6719ada2d71b 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
@@ -101,6 +101,9 @@ class CreateExternalDataJobModelActivityOutputs:
# 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.
enrichment_enabled: bool = False
+ # True when column-statistics profiling should run (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
@activity.defn
@@ -172,6 +175,14 @@ def create_external_data_job_model_activity(
enrichment_should_run = bool(ai_data_processing_approved and team is not None and enrichment_enabled(team))
+ # Column-statistics profiling is gated on its feature flag only (no consent term) — let the
+ # workflow skip the child rather than spawn a no-op. Lazy import keeps deltalake off this path.
+ from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import ( # noqa: PLC0415
+ statistics_enabled,
+ )
+
+ statistics_should_run = bool(team is not None and statistics_enabled(team))
+
return CreateExternalDataJobModelActivityOutputs(
job_id=str(job.id),
incremental_or_append=schema.is_incremental or schema.is_append or schema.is_webhook,
@@ -180,6 +191,7 @@ def create_external_data_job_model_activity(
last_synced_at=schema.last_synced_at.isoformat() if schema.last_synced_at else None,
emit_signals_enabled=emit_signals_enabled,
enrichment_enabled=enrichment_should_run,
+ statistics_enabled=statistics_should_run,
)
except Exception as e:
logger.exception(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
new file mode 100644
index 000000000000..d11ee7f743b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_compute_table_statistics.py
@@ -0,0 +1,285 @@
+import json
+import uuid
+import datetime as dt
+from decimal import Decimal
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.utils import timezone
+
+import pyarrow as pa
+from temporalio.testing import ActivityEnvironment
+
+from posthog.models import Organization, Team
+
+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_job import ExternalDataJob
+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 import (
+ compute_table_statistics as comp,
+)
+from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.compute_table_statistics import (
+ ComputeTableStatisticsInputs,
+ ComputeTableStatisticsWorkflow,
+ _aggregate_add_action_stats,
+ compute_table_statistics_activity,
+ compute_table_statistics_sync,
+)
+
+DELTA_HELPER_PATH = (
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper.DeltaTableHelper"
+)
+
+
+class TestAggregateAddActionStats:
+ def test_sums_records_and_null_counts_and_takes_min_max_across_files(self) -> None:
+ # Two files: row_count is the sum; null_count is the sum; min is the min-of-mins, max the max-of-maxes.
+ add_actions = pa.table(
+ {
+ "num_records": [10, 20],
+ "null_count.amount": [1, 2],
+ "min.amount": [5, 3],
+ "max.amount": [9, 15],
+ }
+ )
+ row_count, stats = _aggregate_add_action_stats(add_actions, {"amount": "Int64"})
+ assert row_count == 30
+ assert stats["amount"].null_count == 3
+ assert stats["amount"].min_value == "3"
+ assert stats["amount"].max_value == "15"
+ assert stats["amount"].has_min_max is True
+
+ def test_column_without_log_stats_marks_has_min_max_false(self) -> None:
+ # A column present in the table but with no min/max/null in the Delta log (e.g. nested type).
+ add_actions = pa.table({"num_records": [5]})
+ _, stats = _aggregate_add_action_stats(add_actions, {"payload": "Tuple(String, Int64)"})
+ assert stats["payload"].has_min_max is False
+ assert stats["payload"].null_count is None
+ assert stats["payload"].min_value is None
+ assert stats["payload"].max_value is None
+
+ def test_ignores_none_entries_in_per_file_stats(self) -> None:
+ # A file with no min (all-null file) contributes None; aggregation must skip it, not crash.
+ add_actions = pa.table(
+ {"num_records": [4, 6], "null_count.x": [None, 2], "min.x": [None, 4], "max.x": [7, None]}
+ )
+ row_count, stats = _aggregate_add_action_stats(add_actions, {"x": "Int64"})
+ assert row_count == 10
+ assert stats["x"].null_count == 2
+ assert stats["x"].min_value == "4"
+ assert stats["x"].max_value == "7"
+
+ def test_null_count_unknown_when_all_per_file_values_are_none(self) -> None:
+ # The log carries the null_count key but every file's value is None (missing stats). That's
+ # "unknown", not "zero nulls" — returning 0 would mislead the agent into "no nulls".
+ add_actions = pa.table({"num_records": [5, 5], "null_count.x": [None, None], "min.x": [1, 2]})
+ _, stats = _aggregate_add_action_stats(add_actions, {"x": "Int64"})
+ assert stats["x"].null_count is None
+
+ def test_real_zero_null_count_is_preserved(self) -> None:
+ add_actions = pa.table({"num_records": [5, 5], "null_count.x": [0, 0]})
+ _, stats = _aggregate_add_action_stats(add_actions, {"x": "Int64"})
+ assert stats["x"].null_count == 0
+
+ @pytest.mark.parametrize(
+ "definition,expected_type",
+ [
+ ({"clickhouse": "Nullable(Int64)"}, "Int64"),
+ ({"clickhouse": "Int64", "hogql": "IntegerDatabaseField"}, "Int64"),
+ ("String", "String"),
+ ({"hogql": "StringDatabaseField"}, "StringDatabaseField"),
+ ],
+ )
+ def test_column_type_extracted_and_cleaned(self, definition: object, expected_type: str) -> None:
+ add_actions = pa.table({"num_records": [1], "min.c": [1], "max.c": [1]})
+ _, stats = _aggregate_add_action_stats(add_actions, {"c": definition})
+ assert stats["c"].column_type == expected_type
+
+ @pytest.mark.parametrize(
+ "min_val,max_val,expected_min,expected_max",
+ [
+ (3, 9, "3", "9"),
+ (Decimal("1.50"), Decimal("9.99"), "1.50", "9.99"),
+ (dt.date(2024, 1, 1), dt.date(2025, 6, 25), "2024-01-01", "2025-06-25"),
+ ],
+ )
+ def test_min_max_coerced_to_string(self, min_val, max_val, expected_min, expected_max) -> None:
+ add_actions = pa.table({"num_records": [1], "min.v": [min_val], "max.v": [max_val]})
+ _, stats = _aggregate_add_action_stats(add_actions, {"v": "X"})
+ assert stats["v"].min_value == expected_min
+ assert stats["v"].max_value == expected_max
+
+
+class TestComputeTableStatisticsSync:
+ def _team(self, *, ai_approved: bool = False) -> Team:
+ org = Organization.objects.create(name="org", is_ai_data_processing_approved=ai_approved)
+ return Team.objects.create(organization=org, name="t")
+
+ def _schema_table_job(self, team: Team, *, columns: dict | None = None):
+ credential = DataWarehouseCredential.objects.create(access_key="k", access_secret="s", team=team)
+ table = 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)"}},
+ )
+ source = ExternalDataSource.objects.create(
+ source_id="src", connection_id="conn", team=team, source_type="Stripe"
+ )
+ schema = ExternalDataSchema.objects.create(name="Charge", team=team, source=source, table=table)
+ job = ExternalDataJob.objects.create(
+ team=team, pipeline=source, schema=schema, status=ExternalDataJob.Status.COMPLETED, rows_synced=0
+ )
+ return schema, table, job
+
+ def _mock_delta(self, add_actions: pa.Table, version: int = 7):
+ delta_table = MagicMock()
+ delta_table.version.return_value = version
+ delta_table.get_add_actions.return_value = add_actions
+ helper = MagicMock()
+ helper.get_delta_table = AsyncMock(return_value=delta_table)
+ return helper
+
+ def test_skipped_when_flag_disabled(self) -> None:
+ team = self._team()
+ self._schema_table_job(team)
+ schema = ExternalDataSchema.objects.get(team=team)
+ with patch.object(comp, "statistics_enabled", return_value=False):
+ result = compute_table_statistics_sync(team.id, schema.id)
+ assert result == {"status": "skipped", "reason": "flag_disabled"}
+ assert WarehouseColumnStatistics.objects.for_team(team.id).count() == 0
+
+ def test_persists_per_column_statistics(self) -> None:
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ add_actions = pa.table(
+ {"num_records": [10, 30], "null_count.amount": [1, 3], "min.amount": [5, 2], "max.amount": [9, 50]}
+ )
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions, version=12)),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result["status"] == "done"
+ stat = WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount")
+ assert stat.row_count == 40
+ assert stat.null_count == 4
+ assert stat.null_fraction == 0.1
+ assert stat.min_value == "2"
+ assert stat.max_value == "50"
+ assert stat.has_min_max is True
+ assert stat.computed_for_delta_version == 12
+ assert stat.column_type == "Int64"
+
+ def test_runs_without_ai_data_processing_consent(self) -> None:
+ # Statistics never leave our infra, so — unlike enrichment — they must NOT be gated on AI consent.
+ # Guards against someone copy-pasting enrichment's consent gate into this path.
+ team = self._team(ai_approved=False)
+ schema, table, _ = self._schema_table_job(team)
+ add_actions = pa.table({"num_records": [1], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions)),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+ assert result["status"] == "done"
+ assert WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id).exists()
+
+ def test_recompute_overwrites_existing_row(self) -> None:
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team,
+ table=table,
+ column_name="amount",
+ row_count=1,
+ computed_at=timezone.now() - dt.timedelta(days=2),
+ computed_for_delta_version=1,
+ )
+ add_actions = pa.table({"num_records": [99], "null_count.amount": [0], "min.amount": [1], "max.amount": [1]})
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(add_actions, version=5)),
+ ):
+ compute_table_statistics_sync(team.id, schema.id)
+
+ rows = WarehouseColumnStatistics.objects.for_team(team.id).filter(table_id=table.id, column_name="amount")
+ assert rows.count() == 1 # overwritten, not duplicated
+ row = rows.get()
+ assert row.row_count == 99
+ assert row.computed_for_delta_version == 5
+
+ def test_skipped_when_computed_recently(self) -> None:
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ WarehouseColumnStatistics.objects.for_team(team.id).create(
+ team=team, table=table, column_name="amount", row_count=7, computed_at=timezone.now()
+ )
+ helper = self._mock_delta(pa.table({"num_records": [1]}))
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=helper) as mock_helper,
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+
+ assert result == {"status": "skipped", "reason": "computed_recently"}
+ mock_helper.assert_not_called() # didn't even open the Delta table
+ assert (
+ WarehouseColumnStatistics.objects.for_team(team.id).get(table_id=table.id, column_name="amount").row_count
+ == 7
+ )
+
+ def test_skipped_when_no_table(self) -> None:
+ team = self._team()
+ source = ExternalDataSource.objects.create(
+ source_id="src", connection_id="conn", team=team, source_type="Stripe"
+ )
+ schema = ExternalDataSchema.objects.create(name="Charge", team=team, source=source, table=None)
+ with patch.object(comp, "statistics_enabled", return_value=True):
+ result = compute_table_statistics_sync(team.id, schema.id)
+ assert result == {"status": "skipped", "reason": "no_table"}
+
+ def test_skipped_when_no_files(self) -> None:
+ team = self._team()
+ schema, table, _ = self._schema_table_job(team)
+ empty = pa.table({"num_records": pa.array([], type=pa.int64())})
+ with (
+ patch.object(comp, "statistics_enabled", return_value=True),
+ patch(DELTA_HELPER_PATH, return_value=self._mock_delta(empty)),
+ ):
+ result = compute_table_statistics_sync(team.id, schema.id)
+ assert result == {"status": "skipped", "reason": "no_files"}
+
+
[email protected]_db(transaction=True)
+class TestComputeTableStatisticsActivity:
+ async def test_activity_returns_sync_result(self) -> None:
+ with patch.object(
+ comp, "compute_table_statistics_sync", return_value={"status": "done", "columns": 1, "row_count": 5}
+ ) as mock_sync:
+ inputs = ComputeTableStatisticsInputs(team_id=1, schema_id=uuid.uuid4())
+ result = await ActivityEnvironment().run(compute_table_statistics_activity, inputs)
+ assert result == {"status": "done", "columns": 1, "row_count": 5}
+ mock_sync.assert_called_once()
+
+ async def test_activity_reraises_on_failure(self) -> None:
+ with patch.object(comp, "compute_table_statistics_sync", side_effect=ValueError("boom")):
+ inputs = ComputeTableStatisticsInputs(team_id=1, schema_id=uuid.uuid4())
+ with pytest.raises(ValueError, match="boom"):
+ await ActivityEnvironment().run(compute_table_statistics_activity, inputs)
+
+
+class TestComputeTableStatisticsWorkflow:
+ def test_parse_inputs_round_trips_json(self) -> None:
+ schema_id = uuid.uuid4()
+ parsed = ComputeTableStatisticsWorkflow.parse_inputs([json.dumps({"team_id": 42, "schema_id": str(schema_id)})])
+ assert parsed.team_id == 42
+ assert parsed.schema_id == schema_id
diff --git a/pyproject.toml b/pyproject.toml
index d4050177618c..f38c863abac4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -577,6 +577,8 @@ ignore_imports = [
# (warehouse_sources, data_modeling, data_tools, cdp, revenue_analytics, batch_exports)
# directly. Thin each viewset to parse -> facade -> serialize and delete each entry.
# backend:contract-check stays off until this list is empty.
+ "products.data_warehouse.backend.presentation.views.column_statistics -> products.warehouse_sources.backend.models.column_statistics",
+ "products.data_warehouse.backend.presentation.views.column_statistics -> products.warehouse_sources.backend.models.table",
"products.data_warehouse.backend.presentation.views.data_modeling_job -> products.data_modeling.backend.models.data_modeling_job",
"products.data_warehouse.backend.presentation.views.data_warehouse -> products.batch_exports.backend.models.batch_export",
"products.data_warehouse.backend.presentation.views.data_warehouse -> products.cdp.backend.models.hog_functions.hog_function",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f71327dd6407..ef7d78a08b81 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35127,6 +35127,46 @@ export namespace Schemas {
results: WarehouseColumnAnnotation[];
}
+ export interface WarehouseColumnStatistics {
+ readonly id: string;
+ /** ID of the data warehouse table this column belongs to. */
+ readonly table: string;
+ /** Name of the column these statistics describe. */
+ readonly column_name: string;
+ /** ClickHouse type the statistics were computed against (e.g. Int64, DateTime64). */
+ readonly column_type: string;
+ /** Total number of rows in the table when these statistics were computed. */
+ readonly row_count: number;
+ /** Number of NULL values in this column, or null if the Delta log carried no count. */
+ readonly null_count: number;
+ /** Fraction of values that are NULL (null_count / row_count), between 0 and 1. */
+ readonly null_fraction: number;
+ /** Minimum value in the column, as a string. Null when unavailable. For string columns this may be truncated by the underlying Delta statistics, so treat string bounds as approximate. */
+ readonly min_value: string;
+ /** Maximum value in the column, as a string. Null when unavailable (see min_value). */
+ readonly max_value: string;
+ /** Whether the Delta log carried min/max statistics for this column (false for some nested/binary types). */
+ readonly has_min_max: boolean;
+ /** When these statistics were last computed. */
+ readonly computed_at: string;
+ /** Delta table version the statistics were computed against. */
+ readonly computed_for_delta_version: number;
+ /** How the statistics were produced. Currently always 'delta_log'. */
+ readonly stats_basis: string;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ }
+
+ export interface PaginatedWarehouseColumnStatisticsList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: WarehouseColumnStatistics[];
+ }
+
export interface WebAnalyticsFilterPreset {
readonly id: string;
readonly short_id: string;
@@ -66057,6 +66097,21 @@ export namespace Schemas {
table_id?: string;
};
+ export type WarehouseColumnStatisticsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Only return statistics for this data warehouse table.
+ */
+ table_id?: string;
+ };
+
export type WarehouseModelPathsListParams = {
/**
* Number of results to return per page.