:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(insights): add data warehouse support to box plot insights (#72229)
Thomas Obermüller1b81ec125593
diff --git a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsxindex a84c93fee3c4..f192796396c8 100644--- a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx+++ b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx@@ -62,9 +62,7 @@ export function TrendsSeries(): JSX.Element | null {? MathAvailability.BoxPlotOnly: MathAvailability.Allconst supportsDataWarehouse =- (isTrends && display !== ChartDisplayType.CalendarHeatmap && display !== ChartDisplayType.BoxPlot) ||- isLifecycle ||- isStickiness+ (isTrends && display !== ChartDisplayType.CalendarHeatmap) || isLifecycle || isStickinessconst showFormulaOption =isTrends && display !== ChartDisplayType.CalendarHeatmap && display !== ChartDisplayType.BoxPlotdiff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsxindex a15ece5c96f3..9ba143e5f1f6 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx@@ -7,6 +7,7 @@ import userEvent from '@testing-library/user-event'import { Provider } from 'kea'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { useAvailableFeatures } from '~/mocks/features'@@ -292,6 +293,71 @@ describe('ActionFilterRow', () => {expect(screen.queryByTestId('math-selector-0')).not.toBeInTheDocument()expect(screen.getByTestId('box-plot-property-select')).toBeInTheDocument()})++ it('offers only numeric warehouse columns in the box plot property selector for data warehouse series', async () => {+ databaseTableListLogic.mount()+ databaseTableListLogic.actions.loadDatabaseSuccess({+ tables: {+ events_table: {+ type: 'data_warehouse',+ id: 'wh-table-1',+ name: 'events_table',+ fields: {+ duration: {+ name: 'duration',+ hogql_value: 'duration',+ type: 'float',+ schema_valid: true,+ },+ customer_name: {+ name: 'customer_name',+ hogql_value: 'customer_name',+ type: 'string',+ schema_valid: true,+ },+ },+ },+ },+ joins: [],+ } as any)++ const dataWarehouseFilter = {+ id: 'events_table',+ name: 'events_table',+ type: EntityTypes.DATA_WAREHOUSE,+ table_name: 'events_table',+ order: 0,+ }+ const { logic, setFilters } = setup({+ events: [],+ actions: [],+ data_warehouse: [dataWarehouseFilter],+ } as Partial<FilterType>)+ renderRow(logic, {+ mathAvailability: MathAvailability.BoxPlotOnly,+ filter: { ...DEFAULT_FILTER, ...dataWarehouseFilter },+ })++ await userEvent.click(screen.getByTestId('box-plot-property-select'))+ await screen.findByText('duration')+ // The box plot runner applies toFloat() to the selected column, so non-numeric+ // columns must not be offered+ expect(screen.queryByText('customer_name')).not.toBeInTheDocument()+ await userEvent.click(screen.getByText('duration'))++ await waitFor(() => {+ expect(setFilters).toHaveBeenCalledWith(+ expect.objectContaining({+ data_warehouse: [+ expect.objectContaining({+ math_property: 'duration',+ math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,+ }),+ ],+ })+ )+ })+ })})describe('property filters', () => {diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsxindex 395a20d1df60..9864baa6ddd1 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx@@ -33,7 +33,7 @@ import { teamLogic } from 'scenes/teamLogic'import { MathCategory, mathTypeToApiValues, mathsLogic } from 'scenes/trends/mathsLogic'import { actionsModel } from '~/models/actionsModel'-import { NodeKind } from '~/queries/schema/schema-general'+import { DatabaseSerializedFieldType, NodeKind } from '~/queries/schema/schema-general'import {AnyPropertyFilter,BaseMathType,@@ -46,7 +46,6 @@ import {import { ActionFilterRowMenu } from './ActionFilterRowMenu'import { getValue, taxonomicFilterGroupTypeToEntityType } from './actionFilterRowUtils'-import { BoxPlotPropertySelector } from './BoxPlotPropertySelector'import { HogQLMathEditorDropdown } from './HogQLMathEditor'import { MathSelector } from './MathSelector'import { getDefaultMathHogQLExpression } from './mathUtils'@@ -71,6 +70,10 @@ const DragHandle = ({ listeners }: DragHandleProps): JSX.Element => (</span>)+// The taxonomic filter's showNumericalPropsOnly flag doesn't filter warehouse schema columns,+// so numeric-only pickers must not be fed non-numeric columns in the first place.+const NUMERIC_SCHEMA_FIELD_TYPES: DatabaseSerializedFieldType[] = ['integer', 'float', 'decimal']+export function ActionFilterRow({logic,filter,@@ -137,6 +140,8 @@ export function ActionFilterRow({const query = mountedInsightDataLogic?.values?.queryconst isFunnelContext = mathAvailability === MathAvailability.FunnelsOnly+ // Box plot has no math aggregation to pick — the property selector stands alone in place of the math selector.+ const isBoxPlotContext = mathAvailability === MathAvailability.BoxPlotOnlyconst isTrendsContext = trendsDisplayCategory != nullconst suggestedFiltersLabel = isFunnelContext ? 'Suggested step' : isTrendsContext ? 'Suggested series' : undefined@@ -560,7 +565,7 @@ export function ActionFilterRow({{mathAvailability !== MathAvailability.None &&mathAvailability !== MathAvailability.FunnelsOnly && (<>- {mathAvailability !== MathAvailability.BoxPlotOnly && (+ {!isBoxPlotContext && (<div className="@min-[0px]/editor-panel:shrink @min-[0px]/editor-panel:min-w-28 @min-[0px]/editor-panel:overflow-hidden"><MathSelectormath={math}@@ -578,50 +583,53 @@ export function ActionFilterRow({/></div>)}- {mathAvailability === MathAvailability.BoxPlotOnly && (- <BoxPlotPropertySelector- mathPropertyType={mathPropertyType}+ {(isBoxPlotContext ||+ mathDefinitions[math || BaseMathType.TotalCount]?.category ===+ MathCategory.PropertyValue) && (+ <PropertyValueMathSelector+ mathPropertyType={+ // For warehouse series, don't trust mathPropertyType — a swap from an+ // event series can leave a stale non-warehouse group on the filter.+ isDataWarehouseFilter+ ? TaxonomicFilterGroupType.DataWarehouseProperties+ : mathPropertyType ||+ TaxonomicFilterGroupType.NumericalEventProperties+ }+ mathPropertyTypes={+ isDataWarehouseFilter+ ? [TaxonomicFilterGroupType.DataWarehouseProperties]+ : [+ TaxonomicFilterGroupType.NumericalEventProperties,+ TaxonomicFilterGroupType.SessionProperties,+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.DataWarehousePersonProperties,+ ]+ }mathProperty={mathProperty}+ mathName={name}index={index}onMathPropertySelect={onMathPropertySelect}- mathName={name}+ showNumericalPropsOnly={isBoxPlotContext || showNumericalPropsOnly}+ schemaColumns={+ isDataWarehouseFilter && filter.name+ ? Object.values(+ dataWarehouseTablesMap[filter.name]?.fields ?? []+ ).filter(+ (field) =>+ !(isBoxPlotContext || showNumericalPropsOnly) ||+ NUMERIC_SCHEMA_FIELD_TYPES.includes(field.type)+ )+ : []+ }+ mathDisplayName={+ isBoxPlotContext+ ? undefined+ : mathDefinitions[math ?? '']?.name.toLowerCase()+ }+ placeholder={isBoxPlotContext ? 'Select numeric property' : undefined}+ dataAttr={isBoxPlotContext ? 'box-plot-property-select' : undefined}/>)}- {mathAvailability !== MathAvailability.BoxPlotOnly &&- mathDefinitions[math || BaseMathType.TotalCount]?.category ===- MathCategory.PropertyValue && (- <PropertyValueMathSelector- mathPropertyType={- mathPropertyType ||- (isDataWarehouseFilter- ? TaxonomicFilterGroupType.DataWarehouseProperties- : TaxonomicFilterGroupType.NumericalEventProperties)- }- mathPropertyTypes={- isDataWarehouseFilter- ? [TaxonomicFilterGroupType.DataWarehouseProperties]- : [- TaxonomicFilterGroupType.NumericalEventProperties,- TaxonomicFilterGroupType.SessionProperties,- TaxonomicFilterGroupType.PersonProperties,- TaxonomicFilterGroupType.DataWarehousePersonProperties,- ]- }- mathProperty={mathProperty}- mathName={name}- index={index}- onMathPropertySelect={onMathPropertySelect}- showNumericalPropsOnly={showNumericalPropsOnly}- schemaColumns={- isDataWarehouseFilter && filter.name- ? Object.values(- dataWarehouseTablesMap[filter.name]?.fields ?? []- )- : []- }- mathDisplayName={mathDefinitions[math ?? '']?.name.toLowerCase()}- />- )}{mathDefinitions[math || BaseMathType.TotalCount]?.category ===MathCategory.HogQLExpression && (<HogQLMathEditorDropdowndiff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/BoxPlotPropertySelector.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/BoxPlotPropertySelector.tsxdeleted file mode 100644index 684f1895153f..000000000000--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/BoxPlotPropertySelector.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'--interface BoxPlotPropertySelectorProps {- /** The currently selected taxonomic group for the box plot property, e.g. session or person properties. */- mathPropertyType: TaxonomicFilterGroupType | null | undefined- /** The currently selected numeric property key for the box plot calculation. */- mathProperty: string | null | undefined- /** The row index used when reporting selection changes back to the parent filter list. */- index: number- /** Called when the user selects a property and its taxonomic group. */- onMathPropertySelect: (index: number, value: string, groupType: TaxonomicFilterGroupType) => void- /** The event or action name used to scope property suggestions shown in the picker. */- mathName: string | null | undefined-}--export function BoxPlotPropertySelector({- mathPropertyType,- mathProperty,- index,- onMathPropertySelect,- mathName,-}: BoxPlotPropertySelectorProps): JSX.Element {- return (- <div className="flex-auto min-w-0">- <TaxonomicStringPopover- groupType={mathPropertyType || TaxonomicFilterGroupType.NumericalEventProperties}- groupTypes={[- TaxonomicFilterGroupType.NumericalEventProperties,- TaxonomicFilterGroupType.SessionProperties,- TaxonomicFilterGroupType.PersonProperties,- ]}- value={mathProperty || undefined}- onChange={(currentValue, groupType) => onMathPropertySelect(index, currentValue, groupType)}- eventNames={mathName ? [mathName] : []}- placeholder="Select numeric property"- data-attr="box-plot-property-select"- showNumericalPropsOnly- selectingKeyOnly- renderValue={(currentValue) => (- <PropertyKeyInfo- value={currentValue}- disablePopover- type={TaxonomicFilterGroupType.EventProperties}- />- )}- />- </div>- )-}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/PropertyValueMathSelector.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/PropertyValueMathSelector.tsxindex 65e9f6dd16b2..7d85e7361336 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/PropertyValueMathSelector.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/PropertyValueMathSelector.tsx@@ -21,8 +21,12 @@ interface PropertyValueMathSelectorProps {showNumericalPropsOnly?: boolean/** Available schema fields for data warehouse property suggestions when the picker is scoped to a table. */schemaColumns: DatabaseSchemaField[]- /** Display name of the math aggregation, e.g. "average" */+ /** Display name of the math aggregation, e.g. "average". When omitted (e.g. box plot, which has no+ * math aggregation), the selected value renders without the explanatory tooltip. */mathDisplayName?: string+ /** Shown when no property is selected yet, for contexts where the picker stands alone (e.g. box plot). */+ placeholder?: string+ dataAttr?: string}export function PropertyValueMathSelector({@@ -35,6 +39,8 @@ export function PropertyValueMathSelector({showNumericalPropsOnly,schemaColumns,mathDisplayName,+ placeholder,+ dataAttr = 'math-property-select',}: PropertyValueMathSelectorProps): JSX.Element {return (<div className="flex-auto min-w-0">@@ -53,36 +59,45 @@ export function PropertyValueMathSelector({value={mathProperty}onChange={(currentValue, groupType) => onMathPropertySelect(index, currentValue, groupType)}eventNames={mathName ? [mathName] : []}- data-attr="math-property-select"+ placeholder={placeholder}+ data-attr={dataAttr}showNumericalPropsOnly={showNumericalPropsOnly}selectingKeyOnly- renderValue={(currentValue) => (- <Tooltip- title={- currentValue === '$session_duration' ? (- <>- Calculate {mathDisplayName} of the session duration. This is based on the{' '}- <code>$session_id</code> property associated with events. The duration is derived- from the time difference between the first and last event for each distinct{' '}- <code>$session_id</code>.- </>- ) : (- <>- Calculate {mathDisplayName} from property <code>{currentValue}</code>. Note that- only {mathName} occurrences where <code>{currentValue}</code> is set with a numeric- value will be taken into account.- </>- )- }- placement="right"- >+ renderValue={(currentValue) => {+ const propertyKeyInfo = (<PropertyKeyInfovalue={currentValue}disablePopovertype={TaxonomicFilterGroupType.EventProperties}/>- </Tooltip>- )}+ )+ if (!mathDisplayName) {+ return propertyKeyInfo+ }+ return (+ <Tooltip+ title={+ currentValue === '$session_duration' ? (+ <>+ Calculate {mathDisplayName} of the session duration. This is based on the{' '}+ <code>$session_id</code> property associated with events. The duration is+ derived from the time difference between the first and last event for each+ distinct <code>$session_id</code>.+ </>+ ) : (+ <>+ Calculate {mathDisplayName} from property <code>{currentValue}</code>. Note that+ only {mathName} occurrences where <code>{currentValue}</code> is set with a+ numeric value will be taken into account.+ </>+ )+ }+ placement="right"+ >+ {propertyKeyInfo}+ </Tooltip>+ )+ }}/></div>)diff --git a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambrindex 95dab6eb5ffe..711b678864a4 100644--- a/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr+++ b/posthog/hogql_queries/insights/trends/test/__snapshots__/test_boxplot_trends_query_runner.ambr@@ -1621,3 +1621,31 @@use_hive_partitioning=0'''# ---+# name: TestBoxPlotTrendsQueryRunnerDataWarehouse.test_data_warehouse_series_returns_distribution+ '''+ SELECT toStartOfDay(toTimeZone(e.created, 'UTC')) AS day_start,+ min(accurateCastOrNull(e.revenue, 'Float64')) AS min_val,+ quantile(0.25)(accurateCastOrNull(e.revenue, 'Float64')) AS p25,+ quantile(0.5)(accurateCastOrNull(e.revenue, 'Float64')) AS median_val,+ quantile(0.75)(accurateCastOrNull(e.revenue, 'Float64')) AS p75,+ max(accurateCastOrNull(e.revenue, 'Float64')) AS max_val,+ avg(accurateCastOrNull(e.revenue, 'Float64')) AS mean_val+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql.datawarehouse.boxplot/posthog_test_boxplot_table/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `created` DateTime64(3, \'UTC\'), `revenue` Float64') AS e+ WHERE and(greaterOrEquals(toTimeZone(e.created, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2023-12-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(toTimeZone(e.created, 'UTC'), assumeNotNull(toDateTime('2023-12-03 23:59:59', 'UTC'))))+ GROUP BY day_start+ ORDER BY day_start ASC+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,+ readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ optimize_rewrite_aggregate_function_with_if=0,+ optimize_min_inequality_conjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/posthog/hogql_queries/insights/trends/test/data/boxplot_data.csv b/posthog/hogql_queries/insights/trends/test/data/boxplot_data.csvnew file mode 100644index 000000000000..f645a2bd0535--- /dev/null+++ b/posthog/hogql_queries/insights/trends/test/data/boxplot_data.csv@@ -0,0 +1,6 @@+id,created,revenue+1,2023-12-02 10:00:00,10+2,2023-12-02 11:00:00,20+3,2023-12-02 12:00:00,30+4,2023-12-02 13:00:00,40+5,2023-12-02 14:00:00,50diff --git a/posthog/hogql_queries/insights/trends/test/test_boxplot_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_boxplot_trends_query_runner.pyindex 1ebee657b381..7047d6128a47 100644--- a/posthog/hogql_queries/insights/trends/test/test_boxplot_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/test/test_boxplot_trends_query_runner.py@@ -1,3 +1,4 @@+from pathlib import Pathfrom typing import Optionalimport pytest@@ -12,11 +13,23 @@ from posthog.test.base import (from parameterized import parameterized-from posthog.schema import BoxPlotDatum, ChartDisplayType, DateRange, EventsNode, TrendsFilter, TrendsQuery+from posthog.schema import (+ BoxPlotDatum,+ ChartDisplayType,+ DataWarehouseNode,+ DateRange,+ EventsNode,+ TrendsFilter,+ TrendsQuery,+)from posthog.hogql_queries.insights.trends.boxplot_trends_query_runner import BoxPlotTrendsQueryRunnerfrom posthog.models.utils import uuid7+from products.warehouse_sources.backend.facade.testing import create_data_warehouse_table_from_csv++TEST_BUCKET = "test_storage_bucket-posthog.hogql.datawarehouse.boxplot"+@freeze_time("2024-01-01T00:00:00Z")class TestBoxPlotTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):@@ -515,3 +528,81 @@ class TestBoxPlotTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert datum.min > 0assert datum.max > 0assert datum.min <= datum.p25 <= datum.median <= datum.p75 <= datum.max+++# S3-backed table creation must happen with the real clock (frozen time breaks request signing),+# so these tests freeze time around query execution only, unlike TestBoxPlotTrendsQueryRunner.+class TestBoxPlotTrendsQueryRunnerDataWarehouse(ClickhouseTestMixin, APIBaseTest):+ def teardown_method(self, method) -> None:+ if getattr(self, "cleanUpDataWarehouse", None):+ self.cleanUpDataWarehouse()++ @staticmethod+ def _boxplot_query(series: DataWarehouseNode) -> TrendsQuery:+ return TrendsQuery(+ dateRange=DateRange(date_from="2023-12-01", date_to="2023-12-03"),+ interval="day",+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOX_PLOT),+ series=[series],+ )++ @snapshot_clickhouse_queries+ def test_data_warehouse_series_returns_distribution(self):+ table, _source, _credential, _df, self.cleanUpDataWarehouse = create_data_warehouse_table_from_csv(+ csv_path=Path(__file__).parent / "data" / "boxplot_data.csv",+ table_name="boxplot_table",+ table_columns={+ "id": {"clickhouse": "String", "hogql": "StringDatabaseField"},+ "created": {"clickhouse": "DateTime64(3, 'UTC')", "hogql": "DateTimeDatabaseField"},+ "revenue": {"clickhouse": "Float64", "hogql": "FloatDatabaseField"},+ },+ test_bucket=TEST_BUCKET,+ team=self.team,+ )++ query = self._boxplot_query(+ DataWarehouseNode(+ id=table.name,+ table_name=table.name,+ id_field="id",+ distinct_id_field="id",+ timestamp_field="created",+ math_property="revenue",+ math_property_type="data_warehouse_properties",+ )+ )+ with freeze_time("2024-01-01T00:00:00Z"):+ response = BoxPlotTrendsQueryRunner(team=self.team, query=query).calculate()+ data = [BoxPlotDatum(**d) for d in response.results]++ assert len(data) == 3+ by_day = {d.day: d for d in data}++ datum = by_day["2023-12-02"]+ assert datum.min == 10.0+ assert datum.p25 == pytest.approx(20.0)+ assert datum.median == pytest.approx(30.0)+ assert datum.p75 == pytest.approx(40.0)+ assert datum.max == 50.0+ assert datum.mean == pytest.approx(30.0)+ assert datum.series_label == f"{table.name} - revenue"++ for zero_day in ["2023-12-01", "2023-12-03"]:+ assert by_day[zero_day].min == 0.0+ assert by_day[zero_day].max == 0.0++ def test_data_warehouse_series_without_property_returns_error(self):+ query = self._boxplot_query(+ DataWarehouseNode(+ id="some_table",+ table_name="some_table",+ id_field="id",+ distinct_id_field="id",+ timestamp_field="created",+ )+ )+ with freeze_time("2024-01-01T00:00:00Z"):+ response = BoxPlotTrendsQueryRunner(team=self.team, query=query).calculate()++ assert response.results == []+ assert response.error == "A numeric property must be selected for box plot."