: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
chore(endpoints): render usage trends chart via quill-charts directly (#70835)
Sam Pennington7212e776f9bd
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b1f6878b5629..608f6c249cf5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2068,6 +2068,10 @@ snapshots:hash: v1.k794b7964.2ff7288bc0a83e48485c4bd195b0cbceb06d5fd2218264cf63c49a72a90f00dd.tsDphOLaTwWpwAxmLc9dw4zQw9og1WJG5vjOGij2UeEdata-warehouse-query-history-modal--with-history--light:hash: v1.k794b7964.e72700e47a962bf542a5cb857bc6bd98e4d0ca8e280db1ce01c144d3d1b818ef.naPm1iXreZerb2g6MdHDraZEtV7nGY8bi_60zMzf70s+ endpoints-usagetrendschart--breakdown--dark:+ hash: v1.k794b7964.0f49030dacb9bee225faf49bd086e33ecdb005124fa98ac490cd8b10a27470a9.byjnYIJxyHM8PmD4dNpazdlTjYlvsWBXUQc7tM8ms2A+ endpoints-usagetrendschart--breakdown--light:+ hash: v1.k794b7964.99e7ba5520926109658e601921f2ff2ee8f2270671a9d35dc520e33f5cdb87b8.ewLUFPEIaHWeXrPE6ExJ8TC2_B4WJWX1SOETBVN2rTcerrortracking-assigneedisplay--all-displays--dark:hash: v1.k794b7964.8b92c8df5d800eb86b421fff454f46834eac7d0224872a85816e3db621d3b341.BWhYbKwsYPTyu8Z7A3tKkBgmCq8en82xZrQkJO8MIQUerrortracking-assigneedisplay--all-displays--light:diff --git a/products/endpoints/frontend/nodes/EndpointsUsageTrendsChart.stories.tsx b/products/endpoints/frontend/nodes/EndpointsUsageTrendsChart.stories.tsxnew file mode 100644index 000000000000..6eacdd2c8250--- /dev/null+++ b/products/endpoints/frontend/nodes/EndpointsUsageTrendsChart.stories.tsx@@ -0,0 +1,49 @@+import { Meta, StoryObj } from '@storybook/react'++import { Stage, playHoverAtFraction } from '@posthog/quill-charts/story-helpers'++import { EndpointsUsageTrendsChart } from './EndpointsUsageTrendsNode'++const meta: Meta<typeof EndpointsUsageTrendsChart> = {+ title: 'Endpoints/UsageTrendsChart',+ component: EndpointsUsageTrendsChart,+ parameters: {+ layout: 'centered',+ testOptions: { snapshotBrowsers: ['chromium'] },+ },+}+export default meta++type Story = StoryObj<typeof EndpointsUsageTrendsChart>++const DAYS = ['2026-07-01', '2026-07-02', '2026-07-03', '2026-07-04', '2026-07-05', '2026-07-06', '2026-07-07']++const REQUESTS_BY_ENDPOINT: Record<string, number[]> = {+ '/api/events': [210, 190, 260, 240, 300, 330, 290],+ '/api/persons': [90, 110, 80, 130, 120, 140, 100],+ '/api/insights': [40, 55, 60, 45, 70, 65, 80],+}++/**+ * One breakdown story, hovered mid-chart. Scaling and grouping are covered by+ * `endpointsUsageTrendsTransforms.test.ts`, so what a snapshot uniquely buys is that the chart+ * paints at all (it once rendered zero-height) plus the tooltip — whose date header and total row+ * no unit test reaches.+ */+export const Breakdown: Story = {+ render: () => (+ <Stage width={760}>+ <EndpointsUsageTrendsChart+ metric="requests"+ results={DAYS.flatMap((date, i) =>+ Object.entries(REQUESTS_BY_ENDPOINT).map(([breakdown, values]) => ({+ date,+ breakdown,+ value: values[i],+ }))+ )}+ />+ </Stage>+ ),+ play: async ({ canvasElement }) => await playHoverAtFraction(canvasElement, 0.5),+}diff --git a/products/endpoints/frontend/nodes/EndpointsUsageTrendsNode.tsx b/products/endpoints/frontend/nodes/EndpointsUsageTrendsNode.tsxindex fd02c4696df3..ca82c61cfb38 100644--- a/products/endpoints/frontend/nodes/EndpointsUsageTrendsNode.tsx+++ b/products/endpoints/frontend/nodes/EndpointsUsageTrendsNode.tsx@@ -1,26 +1,31 @@import { BuiltLogic, LogicWrapper, useValues } from 'kea'-import { useState } from 'react'+import { useMemo, useState } from 'react'import { LemonSkeleton } from '@posthog/lemon-ui'+import { TimeSeriesLineChart, type TimeSeriesLineChartConfig } from '@posthog/quill-charts'+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { teamLogic } from 'scenes/teamLogic'import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'-import { LineGraph } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'-import { AxisSeries } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'import {AnyResponseType,EndpointsUsageTrendsQuery,EndpointsUsageTrendsQueryResponse,} from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'-import { ChartDisplayType } from '~/types'+import { IntervalType } from '~/types'-type TrendsDataPoint = {- date: string- value: number- breakdown?: string-}+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'++import {+ type EndpointsUsageMetric,+ type TrendsDataPoint,+ transformDataForChart,+} from './endpointsUsageTrendsTransforms'++const handleChartError = makeChartErrorHandler('endpoints-usage-trends-chart')let uniqueNode = 0export function EndpointsUsageTrendsNode(props: {@@ -44,6 +49,7 @@ export function EndpointsUsageTrendsNode(props: {const { response, responseLoading } = useValues(logic)const queryResponse = response as EndpointsUsageTrendsQueryResponse | undefined+ const results = queryResponse?.results as TrendsDataPoint[] | undefinedif (responseLoading) {return (@@ -53,8 +59,6 @@ export function EndpointsUsageTrendsNode(props: {)}- const results = queryResponse?.results as TrendsDataPoint[] | undefined-if (!results || results.length === 0) {return (<div className="flex items-center justify-center h-60 border rounded bg-bg-light text-muted">@@ -63,197 +67,54 @@ export function EndpointsUsageTrendsNode(props: {)}- const { xData, yData } = transformDataForLineGraph(results, props.query.metric)-- // Use area chart for CPU time and bytes read (sparkline-like), line chart for others- const chartType =- props.query.metric === 'cpu_seconds' || props.query.metric === 'bytes_read'- ? ChartDisplayType.ActionsAreaGraph- : ChartDisplayType.ActionsLineGraph-- return (- <div className="border rounded bg-bg-light p-2 h-60">- <LineGraph- xData={xData}- yData={yData}- visualizationType={chartType}- chartSettings={{- showLegend: yData.length > 1,- }}- />- </div>- )+ return <EndpointsUsageTrendsChart results={results} metric={props.query.metric} interval={props.query.interval} />}-interface ScaleFactor {- divisor: number- label: string- suffix: string- decimalPlaces: number-}--function getScaleFactor(values: number[], metric: string): ScaleFactor {- if (values.length === 0) {- return { divisor: 1, label: getMetricLabel(metric), suffix: '', decimalPlaces: 0 }- }-- const maxValue = Math.max(...values)-- if (metric === 'bytes_read') {- if (maxValue >= 1024 * 1024 * 1024) {- return { divisor: 1024 * 1024 * 1024, label: 'Bytes read (GB)', suffix: ' GB', decimalPlaces: 2 }- } else if (maxValue >= 1024 * 1024) {- return { divisor: 1024 * 1024, label: 'Bytes read (MB)', suffix: ' MB', decimalPlaces: 2 }- } else if (maxValue >= 1024) {- return { divisor: 1024, label: 'Bytes read (KB)', suffix: ' KB', decimalPlaces: 2 }- }- return { divisor: 1, label: 'Bytes read (B)', suffix: ' B', decimalPlaces: 0 }- }-- if (metric === 'query_duration') {- if (maxValue >= 60000) {- return { divisor: 60000, label: 'Query duration (min)', suffix: ' min', decimalPlaces: 2 }- } else if (maxValue >= 1000) {- return { divisor: 1000, label: 'Query duration (s)', suffix: ' s', decimalPlaces: 2 }- }- return { divisor: 1, label: 'Query duration (ms)', suffix: ' ms', decimalPlaces: 0 }- }-- if (metric === 'cpu_seconds') {- if (maxValue >= 60) {- return { divisor: 60, label: 'CPU time (min)', suffix: ' min', decimalPlaces: 2 }- }- return { divisor: 1, label: 'CPU time (s)', suffix: ' s', decimalPlaces: 2 }- }-- if (metric === 'error_rate') {- // Error rate comes as 0-1, display as percentage- return { divisor: 0.01, label: 'Error rate (%)', suffix: '%', decimalPlaces: 2 }- }-- return { divisor: 1, label: getMetricLabel(metric), suffix: '', decimalPlaces: 0 }-}--function scaleMetricData(- values: number[],- metric: string-): {- values: number[]- label: string- settings: { formatting: { suffix: string; decimalPlaces: number } }-} {- const { divisor, label, suffix, decimalPlaces } = getScaleFactor(values, metric)- return {- values: values.map((v) => v / divisor),- label,- settings: { formatting: { suffix, decimalPlaces } },- }-}--function transformDataForLineGraph(- results: TrendsDataPoint[],- metric: string-): {- xData: AxisSeries<string>- yData: AxisSeries<number>[]-} {- const hasBreakdown = results.some((r) => r.breakdown !== undefined)-- if (hasBreakdown) {- // Group by breakdown value- const breakdowns = [...new Set(results.map((r) => r.breakdown || 'unknown'))]-- // Group by date- const dateGroups = results.reduce(- (acc, point) => {- const dateKey = point.date- if (!acc[dateKey]) {- acc[dateKey] = {}- }- acc[dateKey][point.breakdown || 'unknown'] = point.value- return acc- },- {} as Record<string, Record<string, number>>- )-- const dates = Object.keys(dateGroups).sort()-- // Determine scale based on all values for consistency across breakdowns- const allValues = results.map((r) => r.value)- const scaleFactor = getScaleFactor(allValues, metric)+export function EndpointsUsageTrendsChart({+ results,+ metric,+ // Quill only formats the axis ticks and the tooltip header when both `timezone` and `interval`+ // are set, so an absent interval would leave raw ISO labels on both.+ interval = 'day',+}: {+ results: TrendsDataPoint[]+ metric: EndpointsUsageMetric+ interval?: IntervalType+}): JSX.Element {+ const isAreaChart = metric === 'cpu_seconds' || metric === 'bytes_read'++ const { labels, series, scale } = useMemo(+ () => transformDataForChart(results, metric, isAreaChart),+ [results, metric, isAreaChart]+ )+ const { timezone } = useValues(teamLogic)+ const theme = useChartTheme()+ const config = useChartConfig<TimeSeriesLineChartConfig>(() => {+ const formatValue = (value: number): string => `${value.toFixed(scale.decimalPlaces)}${scale.suffix}`return {- xData: {- column: {- name: 'date',- type: { name: 'DATE', isNumerical: false },- label: 'Date',- dataIndex: 0,- },- data: dates,+ xAxis: { timezone, interval, allDays: labels },+ yAxis: { scale: 'linear', showGrid: true, startAtZero: true, tickFormatter: formatValue },+ legend: { show: series.length > 1, position: 'top', interactive: true },+ tooltip: {+ placement: 'cursor',+ pinnable: true,+ sortedByValue: true,+ showTotal: series.length > 1,+ valueFormatter: formatValue,},- yData: breakdowns.map((breakdown, index) => {- const breakdownValues = dates.map((date) => dateGroups[date][breakdown] || 0)- return {- column: {- name: breakdown,- type: { name: 'FLOAT', isNumerical: true },- label: breakdown,- dataIndex: index + 1,- },- data: breakdownValues.map((v) => v / scaleFactor.divisor),- settings: {- formatting: {- suffix: scaleFactor.suffix,- decimalPlaces: scaleFactor.decimalPlaces,- },- },- }- }),}- }+ }, [labels, series.length, scale, timezone, interval])- // Simple case - no breakdown- const rawValues = results.map((r) => r.value)- const { values: scaledValues, label: scaledLabel, settings } = scaleMetricData(rawValues, metric)-- return {- xData: {- column: {- name: 'date',- type: { name: 'DATE', isNumerical: false },- label: 'Date',- dataIndex: 0,- },- data: results.map((r) => r.date),- },- yData: [- {- column: {- name: metric,- type: { name: 'FLOAT', isNumerical: true },- label: scaledLabel,- dataIndex: 1,- },- data: scaledValues,- settings,- },- ],- }-}--function getMetricLabel(metric: string): string {- switch (metric) {- case 'bytes_read':- return 'Bytes read'- case 'cpu_seconds':- return 'CPU time'- case 'query_duration':- return 'Query duration'- case 'error_rate':- return 'Error rate'- case 'requests':- default:- return 'Executions'- }+ return (+ <div className="border rounded bg-bg-light p-2 h-60 flex flex-col">+ <TimeSeriesLineChart+ series={series}+ labels={labels}+ theme={theme}+ config={config}+ onError={handleChartError}+ />+ </div>+ )}diff --git a/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.test.ts b/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.test.tsnew file mode 100644index 000000000000..87a8507b520e--- /dev/null+++ b/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.test.ts@@ -0,0 +1,82 @@+import { getScaleFactor, transformDataForChart, type TrendsDataPoint } from './endpointsUsageTrendsTransforms'++describe('endpointsUsageTrendsTransforms', () => {+ describe('getScaleFactor', () => {+ it.each([+ ['bytes_read', 500, { divisor: 1, suffix: ' B', decimalPlaces: 0 }],+ ['bytes_read', 2048, { divisor: 1024, suffix: ' KB', decimalPlaces: 2 }],+ ['bytes_read', 5 * 1024 * 1024, { divisor: 1024 * 1024, suffix: ' MB', decimalPlaces: 2 }],+ ['bytes_read', 5 * 1024 * 1024 * 1024, { divisor: 1024 * 1024 * 1024, suffix: ' GB', decimalPlaces: 2 }],+ ['query_duration', 500, { divisor: 1, suffix: ' ms', decimalPlaces: 0 }],+ ['query_duration', 5000, { divisor: 1000, suffix: ' s', decimalPlaces: 2 }],+ ['query_duration', 120000, { divisor: 60000, suffix: ' min', decimalPlaces: 2 }],+ ['cpu_seconds', 30, { divisor: 1, suffix: ' s', decimalPlaces: 2 }],+ ['cpu_seconds', 120, { divisor: 60, suffix: ' min', decimalPlaces: 2 }],+ ['error_rate', 0.5, { divisor: 0.01, suffix: '%', decimalPlaces: 2 }],+ ['requests', 500, { divisor: 1, suffix: '', decimalPlaces: 0 }],+ ] as const)('scales %s at max value %d', (metric, maxValue, expected) => {+ const scale = getScaleFactor([maxValue], metric)+ expect(scale.divisor).toBe(expected.divisor)+ expect(scale.suffix).toBe(expected.suffix)+ expect(scale.decimalPlaces).toBe(expected.decimalPlaces)+ })++ it('falls back to the metric label with no scaling when there are no values', () => {+ expect(getScaleFactor([], 'requests')).toEqual({+ divisor: 1,+ label: 'Executions',+ suffix: '',+ decimalPlaces: 0,+ })+ })+ })++ describe('transformDataForChart', () => {+ it('divides values by the scale divisor in the simple (no breakdown) case', () => {+ const results: TrendsDataPoint[] = [+ { date: '2026-07-01', value: 120 },+ { date: '2026-07-02', value: 180 },+ ]+ const { labels, series } = transformDataForChart(results, 'cpu_seconds', false)++ expect(labels).toEqual(['2026-07-01', '2026-07-02'])+ expect(series).toEqual([{ key: 'cpu_seconds', label: 'CPU time (min)', data: [2, 3] }])+ })++ it('divides values by the scale divisor in the breakdown case', () => {+ const results: TrendsDataPoint[] = [+ { date: '2026-07-01', breakdown: '/api/events', value: 60 },+ { date: '2026-07-02', breakdown: '/api/events', value: 120 },+ ]+ const { series } = transformDataForChart(results, 'cpu_seconds', false)++ expect(series).toEqual([{ key: '/api/events', label: '/api/events', data: [1, 2] }])+ })++ it('fills missing breakdown values at a date with 0 rather than dropping the series', () => {+ const results: TrendsDataPoint[] = [+ { date: '2026-07-01', breakdown: '/api/events', value: 10 },+ { date: '2026-07-01', breakdown: '/api/persons', value: 20 },+ { date: '2026-07-02', breakdown: '/api/events', value: 30 },+ // '/api/persons' has no row on 2026-07-02+ ]+ const { labels, series } = transformDataForChart(results, 'requests', false)++ expect(labels).toEqual(['2026-07-01', '2026-07-02'])+ expect(series).toEqual([+ { key: '/api/events', label: '/api/events', data: [10, 30] },+ { key: '/api/persons', label: '/api/persons', data: [20, 0] },+ ])+ })++ it('applies an area fill only when isAreaChart is true', () => {+ const results: TrendsDataPoint[] = [{ date: '2026-07-01', value: 10 }]++ const line = transformDataForChart(results, 'requests', false)+ const area = transformDataForChart(results, 'bytes_read', true)++ expect(line.series[0].fill).toBeUndefined()+ expect(area.series[0].fill).toEqual({ opacity: 0.5 })+ })+ })+})diff --git a/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.ts b/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.tsnew file mode 100644index 000000000000..c2dea450f823--- /dev/null+++ b/products/endpoints/frontend/nodes/endpointsUsageTrendsTransforms.ts@@ -0,0 +1,145 @@+import { type Series } from '@posthog/quill-charts'++import { EndpointsUsageTrendsQuery } from '~/queries/schema/schema-general'++export type EndpointsUsageMetric = EndpointsUsageTrendsQuery['metric']++export type TrendsDataPoint = {+ date: string+ value: number+ breakdown?: string+}++export interface ScaleFactor {+ divisor: number+ label: string+ suffix: string+ decimalPlaces: number+}++export function getScaleFactor(values: number[], metric: EndpointsUsageMetric): ScaleFactor {+ if (values.length === 0) {+ return { divisor: 1, label: getMetricLabel(metric), suffix: '', decimalPlaces: 0 }+ }++ const maxValue = Math.max(...values)++ if (metric === 'bytes_read') {+ if (maxValue >= 1024 * 1024 * 1024) {+ return { divisor: 1024 * 1024 * 1024, label: 'Bytes read (GB)', suffix: ' GB', decimalPlaces: 2 }+ } else if (maxValue >= 1024 * 1024) {+ return { divisor: 1024 * 1024, label: 'Bytes read (MB)', suffix: ' MB', decimalPlaces: 2 }+ } else if (maxValue >= 1024) {+ return { divisor: 1024, label: 'Bytes read (KB)', suffix: ' KB', decimalPlaces: 2 }+ }+ return { divisor: 1, label: 'Bytes read (B)', suffix: ' B', decimalPlaces: 0 }+ }++ if (metric === 'query_duration') {+ if (maxValue >= 60000) {+ return { divisor: 60000, label: 'Query duration (min)', suffix: ' min', decimalPlaces: 2 }+ } else if (maxValue >= 1000) {+ return { divisor: 1000, label: 'Query duration (s)', suffix: ' s', decimalPlaces: 2 }+ }+ return { divisor: 1, label: 'Query duration (ms)', suffix: ' ms', decimalPlaces: 0 }+ }++ if (metric === 'cpu_seconds') {+ if (maxValue >= 60) {+ return { divisor: 60, label: 'CPU time (min)', suffix: ' min', decimalPlaces: 2 }+ }+ return { divisor: 1, label: 'CPU time (s)', suffix: ' s', decimalPlaces: 2 }+ }++ if (metric === 'error_rate') {+ // Error rate comes as 0-1, display as percentage+ return { divisor: 0.01, label: 'Error rate (%)', suffix: '%', decimalPlaces: 2 }+ }++ return { divisor: 1, label: getMetricLabel(metric), suffix: '', decimalPlaces: 0 }+}++export function transformDataForChart(+ results: TrendsDataPoint[],+ metric: EndpointsUsageMetric,+ isAreaChart: boolean+): {+ labels: string[]+ series: Series[]+ scale: ScaleFactor+} {+ const fill = isAreaChart ? { fill: { opacity: 0.5 } } : {}+ const hasBreakdown = results.some((r) => r.breakdown !== undefined)++ if (hasBreakdown) {+ // Group by breakdown value+ const breakdowns = [...new Set(results.map((r) => r.breakdown || 'unknown'))]++ // Group by date+ const dateGroups = results.reduce(+ (acc, point) => {+ const dateKey = point.date+ if (!acc[dateKey]) {+ acc[dateKey] = {}+ }+ acc[dateKey][point.breakdown || 'unknown'] = point.value+ return acc+ },+ {} as Record<string, Record<string, number>>+ )++ const dates = Object.keys(dateGroups).sort()++ // Determine scale based on all values for consistency across breakdowns+ const scale = getScaleFactor(+ results.map((r) => r.value),+ metric+ )++ return {+ labels: dates,+ series: breakdowns.map((breakdown) => ({+ key: breakdown,+ label: breakdown,+ data: dates.map((date) => (dateGroups[date][breakdown] || 0) / scale.divisor),+ ...fill,+ })),+ scale,+ }+ }++ // Simple case - no breakdown+ const scale = getScaleFactor(+ results.map((r) => r.value),+ metric+ )++ return {+ labels: results.map((r) => r.date),+ series: [+ {+ key: metric,+ label: scale.label,+ data: results.map((r) => r.value / scale.divisor),+ ...fill,+ },+ ],+ scale,+ }+}++function getMetricLabel(metric: EndpointsUsageMetric): string {+ switch (metric) {+ case 'bytes_read':+ return 'Bytes read'+ case 'cpu_seconds':+ return 'CPU time'+ case 'query_duration':+ return 'Query duration'+ case 'error_rate':+ return 'Error rate'+ case 'requests':+ default:+ return 'Executions'+ }+}