: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
refactor(warehouse): stop core reading the column-statistics model (#83035)
Julian Bez6a2ebca50c80
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.pyindex 2e75ca93e80a..3edb2e16bc08 100644--- a/posthog/hogql/database/schema/information_schema.py+++ b/posthog/hogql/database/schema/information_schema.py@@ -231,10 +231,8 @@ def _warehouse_metadata(team_id: Optional[int]) -> _WarehouseMetadata:from posthog.models.scoping import team_scope # noqa: PLC0415from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery # noqa: PLC0415- from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415- DataWarehouseTable,- WarehouseColumnStatistics,- )+ from products.warehouse_sources.backend.facade.api import list_column_statistics # noqa: PLC0415+ from products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415try:with team_scope(team_id):@@ -261,16 +259,12 @@ def _warehouse_metadata(team_id: Optional[int]) -> _WarehouseMetadata:materialized_view_ids[view_name] = str(view_id)# Per-column profiling stats (keyed by table UUID + column). Only the columns that have been# profiled appear; everything else stays absent (NULL in the catalog).- for (- table_id,- column_name,- null_fraction,- min_value,- max_value,- ) in WarehouseColumnStatistics.objects.values_list(- "table_id", "column_name", "null_fraction", "min_value", "max_value"- ):- column_stats[(str(table_id), column_name)] = (null_fraction, min_value, max_value)+ for stats in list_column_statistics(team_id):+ column_stats[(str(stats.table_id), stats.column_name)] = (+ stats.null_fraction,+ stats.min_value,+ stats.max_value,+ )except Exception:# Schema discovery must never fail a query because the warehouse metadata could not be read,# but log so a transient DB error can be told apart from a real bug in the fetch loop.diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.pyindex 81741dedf376..79b05039f5f2 100644--- a/posthog/hogql/database/schema/test/test_information_schema.py+++ b/posthog/hogql/database/schema/test/test_information_schema.py@@ -1,5 +1,7 @@from posthog.test.base import APIBaseTest, ClickhouseTestMixin+from django.apps import apps+from parameterized import parameterizedfrom posthog.hogql import ast@@ -27,7 +29,6 @@ from products.warehouse_sources.backend.facade.models import (ExternalDataSchema,ExternalDataSource,WarehouseColumnAnnotation,- WarehouseColumnStatistics,)from products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -424,8 +425,11 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):"amount": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True},},)+ # Fetched at runtime: the model no longer crosses the facade, and this test only needs a row+ # in place so the merge path has something to read.+ column_statistics_model = apps.get_model("warehouse_sources", "WarehouseColumnStatistics")with team_scope(self.team.id, canonical=True):- WarehouseColumnStatistics.objects.create(+ column_statistics_model.objects.create(team=self.team,table=table,column_name="id",diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.pyindex e9e380a7e0b8..9ab5fca2f768 100644--- a/products/data_warehouse/backend/routes.py+++ b/products/data_warehouse/backend/routes.py@@ -3,7 +3,6 @@ from posthog.api.routing import RouterRegistryimport products.data_warehouse.backend.presentation.views.fix_hogql as fix_hogqlfrom products.data_warehouse.backend.presentation.views import (column_annotation,- column_statistics,data_modeling_job,data_warehouse,expression,@@ -84,9 +83,3 @@ def register_routes(routers: RouterRegistry) -> None:"project_saved_query_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/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 6b6649bba4b4..ea66d698bc5a 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -959,46 +959,6 @@ 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@@ -4958,21 +4918,6 @@ 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 WarehouseExpressionsListParams = {/*** Number of results to return per page.diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.tsindex 3ce312070e22..166a9841d448 100644--- a/products/data_warehouse/frontend/generated/api.ts+++ b/products/data_warehouse/frontend/generated/api.ts@@ -49,7 +49,6 @@ import type {PaginatedTableListApi,PaginatedViewLinkListApi,PaginatedWarehouseColumnAnnotationListApi,- PaginatedWarehouseColumnStatisticsListApi,PatchedDataWarehouseExpressionApi,PatchedDataWarehouseSavedQueryApi,PatchedDataWarehouseSavedQueryColumnAnnotationApi,@@ -75,8 +74,6 @@ import type {ViewLinkValidationResponseApi,WarehouseColumnAnnotationApi,WarehouseColumnAnnotationsListParams,- WarehouseColumnStatisticsApi,- WarehouseColumnStatisticsListParams,WarehouseExpressionsListParams,WarehouseModelPathsListParams,WarehouseSavedQueriesListParams,@@ -1290,68 +1287,6 @@ 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.yamlindex 31736bfe5296..38e741ccf2c0 100644--- a/products/data_warehouse/mcp/tools.yaml+++ b/products/data_warehouse/mcp/tools.yaml@@ -489,12 +489,6 @@ tools:warehouse-column-annotations-update:operation: warehouse_column_annotations_updateenabled: false- warehouse-column-statistics-list:- operation: warehouse_column_statistics_list- enabled: false- warehouse-column-statistics-retrieve:- operation: warehouse_column_statistics_retrieve- enabled: falsewarehouse-dag-list:operation: warehouse_dag_listenabled: falsediff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex 027dec55a585..823fd526537a 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -29,6 +29,9 @@ from products.warehouse_sources.backend.file_uploads import (build_file_upload_url_pattern,hosted_upload_s3_path,)+from products.warehouse_sources.backend.models.column_statistics import (+ WarehouseColumnStatistics as _WarehouseColumnStatistics,+)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob as _ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema as _ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource as _ExternalDataSource@@ -59,6 +62,7 @@ __all__ = ["get_queryable_table","list_tables_for_source","list_jobs_for_source",+ "list_column_statistics",# framework-free helper transforms"clickhouse_columns_to_dwh_columns","motherduck_columns_to_dwh_columns",@@ -234,3 +238,20 @@ def list_jobs_for_source(source_id: UUID, team_id: int) -> list[contracts.Extern.order_by("-created_at"))return [_to_job(j) for j in qs]+++def list_column_statistics(team_id: int) -> list[contracts.ColumnStatistics]:+ """Every column profile for a team, for describing warehouse tables in a query schema."""+ qs = _WarehouseColumnStatistics.objects.for_team(team_id).values_list(+ "table_id", "column_name", "null_fraction", "min_value", "max_value"+ )+ return [+ contracts.ColumnStatistics(+ table_id=table_id,+ column_name=column_name,+ null_fraction=null_fraction,+ min_value=min_value,+ max_value=max_value,+ )+ for table_id, column_name, null_fraction, min_value, max_value in qs+ ]diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.pyindex 86ec8ee15942..7eb3b5e88cc8 100644--- a/products/warehouse_sources/backend/facade/contracts.py+++ b/products/warehouse_sources/backend/facade/contracts.py@@ -140,6 +140,24 @@ class WarehouseColumnAnnotation:updated_at: datetime+# --- Column statistics ---+++@dataclass(frozen=True)+class ColumnStatistics:+ """The per-column data profile core reads when describing a warehouse table.++ Narrower than the model on purpose: this carries only what schema description consumes.+ Row counts, provenance and the Delta version stay product-side.+ """++ table_id: UUID+ column_name: str+ null_fraction: float | None+ min_value: str | None+ max_value: str | None++# --- Credential (read-only metadata; secrets are never exposed) ---diff --git a/products/data_warehouse/backend/presentation/views/column_statistics.py b/products/warehouse_sources/backend/presentation/views/column_statistics.pysimilarity index 100%rename from products/data_warehouse/backend/presentation/views/column_statistics.pyrename to products/warehouse_sources/backend/presentation/views/column_statistics.pydiff --git a/products/warehouse_sources/backend/routes.py b/products/warehouse_sources/backend/routes.pyindex 0627539749a3..5176c62654ad 100644--- a/products/warehouse_sources/backend/routes.py+++ b/products/warehouse_sources/backend/routes.py@@ -1,6 +1,10 @@from posthog.api.routing import RouterRegistry-from products.warehouse_sources.backend.presentation.views import external_data_schema, external_data_source+from products.warehouse_sources.backend.presentation.views import (+ column_statistics,+ external_data_schema,+ external_data_source,+)def register_routes(routers: RouterRegistry) -> None:@@ -16,3 +20,9 @@ def register_routes(routers: RouterRegistry) -> None:"project_external_data_schemas",["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/warehouse_sources/backend/tests/api/test_column_statistics.pysimilarity index 100%rename from products/data_warehouse/backend/tests/api/test_column_statistics.pyrename to products/warehouse_sources/backend/tests/api/test_column_statistics.pydiff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 498c49705a55..6196892534e6 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -12730,6 +12730,46 @@ export interface SourceCredentialApi {expires_at: string}+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[]+}+export type ExternalDataSchemasListParams = {/*** Number of results to return per page.@@ -12864,3 +12904,18 @@ export type ExternalDataSourcesWizardRetrieveParams = {*/source_type?: 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+}diff --git a/products/warehouse_sources/frontend/generated/api.ts b/products/warehouse_sources/frontend/generated/api.tsindex 5f836a5da696..f775019f24ef 100644--- a/products/warehouse_sources/frontend/generated/api.ts+++ b/products/warehouse_sources/frontend/generated/api.ts@@ -32,6 +32,7 @@ import type {IntegrationAccountsResponseApi,PaginatedExternalDataSchemaListApi,PaginatedExternalDataSourceSerializersListApi,+ PaginatedWarehouseColumnStatisticsListApi,PatchedExternalDataSchemaApi,PatchedExternalDataSourceBulkUpdateSchemasApi,PatchedExternalDataSourceSerializersApi,@@ -42,6 +43,8 @@ import type {SourcePreviewResponseApi,SourceSetupApi,SourceSetupResponseApi,+ WarehouseColumnStatisticsApi,+ WarehouseColumnStatisticsListParams,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -1148,3 +1151,65 @@ export const externalDataSourcesWizardRetrieve = async (method: 'GET',})}++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',+ })+}diff --git a/products/warehouse_sources/mcp/tools.yaml b/products/warehouse_sources/mcp/tools.yamlindex 57fef63f534f..0767bde54bdf 100644--- a/products/warehouse_sources/mcp/tools.yaml+++ b/products/warehouse_sources/mcp/tools.yaml@@ -583,3 +583,9 @@ tools:- '*.unreleasedSource'- '*.fields'selectable: true+ warehouse-column-statistics-list:+ operation: warehouse_column_statistics_list+ enabled: false+ warehouse-column-statistics-retrieve:+ operation: warehouse_column_statistics_retrieve+ enabled: false