: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(sql insights): render trend lines via quill-charts (#64827)
Sam Pennington2cf36ace42d2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3b090084587b..8223edff6a9c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5568,6 +5568,10 @@ snapshots:hash: v1.k794b7964.486007121c9a82df768c7474916477a3e46e69b49b83401da0fa51bdd6279300.UTIVI6M2LJyrUd-l5ym6crCCsGmzZ8xrdtoI1TfBrDAscenes-app-insights-sqllinechart--sql-line-chart-breakdown--light:hash: v1.k794b7964.c11566cd09e1284b866c92a29482b1fdc6cf206b0b5e1fb46f2e553c19549a57.Xk4vP5_LzV-5_uSJWDNKR9YIEzfduyKuetdlsGn3FIs+ scenes-app-insights-sqllinechart--sql-line-chart-trend-line-quill--dark:+ hash: v1.k794b7964.576ceec72a168753a7fb85e57c7e1c7f45660ae22926efcd3c1ab99141e5508d.AZaZxEtUZgaYwWWuutcC6gIFyyRh3cH7CFmVuquQOeE+ scenes-app-insights-sqllinechart--sql-line-chart-trend-line-quill--light:+ hash: v1.k794b7964.00048bccb76c666facae706fc4884b75e8bf6caf39329fb2fb77d8ce8820829c.CkTMrfpT9rk-hAjJY_sB8dNew8PsEo_CGQSlg6u36NMscenes-app-insights-trendsboxplot--trends-box-plot--dark:hash: v1.k794b7964.9421d408ac158259cf9c8120e5a4df7e79c87c38f48ff2fb096528ab4c21ccaa.kTH1yU4rwh9ATB6Xt9KnTZi2ZhBZM2uG_hsgwQ47kVYscenes-app-insights-trendsboxplot--trends-box-plot--light:diff --git a/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlLineChartTrendLine.json b/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlLineChartTrendLine.jsonnew file mode 100644index 000000000000..f5d5cb01157a--- /dev/null+++ b/frontend/src/mocks/fixtures/api/projects/team_id/insights/sqlLineChartTrendLine.json@@ -0,0 +1,121 @@+{+ "id": 22,+ "short_id": "qJ3UMu6h",+ "name": "SQL with trend line",+ "derived_name": null,+ "filters": {},+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT\n toStartOfMonth(timestamp) AS month,\n count() AS pageviews\nFROM events\nGROUP BY month\nORDER BY month"+ },+ "display": "ActionsLineGraph",+ "chartSettings": {+ "xAxis": {+ "column": "month"+ },+ "yAxis": [+ {+ "column": "pageviews",+ "settings": {+ "display": {+ "trendLine": true+ },+ "formatting": {+ "prefix": "",+ "suffix": ""+ }+ }+ }+ ]+ },+ "tableSettings": {+ "columns": [+ {+ "column": "month",+ "settings": {+ "formatting": {+ "prefix": "",+ "suffix": ""+ }+ }+ },+ {+ "column": "pageviews",+ "settings": {+ "display": {+ "trendLine": true+ },+ "formatting": {+ "prefix": "",+ "suffix": ""+ }+ }+ }+ ]+ }+ },+ "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": [+ ["2025-10-01", 1520],+ ["2025-11-01", 6775],+ ["2025-12-01", 9162],+ ["2026-01-01", 12520],+ ["2026-02-01", 14192],+ ["2026-03-01", 19208]+ ],+ "hasMore": false,+ "columns": ["month", "pageviews"],+ "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 toStartOfMonth(timestamp) AS month,\n count() AS pageviews\nFROM\n events\nGROUP BY\n month\nORDER BY\n month ASC\nLIMIT 101\nOFFSET 0",+ "types": [+ ["month", "Date"],+ ["pageviews", "UInt64"]+ ],+ "resolved_date_range": null,+ "alerts": [],+ "last_viewed_at": "2026-03-04T16:11:30.018817Z",+ "tags": [],+ "filters_hash": "cache_1_eb04b61fff884f29a4c74600aea3684fb7769ff1fa6e0d4e59865ee187c3b58c"+}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsxindex dd2812572dee..3e002e61baa9 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx@@ -13,8 +13,8 @@ const handleChartError = makeChartErrorHandler('sql-line-chart')/*** SQL line/area graph rendered via @posthog/quill-charts, gated behind the- * `product-analytics-quill-sql-charts` flag (see {@link LineGraph}). Handles line, area, and goal- * lines; everything else falls back to the legacy chart.js path. The tooltip is quill's+ * `product-analytics-quill-sql-charts` flag (see {@link LineGraph}). Handles line, area, goal+ * lines, and trend lines; everything else falls back to the legacy chart.js path. The tooltip is quill's* DefaultTooltip extended to format each row with its column's own settings and to show a total row.*/export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.tsindex 81ec8f610bb6..324bed679000 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts@@ -1,3 +1,5 @@+import { type TrendLineConfig } from '@posthog/quill-charts'+import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'@@ -7,10 +9,12 @@ import { LineGraphProps } from './LineGraph'import {AREA_FILL_OPACITY,MAX_SERIES,+ type SqlLineYSeries,barLayoutForDisplay,buildBarChartConfig,buildLineChartConfig,buildSeries,+ buildTrendLineConfigs,canRenderSqlBarGraph,canRenderSqlLineGraph,capYSeriesData,@@ -61,9 +65,12 @@ describe('sqlLineGraphAdapter', () => {expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)})- it('falls back when any series has a trend line', () => {+ it.each([+ ['line graph', ChartDisplayType.ActionsLineGraph],+ ['area graph', ChartDisplayType.ActionsAreaGraph],+ ])('renders trend-line series natively rather than falling back for a %s', (_name, visualizationType) => {const yData = [ySeries('a', [1], { display: { trendLine: true } })]- expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)+ expect(canRenderSqlLineGraph(baseProps({ visualizationType, yData }))).toBe(true)})it('falls back when any series targets the right y-axis', () => {@@ -92,8 +99,12 @@ describe('sqlLineGraphAdapter', () => {)})- it('falls back when any series has a trend line', () => {- const yData = [ySeries('a', [1], { display: { trendLine: true } })]+ // Trend lines force the legacy fallback on the bar path because quill's+ // TimeSeriesBarChart has no trend-line support — keep this until it does.+ it.each([+ ['a plain series', [ySeries('a', [1], { display: { trendLine: true } })]],+ ['a breakdown series', [breakdownSeries('chrome', [1], { display: { trendLine: true } })]],+ ])('falls back when %s has a trend line', (_name, yData) => {expect(canRenderSqlBarGraph(baseProps({ visualizationType: ChartDisplayType.ActionsBar, yData }))).toBe(false)@@ -203,6 +214,58 @@ describe('sqlLineGraphAdapter', () => {})})+ describe('buildTrendLineConfigs', () => {+ it.each<[string, SqlLineYSeries[] | null | undefined, TrendLineConfig[]]>([+ [+ 'one linear config per opting-in series, keyed by original index',+ [+ ySeries('a', [1], { display: { trendLine: true } }),+ ySeries('b', [2]),+ ySeries('c', [3], { display: { trendLine: true } }),+ ],+ [+ { seriesKey: 'a-0', kind: 'linear' },+ { seriesKey: 'c-2', kind: 'linear' },+ ],+ ],+ ['none when no series opts in', [ySeries('a', [1]), ySeries('b', [2])], []],+ ['none for missing data', undefined, []],+ ['none for null data', null, []],+ [+ 'breakdown trend lines keyed by breakdown value',+ [breakdownSeries('chrome', [1], { display: { trendLine: true } })],+ [{ seriesKey: 'chrome', kind: 'linear' }],+ ],+ ])('builds %s', (_name, ySeriesData, expected) => {+ expect(buildTrendLineConfigs(ySeriesData)).toEqual(expected)+ })++ it('keys each trend line to the series buildSeries assigns', () => {+ const yData = [+ ySeries('a', [1]),+ ySeries('b', [2], { display: { trendLine: true } }),+ breakdownSeries('chrome', [3], { display: { trendLine: true } }),+ ]+ const seriesKeys = buildSeries(yData, ChartDisplayType.ActionsLineGraph).map((s) => s.key)+ const trendLineKeys = buildTrendLineConfigs(yData).map((t) => t.seriesKey)+ // Both derive from getSeriesKey on the same array, so the trend lines are the opt-in subset.+ expect(seriesKeys).toEqual(['a-0', 'b-1', 'chrome'])+ expect(trendLineKeys).toEqual(['b-1', 'chrome'])+ })++ it('uses array-position indexing, so keys stay aligned with buildSeries however the cap slices', () => {+ const yData = [+ ySeries('a', [1]),+ ySeries('b', [2], { display: { trendLine: true } }),+ ySeries('c', [3]),+ ySeries('d', [4], { display: { trendLine: true } }),+ ]+ const seriesKeys = buildSeries(yData, ChartDisplayType.ActionsLineGraph).map((s) => s.key)+ const trendLineKeys = buildTrendLineConfigs(yData).map((t) => t.seriesKey)+ expect(trendLineKeys).toEqual([seriesKeys[1], seriesKeys[3]])+ })+ })+describe('formatSqlSeriesValue', () => {it('applies the column settings and stringifies the result', () => {expect(formatSqlSeriesValue(1200, { formatting: { prefix: '$' } })).toBe('$1200')@@ -261,6 +324,18 @@ describe('sqlLineGraphAdapter', () => {expect(config.goalLines).toHaveLength(1)expect(config.goalLines?.[0]).toMatchObject({ value: 100, label: 'Target' })})++ it.each<[string, SqlLineYSeries[], TrendLineConfig[]]>([+ [+ 'wires trend lines from series that opt in, keyed to match buildSeries',+ [ySeries('a', [1, 2], { display: { trendLine: true } }), ySeries('b', [3, 4])],+ [{ seriesKey: 'a-0', kind: 'linear' }],+ ],+ ['omits trend lines when no series opts in', [ySeries('a', [1, 2]), ySeries('b', [3, 4])], []],+ ])('%s', (_name, ySeriesData, expected) => {+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC', ySeriesData })+ expect(config.trendLines).toEqual(expected)+ })})describe('buildBarChartConfig', () => {@@ -282,5 +357,17 @@ describe('sqlLineGraphAdapter', () => {})expect(config.yAxis?.scale).toBe('linear')})++ it('never emits trend lines (quill bar charts have no trend-line support)', () => {+ const ySeriesData = [ySeries('a', [1, 2], { display: { trendLine: true } })]+ const config = buildBarChartConfig({+ xData: dateXData,+ chartSettings: {},+ timezone: 'UTC',+ visualizationType: ChartDisplayType.ActionsBar,+ ySeriesData,+ })+ expect('trendLines' in config).toBe(false)+ })})})diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.tsindex b1a55f44fa0a..7e9c04ed4a38 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts@@ -4,6 +4,7 @@ import {type Series,type TimeSeriesBarChartConfig,type TimeSeriesLineChartConfig,+ type TrendLineConfig,type XAxisConfig,type YAxisConfig,createXAxisTickCallback,@@ -33,8 +34,21 @@ const getSeriesLabel = (series: SqlLineYSeries): string => ('name' in series ? sconst getSeriesKey = (series: SqlLineYSeries, index: number): string =>'breakdownValue' in series ? series.breakdownValue : `${series.column.name}-${index}`+/** Shares {@link getSeriesKey} with {@link buildSeries} so each trend line's `seriesKey` matches its source series. */+export function buildTrendLineConfigs(ySeriesData: SqlLineYSeries[] | null | undefined): TrendLineConfig[] {+ if (!ySeriesData) {+ return []+ }+ return ySeriesData.reduce<TrendLineConfig[]>((configs, series, index) => {+ if (series.settings?.display?.trendLine) {+ configs.push({ seriesKey: getSeriesKey(series, index), kind: 'linear' })+ }+ return configs+ }, [])+}+/**- * Plain line/area charts — including goal lines — render here. Trend lines, mixed line/bar series,+ * Plain line/area charts — including goal lines and trend lines — render here. Mixed line/bar series* and right y-axis series aren't ported yet, so those fall back to the legacy chart.js path.*/export function canRenderSqlLineGraph(props: LineGraphProps): boolean {@@ -49,9 +63,6 @@ export function canRenderSqlLineGraph(props: LineGraphProps): boolean {if (yData?.some((series) => series.settings?.display?.displayType === 'bar')) {return false}- if (yData?.some((series) => series.settings?.display?.trendLine)) {- return false- }// quill applies a single tick formatter/scale to both gutters, so a right axis can't honor its// own settings yet — fall back to legacy rather than silently dropping those prefs.if (yData?.some((series) => series.settings?.display?.yAxisPosition === 'right')) {@@ -74,6 +85,7 @@ export function canRenderSqlBarGraph(props: LineGraphProps): boolean {) {return false}+ // quill's TimeSeriesBarChart has no trend-line support yet — fall back until it does.if (yData?.some((series) => series.settings?.display?.trendLine)) {return false}@@ -146,6 +158,7 @@ interface BuildConfigArgs {chartSettings: ChartSettingstimezone: stringgoalLines?: GoalLine[]+ ySeriesData?: SqlLineYSeries[] | null}export interface BuildBarConfigArgs extends BuildConfigArgs {@@ -185,11 +198,13 @@ export function buildLineChartConfig({chartSettings,timezone,goalLines,+ ySeriesData,}: BuildConfigArgs): TimeSeriesLineChartConfig {return {xAxis: buildXAxisConfig(xData, chartSettings, timezone),yAxis: buildYAxisConfig(chartSettings),goalLines: schemaGoalLinesToConfigs(goalLines),+ trendLines: buildTrendLineConfigs(ySeriesData),legend: buildLegendConfig(chartSettings),tooltip: { enabled: true, pinnable: true },}diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.tsindex 7c5d1e85d42b..88d3f6e69984 100644--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts@@ -51,8 +51,18 @@ export function useSqlChartModel<TConfig>(const theme = useMemo(() => buildTheme(), [isDarkModeOn])const config = useMemo(- () => (xData ? buildConfig({ xData, chartSettings, timezone, goalLines, visualizationType }) : undefined),- [xData, chartSettings, timezone, goalLines, visualizationType, buildConfig]+ () =>+ xData+ ? buildConfig({+ xData,+ chartSettings,+ timezone,+ goalLines,+ visualizationType,+ ySeriesData,+ })+ : undefined,+ [xData, chartSettings, timezone, goalLines, visualizationType, buildConfig, ySeriesData])if (!xData || !ySeriesData || series.length === 0 || !config) {diff --git a/frontend/src/scenes/insights/stories/SQLLineChart.stories.tsx b/frontend/src/scenes/insights/stories/SQLLineChart.stories.tsxindex 03155320779a..c9b6c0381894 100644--- a/frontend/src/scenes/insights/stories/SQLLineChart.stories.tsx+++ b/frontend/src/scenes/insights/stories/SQLLineChart.stories.tsx@@ -2,6 +2,7 @@ import { samplePersonProperties, sampleRetentionPeopleResponse } from 'scenes/inimport { Meta, StoryObj } from '@storybook/react'+import { FEATURE_FLAGS } from 'lib/constants'import { createInsightStory } from 'scenes/insights/__mocks__/createInsightScene'import { mswDecorator } from '~/mocks/browser'@@ -60,4 +61,16 @@ SQLLineChartBreakdown.parameters = {waitForSelector: '.DataVisualization canvas',},}++export const SQLLineChartTrendLineQuill: Story = createInsightStory(+ require('../../../mocks/fixtures/api/projects/team_id/insights/sqlLineChartTrendLine.json')+)+SQLLineChartTrendLineQuill.parameters = {+ ...meta.parameters,+ featureFlags: [FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS],+ testOptions: {+ ...meta.parameters?.testOptions,+ waitForSelector: '.DataVisualization canvas',+ },+}/* eslint-enable @typescript-eslint/no-var-requires */