: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 box plots to SQL insights (#84558)
Paul D'Ambraf3cba3fe27cd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1358e7bc1e71..77664f1a4776 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -661,9 +661,9 @@ snapshots:components-hogcharts-barchart--with-value-labels--light:hash: v1.k794b7964.6aff50b1c147df21230d149c147deb023f6308cd2e01983b58e65461dd4c7207.vLZ6XqXFhSTA3hr10RUEv9vzOgxKWYtUzWj0OvoCTU0components-hogcharts-boxplot--multi-series-grouped--dark:- hash: v1.k794b7964.100052bfc106ff42b501157a182699d6814f90be488c4e03ff6d7476fdd05cbe.bLaFB-wXyDHV1bbsR0ssdrE6qYaPmFcUTXnYzWDasY0+ hash: v1.k794b7964.fd8a8c11e35ef420a663807a21a6349eba0ae2658c6c3d114763f4629dd45934.d23KBypemM2QY55g8_QWVUc9diJoAL1oNZjK3d3Ebs4components-hogcharts-boxplot--multi-series-grouped--light:- hash: v1.k794b7964.54b13669ffe5a6341141893094ff6887b677688ab89242bc82217f54129fa7a3.TjWyBhlbZbDBnspp8YhHvJCM5Bu146okpGeZRzWrNKs+ hash: v1.k794b7964.016f9887360412c0b22e1b45e677ab2c289961ce86382e4bb7287f7d8c5dd110.cuv1S6OAl-253E0RJgLwIzHtVxH1ji5mzIOT3GTBWnkcomponents-hogcharts-boxplot--no-grid--dark:hash: v1.k794b7964.ec49b9672a800158cc0dd7f1a517dfec0912d03ce7bc8b56c9a08492fdef723f.5tbdsdN5AB0mtLjoNobhw1skLsS4m5Sc6Es7TSdhTWgcomponents-hogcharts-boxplot--no-grid--light:@@ -2689,9 +2689,9 @@ snapshots:insights-boldnumber--empty-result--light:hash: v1.k794b7964.2d0c17643991833246321ec917a7b3a49228fb7b217b6bdb8742bbebe1164a5d.bFD6Zu0IU06yXEaw5GNlDjBhvFh8vqBKvXRQwCS53gsinsights-boxplot--default--dark:- hash: v1.k794b7964.11bcd18191a129b7b821de0f214b9d5fe9169c98ac2d809c636f87648943d802.DWBO44Qbzd87d8axYy5zm4MSecWPDXxD1I3ZTUUHuUc+ hash: v1.k794b7964.0703a7022dee7396b3f005ebe10aeb376345086ef4c7fc2458108ce87351123d.Ps1FFHDhHcNR2ApWX_ypYngS_xpINJtwB9EH-9n8vLUinsights-boxplot--default--light:- hash: v1.k794b7964.80daaf49ad0c7b82eb9071a207eeadd6db945e06743ba4b64690613f5b70265c.nDmyP88KGm6rnkO-8qNwFQM205eMFRUngrx5R4BjIws+ hash: v1.k794b7964.0e1fc3799ec1876e6ccca4da11c8ebc63836acbe5cbe7453912a385be0564dc5.Pxd_3RMZ6szO03ZwKl6_6UT1AW7TiK_1WllTaLSn60kinsights-funnelbarhorizontalchart--breakdown--dark:hash: v1.k794b7964.e1339725b2bf6fd5c152865170f77320dbc22dc941a23fdc81694f3a4b17f884.poYcV8iWzKuJI0od7oM9G9gjUXrgP38w7bGlQushUjginsights-funnelbarhorizontalchart--breakdown--light:@@ -7132,6 +7132,14 @@ snapshots:hash: v1.k794b7964.e0482531b63e3c6c58bb438b0848b476db1ebadb82736444afb0004e5a7d9a2e.EgJaf86aq6hyYkPzdF8Aydv7rycYiRr_UV8fYh_LIL0scenes-app-insights-side-panel-actions--unsaved-insight--light:hash: v1.k794b7964.2b3ed2b5ffec763b0f7e13af74c9e9d57df96464976ae6014512a0d7def42ad3.paLp2yPHgkf2-ncauikOAUdR87k6-KhAh-Nm4uyQ380+ scenes-app-insights-sqlboxplot--edit-options--dark:+ hash: v1.k794b7964.70df9d8ffa57acac2d95f47d3298bb62ca009f1f4b556717ee0bbe319ab7754e.VwWfKL8TJDDpSmrV3mWOD0VkvzSnBrYJTFtSRpxlQcw+ scenes-app-insights-sqlboxplot--edit-options--light:+ hash: v1.k794b7964.836958043bd3b8203146f802f75a29f5edb8ad4c056a5e2cd01d75a14fa453bb.lDduPTYwYFGPpa1wZHBJEHrKfyxy9jVNMI9-pUQAAjE+ scenes-app-insights-sqlboxplot--grouped-series--dark:+ hash: v1.k794b7964.0062f9e095cb6266619d2886be6973be68c7fc906f50d8b37064390de6757656.frURXaRskPxT8wSqipNvLkFVNmgq3uiSKORwD_fLWDA+ scenes-app-insights-sqlboxplot--grouped-series--light:+ hash: v1.k794b7964.d6214c2e48859cedc4c7dc30552657668a7e9a1a7f92f4643b3d2dbe56df2d57.ytDzXwguLj-27G1jRP28BG-bv7d6q1z4CgNsAmbpqgwscenes-app-insights-sqllinechart--sql-bar-chart-value-labels-quill--dark:hash: v1.k794b7964.482f71c0aadde604594294d6e723590838e5b47f543adf3baf39c5ad2f2a9c3e.bpFdUZ6dFKKinvbM5jklQHy3pQoeURgjrWtjcXipKBwscenes-app-insights-sqllinechart--sql-bar-chart-value-labels-quill--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 1ce4ea6641a2..4d34fe999058 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -203,6 +203,7 @@ export const FEATURE_FLAGS = {REPLAY_EXCLUDE_FROM_HIDE_RECORDINGS_MENU: 'replay-exclude-from-hide-recordings-menu', // owner: #team-replay, used to exclude what other people are seeing in ReplaySHOW_UPGRADE_TO_MANAGED_ACCOUNT: 'show-upgrade-to-managed-account', // owner: #team-billing, used to give free accounts a way to force upgrade to managed accountWEBHOOKS_DENYLIST: 'webhooks-denylist', // owner: #team-ingestion, used to disable webhooks for certain companies+ SQL_BOX_PLOT_INSIGHT: 'sql-box-plot-insight', // owner: @pauldambra #team-product-analytics// Legacy flags, TBD if they need to be removedBATCH_EXPORTS_POSTHOG_HTTP: 'posthog-http-batch-exports', // owner: #team-batch-exportsdiff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlBoxPlot.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlBoxPlot.jsonnew file mode 100644index 000000000000..b0bf619e33c8--- /dev/null+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlBoxPlot.json@@ -0,0 +1,208 @@+{+ "id": 31,+ "short_id": "boxPlot",+ "name": "Latency distribution by plan",+ "derived_name": null,+ "filters": {},+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT\n toStartOfWeek(timestamp) AS bucket,\n properties.plan AS series,\n min(toFloat(properties.latency)) AS min,\n quantile(0.25)(toFloat(properties.latency)) AS p25,\n quantile(0.5)(toFloat(properties.latency)) AS median,\n avg(toFloat(properties.latency)) AS mean,\n quantile(0.75)(toFloat(properties.latency)) AS p75,\n max(toFloat(properties.latency)) AS max\nFROM events\nGROUP BY bucket, series\nORDER BY bucket, series"+ },+ "display": "BoxPlot",+ "chartSettings": {+ "boxPlot": {+ "xAxisColumn": "bucket",+ "seriesColumn": "series",+ "minColumn": "min",+ "p25Column": "p25",+ "medianColumn": "median",+ "meanColumn": "mean",+ "p75Column": "p75",+ "maxColumn": "max",+ "excludeOutliers": true+ },+ "showLegend": true,+ "leftYAxisSettings": {+ "label": "Latency (ms)",+ "showGridLines": true+ }+ }+ },+ "order": null,+ "deleted": false,+ "dashboards": [],+ "dashboard_tiles": [],+ "last_refresh": "2026-03-04T16:10:59.052768Z",+ "cache_target_age": "2026-03-04T22:10:59.052768Z",+ "next_allowed_client_refresh": "2026-03-04T16:11:59.052768Z",+ "result": [+ [+ "2026-01-05",+ "Free",+ 80,+ 120,+ 170,+ 195,+ 240,+ 620+ ],+ [+ "2026-01-05",+ "Paid",+ 45,+ 70,+ 95,+ 110,+ 135,+ 310+ ],+ [+ "2026-01-12",+ "Free",+ 75,+ 115,+ 165,+ 185,+ 225,+ 560+ ],+ [+ "2026-01-12",+ "Paid",+ 40,+ 65,+ 88,+ 102,+ 125,+ 280+ ],+ [+ "2026-01-19",+ "Free",+ 90,+ 135,+ 190,+ 215,+ 265,+ 710+ ],+ [+ "2026-01-19",+ "Paid",+ 50,+ 75,+ 105,+ 118,+ 145,+ 340+ ],+ [+ "2026-01-26",+ "Free",+ 70,+ 105,+ 150,+ 172,+ 210,+ 490+ ],+ [+ "2026-01-26",+ "Paid",+ 38,+ 60,+ 82,+ 96,+ 118,+ 250+ ]+ ],+ "hasMore": false,+ "columns": [+ "bucket",+ "series",+ "min",+ "p25",+ "median",+ "mean",+ "p75",+ "max"+ ],+ "created_at": "2026-03-04T16:11:08.460573Z",+ "created_by": {+ "id": 1,+ "uuid": "019c66e6-fd77-0000-a6bb-509ac38f988e",+ "distinct_id": "otSl3FZiAxw3Vv8GUTeWtZcV3mdpR0lH9pprZmBRKXd",+ "first_name": "Employee 427",+ "last_name": "",+ "email": "[email protected]",+ "is_email_verified": null,+ "hedgehog_config": null,+ "role_at_organization": "engineering"+ },+ "description": null,+ "updated_at": "2026-03-04T16:11:08.460609Z",+ "favorited": false,+ "saved": true,+ "last_modified_at": "2026-03-04T16:11:08.456506Z",+ "last_modified_by": {+ "id": 1,+ "uuid": "019c66e6-fd77-0000-a6bb-509ac38f988e",+ "distinct_id": "otSl3FZiAxw3Vv8GUTeWtZcV3mdpR0lH9pprZmBRKXd",+ "first_name": "Employee 427",+ "last_name": "",+ "email": "[email protected]",+ "is_email_verified": null,+ "hedgehog_config": null,+ "role_at_organization": "engineering"+ },+ "is_sample": false,+ "effective_restriction_level": 21,+ "effective_privilege_level": 37,+ "user_access_level": "manager",+ "timezone": "UTC",+ "is_cached": true,+ "query_status": null,+ "hogql": "SELECT\n toStartOfWeek(timestamp) AS bucket,\n properties.plan AS series,\n min(toFloat(properties.latency)) AS min,\n quantile(0.25)(toFloat(properties.latency)) AS p25,\n quantile(0.5)(toFloat(properties.latency)) AS median,\n avg(toFloat(properties.latency)) AS mean,\n quantile(0.75)(toFloat(properties.latency)) AS p75,\n max(toFloat(properties.latency)) AS max\nFROM events\nGROUP BY bucket, series\nORDER BY bucket, series\nLIMIT 101\nOFFSET 0",+ "types": [+ [+ "bucket",+ "Date"+ ],+ [+ "series",+ "String"+ ],+ [+ "min",+ "Float64"+ ],+ [+ "p25",+ "Float64"+ ],+ [+ "median",+ "Float64"+ ],+ [+ "mean",+ "Float64"+ ],+ [+ "p75",+ "Float64"+ ],+ [+ "max",+ "Float64"+ ]+ ],+ "resolved_date_range": null,+ "alerts": [],+ "last_viewed_at": "2026-03-04T16:11:30.018817Z",+ "tags": [],+ "filters_hash": "cache_1_eb04b61fff884f29a4c74600aea3684fb7769ff1fa6e0d4e59865ee187c3b58b"+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.test.tsxnew file mode 100644index 000000000000..c9ed5f94f432--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.test.tsx@@ -0,0 +1,107 @@+import '@testing-library/jest-dom'++import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { BindLogic } from 'kea'++import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { ChartDisplayType } from '~/types'++import { dataNodeLogic } from '../../DataNode/dataNodeLogic'+import { DataVisualizationLogicProps, dataVisualizationLogic } from '../dataVisualizationLogic'+import { BoxPlotSeriesTab } from './BoxPlotSeriesTab'++const query: DataVisualizationNode = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select * from summaries' },+ display: ChartDisplayType.BoxPlot,+ chartSettings: {+ boxPlot: {+ xAxisColumn: 'bucket',+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: 'mean',+ p75Column: 'p75',+ maxColumn: 'max',+ },+ },+}++const cachedResults: HogQLQueryResponse = {+ results: [['Mon', 1, 2, 3, 4, 5, 6, 0]],+ columns: ['bucket', 'min', 'p25', 'median', 'mean', 'p75', 'max', 'alternate_min'],+ types: [+ ['bucket', 'String'],+ ['min', 'Float64'],+ ['p25', 'Float64'],+ ['median', 'Float64'],+ ['mean', 'Float64'],+ ['p75', 'Float64'],+ ['max', 'Float64'],+ ['alternate_min', 'Float64'],+ ],+}++describe('BoxPlotSeriesTab', () => {+ it('shows box plot roles and saves a changed statistic column', async () => {+ initKeaTests()+ const setQuery = jest.fn()+ let currentQuery = query+ const props: DataVisualizationLogicProps = {+ key: 'box-plot-series-tab',+ query: currentQuery,+ cachedResults,+ dataNodeCollectionId: 'box-plot-series-tab',+ setQuery: (setter) => {+ currentQuery = setter(currentQuery)+ setQuery(currentQuery)+ },+ }++ dataNodeLogic({+ key: props.key,+ query: query.source,+ cachedResults,+ dataNodeCollectionId: props.dataNodeCollectionId,+ }).mount()+ dataVisualizationLogic(props).mount()++ const { container } = render(+ <BindLogic logic={dataVisualizationLogic} props={props}>+ <BoxPlotSeriesTab />+ </BindLogic>+ )++ expect(screen.getByText('25th percentile')).toBeInTheDocument()+ expect(screen.getByText('75th percentile')).toBeInTheDocument()++ const minimumSelect = container.querySelector('[data-attr="box-plot-minColumn"]')+ if (!(minimumSelect instanceof HTMLElement)) {+ throw new Error('Expected the minimum column selector')+ }++ const user = userEvent.setup()+ await user.click(minimumSelect)+ await user.click(await screen.findByText('alternate_min'))++ await waitFor(() => expect(currentQuery.chartSettings?.boxPlot?.minColumn).toBe('alternate_min'))++ const xAxisSelect = container.querySelector('[data-attr="box-plot-x-axis-column"]')+ if (!(xAxisSelect instanceof HTMLElement)) {+ throw new Error('Expected the X-axis column selector')+ }++ await user.click(xAxisSelect)+ const noneOption = (await screen.findAllByText('None')).find(+ (element) => !element.closest('[data-attr="box-plot-series-column"]')+ )+ if (!noneOption) {+ throw new Error('Expected the None option')+ }+ await user.click(noneOption)++ await waitFor(() => expect(currentQuery.chartSettings?.boxPlot?.xAxisColumn).toBeNull())+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.tsxnew file mode 100644index 000000000000..1c1626b68e01--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/BoxPlotSeriesTab.tsx@@ -0,0 +1,88 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonLabel, LemonSelect, LemonTag } from '@posthog/lemon-ui'++import { BoxPlotSettings } from '~/queries/schema/schema-general'++import { Column, dataVisualizationLogic } from '../dataVisualizationLogic'+import { BOX_PLOT_STATISTICS } from './Charts/sqlBoxPlotAdapter'++const NONE_COLUMN = '__posthog_box_plot_none__'++export const BoxPlotSeriesTab = (): JSX.Element => {+ const { chartSettings, columns, numericalColumns, responseLoading } = useValues(dataVisualizationLogic)+ const { updateChartSettings } = useActions(dataVisualizationLogic)+ const settings = chartSettings.boxPlot ?? {}++ const updateSettings = (updates: Partial<BoxPlotSettings>): void => {+ updateChartSettings({ boxPlot: { ...settings, ...updates } })+ }++ const toColumnOption = ({ name, type }: Column): { value: string; label: JSX.Element } => ({+ value: name,+ label: (+ <div className="items-center flex-1">+ {name}+ <LemonTag className="ml-2" type="default">+ {type.name}+ </LemonTag>+ </div>+ ),+ })++ const columnOptions = columns.map(toColumnOption)+ const numericalOptions = numericalColumns.map(toColumnOption)+ const optionalColumnOptions = [{ value: NONE_COLUMN, label: 'None' }, ...columnOptions]+ const disabledReason = responseLoading ? 'Query loading...' : undefined++ return (+ <div className="flex flex-col w-full p-3 gap-4">+ <LemonBanner type="info">+ Return one row per box. Calculate the minimum, percentiles, mean, and maximum in SQL.+ </LemonBanner>++ <div>+ <LemonLabel className="mb-1">X-axis</LemonLabel>+ <LemonSelect+ className="w-full"+ data-attr="box-plot-x-axis-column"+ value={settings.xAxisColumn ?? NONE_COLUMN}+ options={optionalColumnOptions}+ disabledReason={disabledReason}+ onChange={(value) => updateSettings({ xAxisColumn: value === NONE_COLUMN ? null : value })}+ />+ <div className="text-xs text-secondary mt-1">Optional when the query returns one row.</div>+ </div>++ <div>+ <LemonLabel className="mb-1">Series</LemonLabel>+ <LemonSelect+ className="w-full"+ data-attr="box-plot-series-column"+ value={settings.seriesColumn ?? NONE_COLUMN}+ options={optionalColumnOptions}+ disabledReason={disabledReason}+ onChange={(value) => updateSettings({ seriesColumn: value === NONE_COLUMN ? null : value })}+ />+ <div className="text-xs text-secondary mt-1">Optional. Each value becomes a separate series.</div>+ </div>++ <div className="flex flex-col gap-3">+ {BOX_PLOT_STATISTICS.map(({ setting, label }) => (+ <div key={setting}>+ <LemonLabel className="mb-1">{label}</LemonLabel>+ <LemonSelect+ className="w-full"+ data-attr={`box-plot-${setting}`}+ value={settings[setting]}+ placeholder="Select a numeric column"+ options={numericalOptions}+ disabledReason={disabledReason}+ onChange={(value) => updateSettings({ [setting]: value })}+ />+ </div>+ ))}+ </div>+ </div>+ )+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsxnew file mode 100644index 000000000000..1fea84c68c3d--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.test.tsx@@ -0,0 +1,147 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'++import type { BoxPlotConfig, BoxPlotSeries } from '@posthog/quill-charts'++import { BoxPlotSettings, ChartSettings } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { Column } from '../../dataVisualizationLogic'+import { SqlBoxPlot } from './SqlBoxPlot'++let latestBoxPlotProps: { labels: string[]; series: BoxPlotSeries[]; config?: BoxPlotConfig } | null = null++jest.mock('posthog-js', () => ({+ __esModule: true,+ default: { capture: jest.fn(), get_session_id: jest.fn(() => 'session-1') },+}))++jest.mock('@posthog/quill-charts', () => ({+ ...jest.requireActual('@posthog/quill-charts'),+ BoxPlot: (props: { labels: string[]; series: BoxPlotSeries[]; config?: BoxPlotConfig }): JSX.Element => {+ latestBoxPlotProps = props+ return <div data-attr="mock-sql-box-plot" />+ },+}))++const posthog = jest.requireMock('posthog-js').default as { capture: jest.Mock }++const columns: Column[] = [+ { name: 'bucket', label: 'bucket', dataIndex: 0, type: { name: 'STRING', isNumerical: false } },+ { name: 'series', label: 'series', dataIndex: 1, type: { name: 'STRING', isNumerical: false } },+ { name: 'min', label: 'min', dataIndex: 2, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'p25', label: 'p25', dataIndex: 3, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'median', label: 'median', dataIndex: 4, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'mean', label: 'mean', dataIndex: 5, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'p75', label: 'p75', dataIndex: 6, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'max', label: 'max', dataIndex: 7, type: { name: 'FLOAT', isNumerical: true } },+]++const boxPlotSettings: BoxPlotSettings = {+ xAxisColumn: 'bucket',+ seriesColumn: 'series',+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: 'mean',+ p75Column: 'p75',+ maxColumn: 'max',+ excludeOutliers: false,+}++const chartSettings: ChartSettings = { boxPlot: boxPlotSettings }++describe('SqlBoxPlot', () => {+ beforeEach(() => {+ initKeaTests()+ latestBoxPlotProps = null+ posthog.capture.mockClear()+ })++ afterEach(() => {+ cleanup()+ })++ it('renders grouped boxes with the standard axis defaults', async () => {+ render(+ <SqlBoxPlot+ rows={[+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ['Mon', 'Paid', 7, 8, 9, 10, 11, 12],+ ]}+ columns={columns}+ chartSettings={chartSettings}+ analyticsKey="grouped-test"+ />+ )++ await screen.findByTestId('mock-sql-box-plot')+ expect(posthog.capture).not.toHaveBeenCalled()+ expect(latestBoxPlotProps).toMatchObject({+ labels: ['Mon'],+ series: [+ { key: 'Free', label: 'Free' },+ { key: 'Paid', label: 'Paid' },+ ],+ config: {+ showGrid: true,+ showAxisLines: { x: true, y: true },+ },+ })+ })++ it('captures unrendered items once per chart and session while keeping valid boxes', async () => {+ const { rerender } = render(+ <SqlBoxPlot+ rows={[+ ['Mon', 'Free', 1, null, 3, 4, 5, 6],+ ['Tue', 'Free', 1, 2, 3, 4, 5, 6],+ ]}+ columns={columns}+ chartSettings={chartSettings}+ analyticsKey="skipped-test"+ />+ )++ await screen.findByTestId('mock-sql-box-plot')+ expect(latestBoxPlotProps).toMatchObject({+ labels: ['Tue'],+ series: [{ key: 'Free', label: 'Free' }],+ })+ await waitFor(() =>+ expect(posthog.capture).toHaveBeenCalledWith('sql box plot items not rendered', {+ unrendered_item_count: 1,+ total_item_count: 2,+ reasons: { missingStatistic: 1, invalidOrder: 0, meanOutsideRange: 0 },+ })+ )++ rerender(+ <SqlBoxPlot+ rows={[+ ['Mon', 'Free', 1, null, 3, 4, 5, 6],+ ['Tue', 'Free', 1, null, 3, 4, 5, 6],+ ]}+ columns={columns}+ chartSettings={chartSettings}+ analyticsKey="skipped-test"+ />+ )+ await waitFor(() => expect(posthog.capture).toHaveBeenCalledTimes(1))+ })++ it('explains how to fix missing column mappings', () => {+ render(+ <SqlBoxPlot+ rows={[['Mon', 'Free', 1, 2, 3, 4, 5, 6]]}+ columns={columns}+ chartSettings={{ boxPlot: { ...boxPlotSettings, medianColumn: undefined } }}+ analyticsKey="mapping-error-test"+ />+ )++ expect(screen.getByText('Select a column for Median.')).toBeInTheDocument()+ expect(latestBoxPlotProps).toBeNull()+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsxnew file mode 100644index 000000000000..595cbb31df4b--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBoxPlot.tsx@@ -0,0 +1,117 @@+import clsx from 'clsx'+import posthog from 'posthog-js'+import { useEffect, useMemo } from 'react'++import { BoxPlot } from '@posthog/quill-charts'+import type { BoxPlotConfig } from '@posthog/quill-charts'++import { useChartConfig, useChartTheme } from 'lib/charts/hooks'++import { ChartSettings } from '~/queries/schema/schema-general'++import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'++import { Column } from '../../dataVisualizationLogic'+import { buildSqlBoxPlotModel } from './sqlBoxPlotAdapter'++const handleChartError = makeChartErrorHandler('sql-box-plot')+const capturedUnrenderedItems = new Set<string>()++export interface SqlBoxPlotProps {+ rows: unknown[][]+ columns: Column[]+ chartSettings: ChartSettings+ analyticsKey: string+ presetChartHeight?: boolean+ className?: string+}++export const SqlBoxPlot = ({+ rows,+ columns,+ chartSettings,+ analyticsKey,+ presetChartHeight,+ className,+}: SqlBoxPlotProps): JSX.Element => {+ const theme = useChartTheme()+ const model = useMemo(+ () => buildSqlBoxPlotModel(rows, columns, chartSettings.boxPlot ?? {}),+ [rows, columns, chartSettings.boxPlot]+ )+ const skippedRowCount = Object.values(model.skippedRows).reduce((total, count) => total + count, 0)+ useEffect(() => {+ const chartSessionKey = `${analyticsKey}:${posthog.get_session_id?.() ?? 'unknown'}`+ if (skippedRowCount > 0 && !capturedUnrenderedItems.has(chartSessionKey)) {+ capturedUnrenderedItems.add(chartSessionKey)+ // pinned: analytics event name - renaming breaks dashboards+ posthog.capture('sql box plot items not rendered', {+ unrendered_item_count: skippedRowCount,+ total_item_count: rows.length,+ reasons: model.skippedRows,+ })+ }+ }, [analyticsKey, model.skippedRows, rows.length, skippedRowCount])++ const yAxisSettings = chartSettings.leftYAxisSettings+ const config = useChartConfig<BoxPlotConfig>(+ () => ({+ yScaleType: yAxisSettings?.scale === 'logarithmic' ? 'log' : 'linear',+ xAxisLabel: chartSettings.xAxisLabel,+ yAxisLabel: yAxisSettings?.label,+ hideXAxis: chartSettings.showXAxisTicks === false,+ hideYAxis: yAxisSettings?.showTicks === false,+ showGrid: yAxisSettings?.showGridLines ?? true,+ showAxisLines: {+ x: chartSettings.showXAxisBorder ?? true,+ y: chartSettings.showYAxisBorder ?? true,+ },+ tooltip: { pinnable: true, placement: 'cursor' },+ legend: { show: chartSettings.showLegend ?? false, position: 'top' },+ }),+ [chartSettings, yAxisSettings]+ )++ const heightClass = presetChartHeight ? 'h-[60vh]' : 'h-full'++ const containerClassName = clsx(+ className,+ 'rounded bg-surface-primary flex flex-1 items-center justify-center p-3',+ heightClass+ )++ if (model.error) {+ return (+ <div className={containerClassName} data-attr="sql-box-plot-error">+ <span className="text-secondary text-sm">{model.error}</span>+ </div>+ )+ }++ if (model.series.length === 0) {+ return (+ <div className={containerClassName} data-attr="sql-box-plot-empty">+ <span className="text-secondary text-sm">No boxes to plot. Check that your query returns rows.</span>+ </div>+ )+ }++ return (+ <div+ className={clsx(+ className,+ 'rounded bg-surface-primary w-full grow relative overflow-hidden flex flex-col p-3',+ heightClass+ )}+ >+ <BoxPlot+ series={model.series}+ labels={model.labels}+ theme={theme}+ config={config}+ dataAttr="sql-box-plot"+ onError={handleChartError}+ />+ </div>+ )+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.test.tsnew file mode 100644index 000000000000..24fca251eadc--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.test.ts@@ -0,0 +1,251 @@+import { BoxPlotSettings } from '~/queries/schema/schema-general'++import { Column } from '../../dataVisualizationLogic'+import { buildSqlBoxPlotModel, getAutoBoxPlotSettings } from './sqlBoxPlotAdapter'++const columns: Column[] = [+ { name: 'bucket', label: 'bucket', dataIndex: 0, type: { name: 'STRING', isNumerical: false } },+ { name: 'series', label: 'series', dataIndex: 1, type: { name: 'STRING', isNumerical: false } },+ { name: 'min', label: 'min', dataIndex: 2, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'p25', label: 'p25', dataIndex: 3, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'median', label: 'median', dataIndex: 4, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'mean', label: 'mean', dataIndex: 5, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'p75', label: 'p75', dataIndex: 6, type: { name: 'FLOAT', isNumerical: true } },+ { name: 'max', label: 'max', dataIndex: 7, type: { name: 'FLOAT', isNumerical: true } },+]++const settings: BoxPlotSettings = {+ xAxisColumn: 'bucket',+ seriesColumn: 'series',+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: 'mean',+ p75Column: 'p75',+ maxColumn: 'max',+}++describe('sqlBoxPlotAdapter', () => {+ test('builds grouped series and leaves missing combinations empty', () => {+ const model = buildSqlBoxPlotModel(+ [+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ['Tue', 'Paid', 10, 20, 30, 40, 50, 60],+ ['Mon', 'Paid', 7, 8, 9, 10, 11, 12],+ ],+ columns,+ settings+ )++ expect(model.error).toBeNull()+ expect(model.labels).toEqual(['Mon', 'Tue'])+ expect(model.series).toEqual([+ {+ key: 'Free',+ label: 'Free',+ data: [{ min: 1, p25: 2, median: 3, mean: 4, p75: 5, max: 6 }, null],+ },+ {+ key: 'Paid',+ label: 'Paid',+ data: [+ { min: 7, p25: 8, median: 9, mean: 10, p75: 11, max: 12 },+ { min: 10, p25: 20, median: 30, mean: 40, p75: 50, max: 60 },+ ],+ },+ ])+ })++ test.each([+ {+ name: 'missing mappings',+ rows: [['Mon', 'Free', 1, 2, 3, 4, 5, 6]],+ boxPlotSettings: { ...settings, medianColumn: undefined },+ error: 'Select a column for Median.',+ },+ {+ name: 'duplicate bucket and series pairs',+ rows: [+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ],+ boxPlotSettings: settings,+ error: 'Rows 1 and 2 use the same X-axis and series values. Return one row for each box.',+ },+ {+ name: 'several rows without an x-axis or series',+ rows: [+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ['Tue', 'Free', 1, 2, 3, 4, 5, 6],+ ],+ boxPlotSettings: { ...settings, xAxisColumn: undefined, seriesColumn: undefined },+ error: 'Select an X-axis column when the query returns more than one row.',+ },+ {+ name: 'different x-axis values with the same display label',+ rows: [+ [null, 'Free', 1, 2, 3, 4, 5, 6],+ ['[No value]', 'Free', 1, 2, 3, 4, 5, 6],+ ],+ boxPlotSettings: settings,+ error: 'Row 2 has an X-axis value that displays as "[No value]", but another value uses the same label. Cast them to distinct strings in SQL.',+ },+ {+ name: 'different series values with the same display label',+ rows: [+ ['Mon', null, 1, 2, 3, 4, 5, 6],+ ['Mon', '[No value]', 1, 2, 3, 4, 5, 6],+ ],+ boxPlotSettings: settings,+ error: 'Row 2 has a series value that displays as "[No value]", but another value uses the same label. Cast them to distinct strings in SQL.',+ },+ ])('reports $name', ({ rows, boxPlotSettings, error }) => {+ expect(buildSqlBoxPlotModel(rows, columns, boxPlotSettings).error).toBe(error)+ })++ test.each([+ {+ name: 'missing statistic',+ invalidRow: ['Mon', 'Free', 1, null, 3, 4, 5, 6],+ skippedRows: { missingStatistic: 1, invalidOrder: 0, meanOutsideRange: 0 },+ },+ {+ name: 'invalid statistic order',+ invalidRow: ['Mon', 'Free', 1, 4, 3, 3, 5, 6],+ skippedRows: { missingStatistic: 0, invalidOrder: 1, meanOutsideRange: 0 },+ },+ {+ name: 'mean outside range',+ invalidRow: ['Mon', 'Free', 1, 2, 3, 9, 5, 6],+ skippedRows: { missingStatistic: 0, invalidOrder: 0, meanOutsideRange: 1 },+ },+ ])('skips a box with $name without hiding valid boxes', ({ invalidRow, skippedRows }) => {+ const model = buildSqlBoxPlotModel([invalidRow, ['Tue', 'Free', 1, 2, 3, 4, 5, 6]], columns, settings)++ expect(model.error).toBeNull()+ expect(model.labels).toEqual(['Tue'])+ expect(model.series).toEqual([+ {+ key: 'Free',+ label: 'Free',+ data: [{ min: 1, p25: 2, median: 3, mean: 4, p75: 5, max: 6 }],+ },+ ])+ expect(model.skippedRows).toEqual(skippedRows)+ })++ test('rejects result shapes that would create a large sparse matrix', () => {+ const rows = Array.from({ length: 101 }, (_, label) =>+ Array.from({ length: 100 }, (_, series) => [label, series, 1, 2, 3, 4, 5, 6])+ ).flat()++ expect(buildSqlBoxPlotModel(rows, columns, settings).error).toBe(+ 'The box plot has too many X-axis and series combinations. Reduce the query result.'+ )+ })++ test('rejects more series than the series limit even when the cell matrix stays small', () => {+ const rows = Array.from({ length: 201 }, (_, series) => ['Mon', series, 1, 2, 3, 4, 5, 6])++ expect(buildSqlBoxPlotModel(rows, columns, settings).error).toBe(+ 'The box plot has too many series. Reduce the number of distinct series values in the query result.'+ )+ })++ test('uses one distribution when the query returns one row without grouping columns', () => {+ const model = buildSqlBoxPlotModel(+ [[1, 2, 3, 4, 5, 6]],+ columns.slice(2).map((column, dataIndex) => ({ ...column, dataIndex })),+ {+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: 'mean',+ p75Column: 'p75',+ maxColumn: 'max',+ }+ )++ expect(model.labels).toEqual(['Distribution'])+ expect(model.series).toEqual([+ {+ key: 'Distribution',+ label: 'Distribution',+ data: [{ min: 1, p25: 2, median: 3, mean: 4, p75: 5, max: 6 }],+ },+ ])+ })++ test('groups by series when the query returns one row per series without an x-axis', () => {+ const model = buildSqlBoxPlotModel(+ [+ ['Mon', 'Free', 1, 2, 3, 4, 5, 6],+ ['Mon', 'Paid', 7, 8, 9, 10, 11, 12],+ ],+ columns,+ { ...settings, xAxisColumn: undefined }+ )++ expect(model.error).toBeNull()+ expect(model.labels).toEqual(['Distribution'])+ expect(model.series).toEqual([+ {+ key: 'Free',+ label: 'Free',+ data: [{ min: 1, p25: 2, median: 3, mean: 4, p75: 5, max: 6 }],+ },+ {+ key: 'Paid',+ label: 'Paid',+ data: [{ min: 7, p25: 8, median: 9, mean: 10, p75: 11, max: 12 }],+ },+ ])+ })++ test.each([+ { excludeOutliers: true, expectedMin: -4, expectedMax: 12 },+ { excludeOutliers: false, expectedMin: -100, expectedMax: 100 },+ ])(+ 'sets whiskers to $expectedMin and $expectedMax when excludeOutliers is $excludeOutliers',+ ({ excludeOutliers, expectedMin, expectedMax }) => {+ const model = buildSqlBoxPlotModel([['Mon', 'Free', -100, 2, 3, 4, 6, 100]], columns, {+ ...settings,+ excludeOutliers,+ })++ expect(model.series[0].data[0]).toEqual({+ min: expectedMin,+ p25: 2,+ median: 3,+ mean: 4,+ p75: 6,+ max: expectedMax,+ })+ }+ )++ test.each([+ {+ name: 'valid choices',+ current: { xAxisColumn: 'bucket', meanColumn: 'median' },+ expectedGrouping: { xAxisColumn: 'bucket', seriesColumn: 'series' },+ expectedMean: 'median',+ },+ {+ name: 'explicit ungrouped choices',+ current: { xAxisColumn: null, seriesColumn: null },+ expectedGrouping: { xAxisColumn: null, seriesColumn: null },+ expectedMean: 'mean',+ },+ ])('auto-maps conventional aliases and preserves $name', ({ current, expectedGrouping, expectedMean }) => {+ expect(getAutoBoxPlotSettings(columns, current)).toEqual({+ ...expectedGrouping,+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: expectedMean,+ p75Column: 'p75',+ maxColumn: 'max',+ })+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.tsnew file mode 100644index 000000000000..6cf1d276f34f--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlBoxPlotAdapter.ts@@ -0,0 +1,231 @@+import type { BoxPlotDatum, BoxPlotSeries } from '@posthog/quill-charts'++import { BoxPlotSettings } from '~/queries/schema/schema-general'++interface BoxPlotColumn {+ name: string+ dataIndex: number+ type: { isNumerical: boolean }+}++export type SqlBoxPlotSkippedRowReason = 'missingStatistic' | 'invalidOrder' | 'meanOutsideRange'++export interface SqlBoxPlotModel {+ labels: string[]+ series: BoxPlotSeries[]+ error: string | null+ skippedRows: Record<SqlBoxPlotSkippedRowReason, number>+}++export type BoxPlotStatisticColumn = keyof Pick<+ BoxPlotSettings,+ 'minColumn' | 'p25Column' | 'medianColumn' | 'meanColumn' | 'p75Column' | 'maxColumn'+>++type BoxPlotValue = keyof Pick<BoxPlotDatum, 'min' | 'p25' | 'median' | 'mean' | 'p75' | 'max'>++export const BOX_PLOT_STATISTICS: {+ setting: BoxPlotStatisticColumn+ value: BoxPlotValue+ label: string+ aliases: string[]+}[] = [+ { setting: 'minColumn', value: 'min', label: 'Minimum', aliases: ['min', 'minimum'] },+ { setting: 'p25Column', value: 'p25', label: '25th percentile', aliases: ['p25', 'q1'] },+ { setting: 'medianColumn', value: 'median', label: 'Median', aliases: ['median', 'p50'] },+ { setting: 'meanColumn', value: 'mean', label: 'Mean', aliases: ['mean', 'avg', 'average'] },+ { setting: 'p75Column', value: 'p75', label: '75th percentile', aliases: ['p75', 'q3'] },+ { setting: 'maxColumn', value: 'max', label: 'Maximum', aliases: ['max', 'maximum'] },+]++const MAX_BOX_PLOT_CELLS = 10_000+// The cell cap alone permits thousands of series under a single X-axis value, so limit series+// independently because each one adds a legend row and per-hover work. Matches MAX_SERIES in+// sqlLineGraphAdapter.+const MAX_BOX_PLOT_SERIES = 200++const emptySkippedRows = (): Record<SqlBoxPlotSkippedRowReason, number> => ({+ missingStatistic: 0,+ invalidOrder: 0,+ meanOutsideRange: 0,+})++const emptyModel = (error: string | null = null): SqlBoxPlotModel => ({+ labels: [],+ series: [],+ error,+ skippedRows: emptySkippedRows(),+})++const findColumn = (+ columns: BoxPlotColumn[],+ name: string | null | undefined,+ numerical = false+): BoxPlotColumn | undefined => {+ if (!name) {+ return undefined+ }+ return columns.find((column) => column.name === name && (!numerical || column.type.isNumerical))+}++const findAliasedColumn = (columns: BoxPlotColumn[], aliases: string[], numerical = false): BoxPlotColumn | undefined =>+ columns.find((column) => aliases.includes(column.name.toLowerCase()) && (!numerical || column.type.isNumerical))++export const getAutoBoxPlotSettings = (columns: BoxPlotColumn[], current: BoxPlotSettings = {}): BoxPlotSettings => {+ const next = { ...current }++ if (current.xAxisColumn !== null && !findColumn(columns, current.xAxisColumn)) {+ next.xAxisColumn = findAliasedColumn(columns, ['label', 'bucket', 'date', 'day'])?.name+ }+ if (current.seriesColumn !== null && !findColumn(columns, current.seriesColumn)) {+ next.seriesColumn = findAliasedColumn(columns, ['series', 'breakdown'])?.name+ }++ for (const statistic of BOX_PLOT_STATISTICS) {+ if (!findColumn(columns, current[statistic.setting], true)) {+ next[statistic.setting] = findAliasedColumn(columns, statistic.aliases, true)?.name+ }+ }++ return next+}++const groupingIdentity = (value: unknown): string => JSON.stringify([typeof value, value ?? null])++const finiteNumber = (value: unknown): number | null => {+ if (value === null || value === undefined || value === '') {+ return null+ }+ const number = typeof value === 'number' ? value : Number(value)+ return Number.isFinite(number) ? number : null+}++export const buildSqlBoxPlotModel = (+ rows: unknown[][],+ columns: BoxPlotColumn[],+ settings: BoxPlotSettings+): SqlBoxPlotModel => {+ const statisticColumns = BOX_PLOT_STATISTICS.map((statistic) => ({+ ...statistic,+ column: findColumn(columns, settings[statistic.setting], true),+ }))+ const missingStatistic = statisticColumns.find(({ column }) => !column)+ if (missingStatistic) {+ return emptyModel(`Select a column for ${missingStatistic.label}.`)+ }++ if (rows.length === 0) {+ return emptyModel()+ }++ const xAxisColumn = findColumn(columns, settings.xAxisColumn)+ const seriesColumn = findColumn(columns, settings.seriesColumn)+ if (!xAxisColumn && !seriesColumn && rows.length > 1) {+ return emptyModel('Select an X-axis column when the query returns more than one row.')+ }++ const labels: string[] = []+ const labelSet = new Set<string>()+ const seriesLabels: string[] = []+ const seriesLabelSet = new Set<string>()+ const dataBySeries = new Map<string, Map<string, BoxPlotSeries['data'][number]>>()+ const skippedRows = emptySkippedRows()+ const xIdentityByLabel = new Map<string, string>()+ const seriesIdentityByLabel = new Map<string, string>()+ const rowByPair = new Map<string, number>()++ for (const [rowIndex, row] of rows.entries()) {+ const nullableValues = Object.fromEntries(+ statisticColumns.map((statistic) => [statistic.value, finiteNumber(row[statistic.column!.dataIndex])])+ ) as Record<BoxPlotValue, number | null>+ if (Object.values(nullableValues).some((value) => value === null)) {+ skippedRows.missingStatistic+++ continue+ }++ const values = nullableValues as Record<BoxPlotValue, number>+ if (+ !(+ values.min <= values.p25 &&+ values.p25 <= values.median &&+ values.median <= values.p75 &&+ values.p75 <= values.max+ )+ ) {+ skippedRows.invalidOrder+++ continue+ }+ if (values.mean < values.min || values.mean > values.max) {+ skippedRows.meanOutsideRange+++ continue+ }++ const xValue = xAxisColumn ? row[xAxisColumn.dataIndex] : 'Distribution'+ const seriesValue = seriesColumn ? row[seriesColumn.dataIndex] : 'Distribution'+ const label = String(xValue ?? '[No value]')+ const seriesLabel = String(seriesValue ?? '[No value]')+ const xIdentity = groupingIdentity(xValue)+ const seriesIdentity = groupingIdentity(seriesValue)++ if (xIdentityByLabel.has(label) && xIdentityByLabel.get(label) !== xIdentity) {+ return emptyModel(+ `Row ${rowIndex + 1} has an X-axis value that displays as "${label}", but another value uses the same label. Cast them to distinct strings in SQL.`+ )+ }+ if (seriesIdentityByLabel.has(seriesLabel) && seriesIdentityByLabel.get(seriesLabel) !== seriesIdentity) {+ return emptyModel(+ `Row ${rowIndex + 1} has a series value that displays as "${seriesLabel}", but another value uses the same label. Cast them to distinct strings in SQL.`+ )+ }+ xIdentityByLabel.set(label, xIdentity)+ seriesIdentityByLabel.set(seriesLabel, seriesIdentity)++ const pairKey = JSON.stringify([xIdentity, seriesIdentity])+ const previousRow = rowByPair.get(pairKey)+ if (previousRow !== undefined) {+ return emptyModel(+ `Rows ${previousRow + 1} and ${rowIndex + 1} use the same X-axis and series values. Return one row for each box.`+ )+ }+ rowByPair.set(pairKey, rowIndex)++ if (!labelSet.has(label)) {+ labels.push(label)+ labelSet.add(label)+ }+ if (!seriesLabelSet.has(seriesLabel)) {+ seriesLabels.push(seriesLabel)+ seriesLabelSet.add(seriesLabel)+ if (seriesLabelSet.size > MAX_BOX_PLOT_SERIES) {+ return emptyModel(+ 'The box plot has too many series. Reduce the number of distinct series values in the query result.'+ )+ }+ }+ if (labelSet.size * seriesLabelSet.size > MAX_BOX_PLOT_CELLS) {+ return emptyModel('The box plot has too many X-axis and series combinations. Reduce the query result.')+ }++ const iqr = values.p75 - values.p25+ const excludeOutliers = settings.excludeOutliers !== false+ const datum = {+ ...values,+ min: excludeOutliers ? Math.max(values.min, values.p25 - 1.5 * iqr) : values.min,+ max: excludeOutliers ? Math.min(values.max, values.p75 + 1.5 * iqr) : values.max,+ }+ const seriesData = dataBySeries.get(seriesLabel) ?? new Map()+ seriesData.set(label, datum)+ dataBySeries.set(seriesLabel, seriesData)+ }++ return {+ labels,+ series: seriesLabels.map((seriesLabel) => ({+ key: seriesLabel,+ label: seriesLabel,+ data: labels.map((label) => dataBySeries.get(seriesLabel)?.get(label) ?? null),+ })),+ error: null,+ skippedRows,+ }+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsxindex 3d92bb18adac..28e80824d02d 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.test.tsx@@ -130,6 +130,54 @@ describe('DisplayTab', () => {)})})+ it('offers box plot settings and hides unsupported controls', async () => {+ initKeaTests()++ const key = 'display-tab-box-plot-test'+ let query: DataVisualizationNode = {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: 'select * from summaries',+ },+ display: ChartDisplayType.BoxPlot,+ chartSettings: { boxPlot: { excludeOutliers: true } },+ }++ const props: DataVisualizationLogicProps = {+ key,+ query,+ dataNodeCollectionId: key,+ setQuery: (setter) => {+ query = setter(query)+ },+ }++ dataVisualizationLogic(props).mount()+ displayLogic({ key }).mount()++ render(+ <BindLogic logic={dataVisualizationLogic} props={props}>+ <BindLogic logic={displayLogic} props={{ key }}>+ <DisplayTab />+ </BindLogic>+ </BindLogic>+ )++ const user = userEvent.setup()++ expect(await screen.findByText('Y-axis')).toBeInTheDocument()+ expect(screen.queryByText('Right Y-axis')).not.toBeInTheDocument()+ expect(screen.queryByText('Goals')).not.toBeInTheDocument()+ expect(screen.queryByText('Show total row')).not.toBeInTheDocument()++ await user.click(screen.getByText('Exclude outliers'))+ await user.click(screen.getByText('Y-axis'))+ expect(screen.queryByText('Begin at zero')).not.toBeInTheDocument()++ await waitFor(() => expect(query.chartSettings?.boxPlot?.excludeOutliers).toBe(false))+ })+it('offers scatter axis settings and drops the panels a scatter has no support for', async () => {initKeaTests()diff --git a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsxindex fee2e17fd653..adc6cdb58b60 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/DisplayTab.tsx@@ -43,12 +43,15 @@ export const DisplayTab = (): JSX.Element => {const isStackedBarChart = effectiveVisualizationType === ChartDisplayType.ActionsStackedBarconst isPieChart = effectiveVisualizationType === ChartDisplayType.ActionsPieconst isScatterPlot = effectiveVisualizationType === ChartDisplayType.ScatterPlot+ const isBoxPlot = effectiveVisualizationType === ChartDisplayType.BoxPlot+ // Scatter and box plots have a single Y axis, so there is no separate right axis to configure.+ const isSingleAxisChart = isScatterPlot || isBoxPlotconst isLineChart =effectiveVisualizationType === ChartDisplayType.ActionsLineGraph ||effectiveVisualizationType === ChartDisplayType.ActionsAreaGraphconst renderYAxisSettings = (name: 'leftYAxisSettings' | 'rightYAxisSettings'): JSX.Element => {- const leftPlaceholder = isScatterPlot ? 'Y-axis label' : 'Left Y-axis label'+ const leftPlaceholder = isSingleAxisChart ? 'Y-axis label' : 'Left Y-axis label'const labelPlaceholder = name === 'leftYAxisSettings' ? leftPlaceholder : 'Right Y-axis label'return (@@ -87,17 +90,19 @@ export const DisplayTab = (): JSX.Element => {}}/>- <LemonSwitch- className="flex-1 w-full"- label="Begin at zero"- checked={- chartSettings[name]?.startAtZero ??- (isScatterPlot ? false : (chartSettings.yAxisAtZero ?? true))- }- onChange={(value) => {- updateChartSettings({ [name]: { startAtZero: value } })- }}- />+ {!isBoxPlot && (+ <LemonSwitch+ className="flex-1 w-full"+ label="Begin at zero"+ checked={+ chartSettings[name]?.startAtZero ??+ (isScatterPlot ? false : (chartSettings.yAxisAtZero ?? true))+ }+ onChange={(value) => {+ updateChartSettings({ [name]: { startAtZero: value } })+ }}+ />+ )}<LemonSwitchclassName="flex-1 w-full"label="Show grid lines"@@ -131,6 +136,16 @@ export const DisplayTab = (): JSX.Element => {updateChartSettings({ showLegend: value })}}/>+ {isBoxPlot && (+ <LemonSwitch+ className="flex-1 w-full"+ label="Exclude outliers"+ checked={chartSettings.boxPlot?.excludeOutliers !== false}+ onChange={(value) => {+ updateChartSettings({ boxPlot: { excludeOutliers: value } })+ }}+ />+ )}{isPieChart ? (<><div className="flex flex-col gap-1">@@ -181,7 +196,7 @@ export const DisplayTab = (): JSX.Element => {}}/>)}- {!isScatterPlot && (+ {!isSingleAxisChart && (<><LemonSwitchclassName="flex-1 w-full"@@ -306,13 +321,13 @@ export const DisplayTab = (): JSX.Element => {!isPieChart? {key: 'left-y-axis',- header: isScatterPlot ? 'Y-axis' : 'Left Y-axis',+ header: isSingleAxisChart ? 'Y-axis' : 'Left Y-axis',className: 'p-2 flex flex-col gap-2',content: renderYAxisSettings('leftYAxisSettings'),}: null,// A scatter has one gutter per axis, so there is no second Y axis to configure.- !isPieChart && !isScatterPlot+ !isPieChart && !isSingleAxisChart? {key: 'right-y-axis',header: 'Right Y-axis',@@ -337,7 +352,7 @@ export const DisplayTab = (): JSX.Element => {),}: null,- !isPieChart && !isScatterPlot+ !isPieChart && !isSingleAxisChart? {key: 'goals',header: (diff --git a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsxindex 601eb6ad4e3d..65fd519bbe78 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/SeriesTab.tsx@@ -27,6 +27,7 @@ import { ResultCustomizationBy } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'import { AxisSeries, Column, dataVisualizationLogic } from '../dataVisualizationLogic'+import { BoxPlotSeriesTab } from './BoxPlotSeriesTab'import { HeatmapSeriesTab } from './Heatmap/HeatmapSeriesTab'import { AxisBreakdownSeries, BREAKDOWN_LIMIT_LABEL, seriesBreakdownLogic } from './seriesBreakdownLogic'import { getAvailableSeriesBreakdownColumns } from './seriesBreakdownUtils'@@ -70,6 +71,10 @@ export const SeriesTab = (): JSX.Element => {return <HeatmapSeriesTab />}+ if (effectiveVisualizationType === ChartDisplayType.BoxPlot) {+ return <BoxPlotSeriesTab />+ }+if (showTableSettings) {return (<div className="flex flex-col w-full p-3 gap-4">diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.test.tsxnew file mode 100644index 000000000000..c4599c78ec3b--- /dev/null+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.test.tsx@@ -0,0 +1,80 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { BindLogic } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { ChartDisplayType } from '~/types'++import { dataNodeLogic } from '../../DataNode/dataNodeLogic'+import { DataVisualizationLogicProps, dataVisualizationLogic } from '../dataVisualizationLogic'+import { TableDisplay } from './TableDisplay'++const cachedResults: HogQLQueryResponse = {+ results: [['Mon', 1, 2, 3, 4, 5, 6]],+ columns: ['bucket', 'min', 'p25', 'median', 'mean', 'p75', 'max'],+ types: [+ ['bucket', 'String'],+ ['min', 'Float64'],+ ['p25', 'Float64'],+ ['median', 'Float64'],+ ['mean', 'Float64'],+ ['p75', 'Float64'],+ ['max', 'Float64'],+ ],+}++describe('TableDisplay', () => {+ afterEach(() => {+ cleanup()+ featureFlagLogic.unmount()+ })++ it('offers box plots and saves the selected display when the feature is enabled', async () => {+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT], {+ [FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT]: true,+ })++ let query: DataVisualizationNode = {+ kind: NodeKind.DataVisualizationNode,+ source: { kind: NodeKind.HogQLQuery, query: 'select * from summaries' },+ display: ChartDisplayType.ActionsTable,+ }+ const props: DataVisualizationLogicProps = {+ key: 'table-display-box-plot',+ query,+ cachedResults,+ dataNodeCollectionId: 'table-display-box-plot',+ setQuery: (setter) => {+ query = setter(query)+ },+ }++ dataNodeLogic({+ key: props.key,+ query: query.source,+ cachedResults,+ dataNodeCollectionId: props.dataNodeCollectionId,+ }).mount()+ dataVisualizationLogic(props).mount()++ render(+ <BindLogic logic={dataVisualizationLogic} props={props}>+ <TableDisplay />+ </BindLogic>+ )++ const user = userEvent.setup()+ await user.click(screen.getByTestId('chart-filter'))+ await user.click(await screen.findByText('Box plot'))++ await waitFor(() => expect(query.display).toBe(ChartDisplayType.BoxPlot))+ })+})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsxindex afa177922e80..dfbf5f151e74 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/TableDisplay.tsx@@ -3,7 +3,9 @@ import { useActions, useValues } from 'kea'import { IconGraph, IconLifecycle, IconPieChart, IconScatter, IconTrends } from '@posthog/icons'import { LemonSelect, LemonSelectOptions, LemonSelectProps } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { Icon123, IconAreaChart, IconHeatmap, IconTableChart } from 'lib/lemon-ui/icons'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { ChartDisplayType } from '~/types'@@ -14,6 +16,7 @@ interface TableDisplayProps extends Pick<LemonSelectProps<ChartDisplayType>, 'diexport const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element => {const { setVisualizationType } = useActions(dataVisualizationLogic)const { autoVisualizationType, columns, numericalColumns, visualizationType } = useValues(dataVisualizationLogic)+ const { featureFlags } = useValues(featureFlagLogic)const canDisplayContinuousChart = columns.length > 1 && numericalColumns.length > 0// Both scatter axes are numeric measures, so one numeric column can't fill both.@@ -119,6 +122,17 @@ export const TableDisplay = ({ disabledReason }: TableDisplayProps): JSX.Element? 'Requires at least two numeric columns, one for each axis': undefined,},+ ...(featureFlags[FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT]+ ? [+ {+ value: ChartDisplayType.BoxPlot,+ icon: <IconGraph />,+ label: 'Box plot',+ disabledReason:+ numericalColumns.length < 6 ? 'Requires six numeric summary columns' : undefined,+ },+ ]+ : []),{value: ChartDisplayType.TwoDimensionalHeatmap,icon: <IconHeatmap />,diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsxindex 1b932ec36ee9..99e25bd1d5cf 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx@@ -35,6 +35,7 @@ import { ElapsedTime } from '../DataNode/ElapsedTime'import { Reload } from '../DataNode/Reload'import { QueryFeature } from '../DataTable/queryFeatures'import { PieChart } from './Components/Charts/PieChart'+import { SqlBoxPlot } from './Components/Charts/SqlBoxPlot'import { SqlChart } from './Components/Charts/SqlChart'import { SqlScatterGraph } from './Components/Charts/SqlScatterGraph'import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'@@ -181,6 +182,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXisChartSettingsPanelOpen,xData,yData,+ columns,chartSettings,dashboardId,dataVisualizationProps,@@ -299,6 +301,17 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSXpresetChartHeight={presetChartHeight}/>)+ } else if (effectiveVisualizationType === ChartDisplayType.BoxPlot) {+ const rows = ('results' in response ? response.results : 'result' in response ? response.result : []) ?? []+ component = (+ <SqlBoxPlot+ rows={Array.isArray(rows) ? rows : []}+ columns={columns}+ chartSettings={chartSettings}+ analyticsKey={dataVisualizationProps.key}+ presetChartHeight={presetChartHeight}+ />+ )} else if (effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {component = <TwoDimensionalHeatmap allowSorting={!(props.embedded && readOnly)} />} else if (effectiveVisualizationType === ChartDisplayType.BoldNumber) {diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.tsindex 5941e85a2d65..aeb1a333c80d 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts@@ -136,6 +136,40 @@ describe('dataVisualizationLogic', () => {})})+ it('auto-maps box plot columns when the chart is selected', async () => {+ dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId }).actions.setResponse({+ columns: ['bucket', 'series', 'min', 'p25', 'median', 'mean', 'p75', 'max'],+ types: [+ ['bucket', 'Date'],+ ['series', 'String'],+ ['min', 'Float64'],+ ['p25', 'Float64'],+ ['median', 'Float64'],+ ['mean', 'Float64'],+ ['p75', 'Float64'],+ ['max', 'Float64'],+ ],+ results: [['2026-01-01', 'Free', 1, 2, 3, 4, 5, 6]],+ })++ logic.actions.setVisualizationType(ChartDisplayType.BoxPlot)++ await expectLogic(logic).toMatchValues({+ chartSettings: expect.objectContaining({+ boxPlot: {+ xAxisColumn: 'bucket',+ seriesColumn: 'series',+ minColumn: 'min',+ p25Column: 'p25',+ medianColumn: 'median',+ meanColumn: 'mean',+ p75Column: 'p75',+ maxColumn: 'max',+ },+ }),+ })+ })+it('resets axes when y-axis columns are no longer numerical', async () => {const dataNode = dataNodeLogic({ key: testKey, query: defaultQuery.source, dataNodeCollectionId })diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.tsindex 15008ebc1f94..ed05870a686f 100644--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts@@ -59,6 +59,7 @@ import type {} from '../../schema/schema-general'import { dataNodeLogic } from '../DataNode/dataNodeLogic'import { QueryFeature, getQueryFeatures } from '../DataTable/queryFeatures'+import { getAutoBoxPlotSettings } from './Components/Charts/sqlBoxPlotAdapter'import { ColumnScalar, FORMATTING_TEMPLATES } from './types'export enum SideBarTab {@@ -376,6 +377,13 @@ const mergeChartSettings = (state: ChartSettings, settings: ChartSettings): Char...settings.scatter,}: undefined,+ boxPlot:+ state.boxPlot || settings.boxPlot+ ? {+ ...state.boxPlot,+ ...settings.boxPlot,+ }+ : undefined,leftYAxisSettings:state.leftYAxisSettings || settings.leftYAxisSettings? {@@ -1854,6 +1862,12 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([applyScatterXAxis(actions, values.columns, values.selectedXAxis, values.selectedYAxis)}+ if (visualizationType === ChartDisplayType.BoxPlot) {+ actions.updateChartSettings({+ boxPlot: getAutoBoxPlotSettings(values.columns, values.chartSettings.boxPlot),+ })+ }+const isAutoHeatmap =visualizationType === ChartDisplayType.Auto &&getAutoVisualizationType(values.columns, values.response) === ChartDisplayType.TwoDimensionalHeatmap@@ -1971,6 +1985,12 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([applyAutoHeatmapSettings(actions, value, values.chartSettings.heatmap ?? {})}+ if (values.effectiveVisualizationType === ChartDisplayType.BoxPlot) {+ actions.updateChartSettings({+ boxPlot: getAutoBoxPlotSettings(value, values.chartSettings.boxPlot),+ })+ }+// The generic setup above only lands a numeric x for a scatter by luck (a DATE column or a// non-numeric first column). Resolve it explicitly so an all-numeric query, a column change,// or a persisted/assistant-created scatter still gets a plottable x axis.diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 5c08d49f3abb..f07cb5b080b4 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -6051,6 +6051,39 @@"required": ["day", "label", "min", "p25", "median", "p75", "max", "mean"],"type": "object"},+ "BoxPlotSettings": {+ "additionalProperties": false,+ "properties": {+ "excludeOutliers": {+ "type": "boolean"+ },+ "maxColumn": {+ "type": "string"+ },+ "meanColumn": {+ "type": "string"+ },+ "medianColumn": {+ "type": "string"+ },+ "minColumn": {+ "type": "string"+ },+ "p25Column": {+ "type": "string"+ },+ "p75Column": {+ "type": "string"+ },+ "seriesColumn": {+ "type": ["string", "null"]+ },+ "xAxisColumn": {+ "type": ["string", "null"]+ }+ },+ "type": "object"+ },"Breakdown": {"additionalProperties": false,"properties": {@@ -15810,6 +15843,9 @@"ChartSettings": {"additionalProperties": false,"properties": {+ "boxPlot": {+ "$ref": "#/definitions/BoxPlotSettings"+ },"chartStyle": {"$ref": "#/definitions/ChartStyle","description": "Chart rendering style overrides (line shape). Only applies to line and area charts."diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex c9f01991806b..745f2f797f65 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1307,6 +1307,18 @@ export interface ScatterChartSettings {showBestFit?: boolean}+export interface BoxPlotSettings {+ xAxisColumn?: string | null+ seriesColumn?: string | null+ minColumn?: string+ p25Column?: string+ medianColumn?: string+ meanColumn?: string+ p75Column?: string+ maxColumn?: string+ excludeOutliers?: boolean+}+export interface YAxisSettings {label?: stringscale?: 'linear' | 'logarithmic'@@ -1341,6 +1353,7 @@ export interface ChartSettings {heatmap?: HeatmapSettingspie?: PieChartSettingsscatter?: ScatterChartSettings+ boxPlot?: BoxPlotSettings/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */resultCustomizations?: Record<string, ResultCustomizationByValue>/** Chart rendering style overrides (line shape). Only applies to line and area charts. */diff --git a/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx b/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsxnew file mode 100644index 000000000000..87d7ccea29b7--- /dev/null+++ b/frontend/src/scenes/insights/stories/SQLBoxPlot.stories.tsx@@ -0,0 +1,109 @@+import { Decorator, Meta, StoryObj } from '@storybook/react'+import { waitFor } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'+import { useEffect, useRef } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'++import { mswDecorator } from '~/mocks/browser'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import __sqlBoxPlot from '../../../mocks/fixtures/api/projects/team_id/insights/sqlBoxPlot.json'++const availableSources = {+ Postgres: { name: 'Postgres', iconPath: '/static/services/postgres.png', fields: [], caption: '', featured: true },+ Stripe: { name: 'Stripe', iconPath: '/static/services/stripe.png', fields: [], caption: '', featured: true },+ GoogleAds: {+ name: 'GoogleAds',+ iconPath: '/static/services/google-ads.png',+ fields: [],+ caption: '',+ featured: true,+ },+}++type Story = StoryObj<{}>++const grantWarehouseAccess: Decorator = function GrantWarehouseAccess(Story): JSX.Element {+ const appContext = (window as any).POSTHOG_APP_CONTEXT+ const originalAccess = useRef<unknown>()+ if (appContext && originalAccess.current === undefined) {+ originalAccess.current = appContext.resource_access_control+ appContext.resource_access_control = {+ ...appContext.resource_access_control,+ [AccessControlResourceType.WarehouseObjects]: AccessControlLevel.Editor,+ }+ }+ useEffect(+ () => () => {+ if (appContext) {+ appContext.resource_access_control = originalAccess.current+ }+ },+ [appContext]+ )+ return <Story />+}++const meta: Meta = {+ title: 'Scenes-App/Insights/SQLBoxPlot',+ parameters: {+ layout: 'fullscreen',+ featureFlags: [FEATURE_FLAGS.SQL_BOX_PLOT_INSIGHT],+ testOptions: {+ snapshotBrowsers: ['chromium'],+ viewport: { width: 1300, height: 720 },+ waitForSelector: '[data-attr="sql-box-plot"]',+ },+ viewMode: 'story',+ mockDate: '2026-02-02',+ },+ decorators: [+ grantWarehouseAccess,+ mswDecorator({+ get: {+ '/api/projects/:team_id/groups_types': [],+ '/api/projects/:team_id/query_tab_state/user': () => [200, null],+ '/api/projects/:team_id/external_data_sources/connections': [],+ '/api/projects/:team_id/external_data_sources/direct_connection_options': [],+ '/api/environments/:team_id/external_data_sources/wizard': availableSources,+ },+ }),+ ],+}++export default meta++export const GroupedSeries: Story = createInsightStory(__sqlBoxPlot as any)++export const EditOptions: Story = {+ render: createInsightStory(__sqlBoxPlot as any, 'edit'),+ parameters: {+ ...meta.parameters,+ testOptions: {+ ...meta.parameters?.testOptions,+ waitForSelector: '[data-attr="box-plot-minColumn"]',+ },+ },+ play: async ({ canvasElement }): Promise<void> => {+ await waitFor(+ async () => {+ if (canvasElement.querySelector('[data-attr="box-plot-minColumn"]')) {+ return+ }+ const settingsButton = canvasElement.querySelector<HTMLElement>(+ '[data-attr="sql-editor-visualization-settings-button"]'+ )+ if (!settingsButton) {+ throw new Error('Visualization settings button not ready')+ }+ await userEvent.click(settingsButton)+ if (!canvasElement.querySelector('[data-attr="box-plot-minColumn"]')) {+ throw new Error('Box plot settings not ready')+ }+ },+ { timeout: 10_000 }+ )+ },+}diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex cc377af56ab9..e5a469dc90ec 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -15,7 +15,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha| TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes || TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) || PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel`; `sliceValueDisplay` picks what the numeric line holds — `'value'`, `'percent'`, or `'both'` for `352 (18.4%)` (defaults to `'percent'` when `isPercent` is set, else `'value'`); `config.legend` for the built-in legend (a toggled-off slice is removed and the rest rescale to the full circle) |-| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |+| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label; supports `config.legend` for grouped series || Heatmap | 2D density grid (e.g. latency over time) — `xLabels` × `yLabels` (row 0 at the bottom), `cells[row][col]` counts → color intensity on one accent (log ramp by default, `colorScale: 'linear'` to opt out); single-cell tooltip resolved from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }` || Sparkline | Tiny inline trend, no axes — a gradient-filled line (default) or stacked bars via `type: 'bar'`; a flat `number[]` + `color`, or full `series` for multi-series; tooltip off by default, opt in with a `tooltip` render prop || MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.stories.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.stories.tsxindex c4591ae005d2..ffdac25973aa 100644--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.stories.tsx+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.stories.tsx@@ -92,7 +92,12 @@ export const MultiSeriesGrouped: Story = {const theme = useReactiveTheme()return (<Stage>- <BoxPlot series={TWO_SERIES} labels={DAYS} theme={theme} config={{ showGrid: true }} />+ <BoxPlot+ series={TWO_SERIES}+ labels={DAYS}+ theme={theme}+ config={{ showGrid: true, legend: { show: true, position: 'top' } }}+ /></Stage>)},diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsxindex 881d457b6efc..c7b8ba156ad1 100644--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.test.tsx@@ -37,6 +37,14 @@ describe('BoxPlot', () => {expect(chart.seriesCount).toBe(2)})+ it('renders a legend when requested', () => {+ const { container } = renderHogChart(+ <BoxPlot series={TWO_SERIES} labels={LABELS} theme={THEME} config={{ legend: { show: true } }} />+ )+ const buttons = container.querySelectorAll('[data-attr="hog-chart-box-plot-legend"] button')+ expect(Array.from(buttons, (button) => button.textContent)).toEqual(['A', 'B'])+ })+it('renders y-axis ticks for the value range that spans whiskers', () => {const series: BoxPlotSeries[] = [{diff --git a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsxindex 7a24009543d5..8549d50d15bf 100644--- a/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx+++ b/packages/quill/packages/charts/src/charts/BoxPlot/BoxPlot.tsx@@ -1,14 +1,25 @@import React, { useCallback, useMemo } from 'react'-import { drawBoxes, drawBoxHighlight, drawGrid, type DrawContext } from '../../core/canvas-renderer'+import { ChartLegend } from '../../components/Legend/ChartLegend'+import { useChartLegend } from '../../components/Legend/useChartLegend'+import {+ drawAxes,+ drawBoxes,+ drawBoxHighlight,+ drawGrid,+ resolveAxisLineColor,+ type DrawContext,+} from '../../core/canvas-renderer'import { Chart } from '../../core/Chart'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'import { dimColor } from '../../core/color-utils'import { createBarScales, type BarScaleSet, yTickCountForHeight } from '../../core/scales'+import { resolveAxisLines } from '../../core/types'import type {ChartConfig,ChartDimensions,ChartDrawArgs,+ ChartLegendConfig,ChartScales,ChartTheme,CreateScalesFn,@@ -50,6 +61,7 @@ export type BoxPlotTooltipContext<Meta = unknown> = TooltipContext<BoxPlotAdapte* horizontal mode — so it's omitted from the consumer-visible config to avoid silently* ignored values. */export interface BoxPlotConfig extends Omit<ChartConfig, 'axisOrientation'> {+ legend?: ChartLegendConfig/** Mean marker radius in CSS pixels. Defaults to 3. */meanRadius?: number/** Whisker cap width as a fraction of the box width. Defaults to 0.6. */@@ -115,12 +127,13 @@ function BoxPlotInner<Meta = unknown>({const {yScaleType = 'linear',showGrid = false,+ showAxisLines = false,meanRadius = 3,whiskerCapRatio = 0.6,boxStrokeWidth = 1.5,} = config ?? {}-- const grouped = series.filter((s) => !s.visibility?.excluded).length > 1+ const { x: xAxisLine, y: yAxisLine } = resolveAxisLines(showAxisLines)+ const axisLines = useMemo(() => ({ x: xAxisLine, y: yAxisLine }), [xAxisLine, yAxisLine])const adaptedSeries = useMemo<Series<BoxPlotAdaptedMeta<Meta>>[]>(() =>@@ -138,19 +151,22 @@ function BoxPlotInner<Meta = unknown>({[series, labels.length])+ const { visibleSeries, legendProps } = useChartLegend(adaptedSeries, theme, config?.legend)+ const grouped = visibleSeries.filter((s) => !s.visibility?.excluded).length > 1+/** Synthetic series carrying min/max samples so the y-domain spans every whisker, not just- * the medians on `adaptedSeries.data`. Fed to `createBarScales` (as `stackedSeries`) for- * the d3 scale and to `Chart` (as `valueRangeSeries`) for `useChartMargins` tick sizing —- * one source, two call sites. */+ * the medians. Fed to `createBarScales` (as `stackedSeries`) for the d3 scale and to `Chart`+ * (as `valueRangeSeries`) for `useChartMargins` tick sizing, so hidden series cannot affect+ * either calculation. */const valueRangeSeries = useMemo<Series[]>(() => {const out: Series[] = []- for (const s of series) {+ for (const s of visibleSeries) {if (s.visibility?.excluded) {continue}const mins: number[] = []const maxs: number[] = []- for (const datum of s.data) {+ for (const datum of s.meta?.datums ?? []) {if (!datum) {continue}@@ -169,7 +185,7 @@ function BoxPlotInner<Meta = unknown>({}}return out- }, [series])+ }, [visibleSeries])const { datumsByKey, seriesByKey } = useMemo(() => {const datums = new Map<string, (BoxPlotDatum | null)[]>()@@ -237,11 +253,13 @@ function BoxPlotInner<Meta = unknown>({labels: drawLabels,}+ const axisLineStyle = axisLines.x || axisLines.yif (showGrid) {drawGrid(baseDrawCtx, {gridColor: theme.gridColor,gridDash: theme.gridDashPattern,orientation: 'vertical',+ frame: !axisLineStyle,})}@@ -269,8 +287,16 @@ function BoxPlotInner<Meta = unknown>({lineWidth: boxStrokeWidth,})}++ if (axisLineStyle) {+ drawAxes(baseDrawCtx, {+ axisColor: resolveAxisLineColor(theme),+ xLine: axisLines.x,+ yLine: axisLines.y,+ })+ }},- [showGrid, meanRadius, whiskerCapRatio, boxStrokeWidth]+ [showGrid, axisLines, meanRadius, whiskerCapRatio, boxStrokeWidth])const drawHover = useCallback(@@ -371,21 +397,23 @@ function BoxPlotInner<Meta = unknown>({)return (- <Chart<BoxPlotAdaptedMeta<Meta>>- series={adaptedSeries}- labels={labels}- config={{ ...config, axisOrientation: 'vertical' }}- theme={theme}- createScales={createScales}- drawStatic={drawStatic}- drawHover={drawHover}- tooltip={renderTooltip}- onPointClick={onPointClick}- valueRangeSeries={valueRangeSeries.length > 0 ? valueRangeSeries : undefined}- className={className}- dataAttr={dataAttr}- >- {children}- </Chart>+ <ChartLegend {...legendProps} legendDataAttr="hog-chart-box-plot-legend">+ <Chart<BoxPlotAdaptedMeta<Meta>>+ series={visibleSeries}+ labels={labels}+ config={{ ...config, axisOrientation: 'vertical' }}+ theme={theme}+ createScales={createScales}+ drawStatic={drawStatic}+ drawHover={drawHover}+ tooltip={renderTooltip}+ onPointClick={onPointClick}+ valueRangeSeries={valueRangeSeries.length > 0 ? valueRangeSeries : undefined}+ className={className}+ dataAttr={dataAttr}+ >+ {children}+ </Chart>+ </ChartLegend>)}diff --git a/posthog/schema.py b/posthog/schema.pyindex abbad6a784c7..a838cce3fabd 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -888,6 +888,21 @@ class BiasRisk(BaseModel):)+class BoxPlotSettings(BaseModel):+ model_config = ConfigDict(+ extra="forbid",+ )+ excludeOutliers: bool | None = None+ maxColumn: str | None = None+ meanColumn: str | None = None+ medianColumn: str | None = None+ minColumn: str | None = None+ p25Column: str | None = None+ p75Column: str | None = None+ seriesColumn: str | None = None+ xAxisColumn: str | None = None++class BreakdownValue(BaseModel):model_config = ConfigDict(extra="forbid",@@ -15080,6 +15095,7 @@ class ChartSettings(BaseModel):model_config = ConfigDict(extra="forbid",)+ boxPlot: BoxPlotSettings | None = NonechartStyle: ChartStyle | None = Field(default=None,description=("Chart rendering style overrides (line shape). Only applies to line and area charts."),diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex f69379c62e56..30d7db58b423 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -8625,6 +8625,18 @@ export interface DataTableNodeApi {version?: number | null}+export interface BoxPlotSettingsApi {+ excludeOutliers?: boolean | null+ maxColumn?: string | null+ meanColumn?: string | null+ medianColumn?: string | null+ minColumn?: string | null+ p25Column?: string | null+ p75Column?: string | null+ seriesColumn?: string | null+ xAxisColumn?: string | null+}+export interface HeatmapGradientStopApi {color: stringvalue: number@@ -8771,6 +8783,7 @@ export interface ChartAxisApi {export type ChartSettingsApiResultCustomizations = { [key: string]: ResultCustomizationByValueApi } | nullexport interface ChartSettingsApi {+ boxPlot?: BoxPlotSettingsApi | null/** Chart rendering style overrides (line shape). Only applies to line and area charts. */chartStyle?: ChartStyleApi | nullgoalLines?: GoalLineApi[] | nulldiff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.pyindex 7754e702f8d6..61fc08b3335e 100644--- a/products/product_analytics/backend/presentation/insight.py+++ b/products/product_analytics/backend/presentation/insight.py@@ -1522,7 +1522,16 @@ class MCPInsightSerializer(InsightSerializer):# Already-wrapped node → use as-isfor wrapped_cls in (schema.DataVisualizationNode, schema.InsightVizNode):try:- return wrapped_cls.model_validate(value).model_dump(exclude_none=True, mode="json")+ wrapped_node = wrapped_cls.model_validate(value)+ normalized_query = wrapped_node.model_dump(exclude_none=True, mode="json")+ if isinstance(wrapped_node, schema.DataVisualizationNode):+ box_plot = wrapped_node.chartSettings.boxPlot if wrapped_node.chartSettings else None+ if box_plot is not None:+ normalized_box_plot = normalized_query.setdefault("chartSettings", {}).setdefault("boxPlot", {})+ for field in ("xAxisColumn", "seriesColumn"):+ if field in box_plot.model_fields_set and getattr(box_plot, field) is None:+ normalized_box_plot[field] = None+ return normalized_queryexcept PydanticValidationError:passdiff --git a/products/product_analytics/backend/tests/api/test_insight_query.py b/products/product_analytics/backend/tests/api/test_insight_query.pyindex 0ef7364fc39c..4dfbcb1f03d5 100644--- a/products/product_analytics/backend/tests/api/test_insight_query.py+++ b/products/product_analytics/backend/tests/api/test_insight_query.py@@ -2,6 +2,8 @@ from typing import get_argsfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status@@ -12,11 +14,27 @@ from products.product_analytics.backend.facade.models import Insightfrom products.product_analytics.backend.presentation.insight import (AUTO_WRAPPED_INSIGHT_QUERY_KINDS,BARE_RENDERED_INSIGHT_VIZ_SOURCE_KINDS,+ MCPInsightSerializer,)from ee.api.test.base import LicensedTestMixin+class TestMCPInsightSerializer(SimpleTestCase):+ def test_preserves_explicit_box_plot_grouping_nulls(self) -> None:+ normalized_query = MCPInsightSerializer().validate_query(+ {+ "kind": "DataVisualizationNode",+ "source": {"kind": "HogQLQuery", "query": "select 1"},+ "chartSettings": {"boxPlot": {"xAxisColumn": None, "seriesColumn": None}},+ }+ )++ box_plot = normalized_query["chartSettings"]["boxPlot"]+ assert box_plot["xAxisColumn"] is None+ assert box_plot["seriesColumn"] is None++class TestInsight(ClickhouseTestMixin, LicensedTestMixin, APIBaseTest, QueryMatchingTest):maxDiff = Nonediff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 64a689ea4c0c..50deeae9c378 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -7787,6 +7787,18 @@ export interface DataTableNodeApi {version?: number | null}+export interface BoxPlotSettingsApi {+ excludeOutliers?: boolean | null+ maxColumn?: string | null+ meanColumn?: string | null+ medianColumn?: string | null+ minColumn?: string | null+ p25Column?: string | null+ p75Column?: string | null+ seriesColumn?: string | null+ xAxisColumn?: string | null+}+export interface HeatmapGradientStopApi {color: stringvalue: number@@ -7933,6 +7945,7 @@ export interface ChartAxisApi {export type ChartSettingsApiResultCustomizations = { [key: string]: ResultCustomizationByValueApi } | nullexport interface ChartSettingsApi {+ boxPlot?: BoxPlotSettingsApi | null/** Chart rendering style overrides (line shape). Only applies to line and area charts. */chartStyle?: ChartStyleApi | nullgoalLines?: GoalLineApi[] | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 178d85d3fa12..ef30cf19f9af 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8468,6 +8468,18 @@ export namespace Schemas {version?: number | null;}+ export interface BoxPlotSettings {+ excludeOutliers?: boolean | null;+ maxColumn?: string | null;+ meanColumn?: string | null;+ medianColumn?: string | null;+ minColumn?: string | null;+ p25Column?: string | null;+ p75Column?: string | null;+ seriesColumn?: string | null;+ xAxisColumn?: string | null;+ }+export interface HeatmapGradientStop {color: string;value: number;@@ -8623,6 +8635,7 @@ export namespace Schemas {export type ChartSettingsResultCustomizations = {[key: string]: ResultCustomizationByValue} | null;export interface ChartSettings {+ boxPlot?: BoxPlotSettings | null;/** Chart rendering style overrides (line shape). Only applies to line and area charts. */chartStyle?: ChartStyle | null;goalLines?: GoalLine[] | null;