: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(alerts): render the evaluation history chart with quill charts (#86545)
Sam Pennington33db828fdf20
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6b964dd36d4f..bff1a1285dc6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4745,25 +4745,25 @@ snapshots:posthog-3000-keyboard-shortcut--within-tooltip--light:hash: v1.k794b7964.aa2d9701c9134d5c374b6517f2fa542eb24c7e15ebf0d65f64efbc0ec2a99efa.BL1mMRm5CNDAmAMk-2pf-lp8EI6t65oBqoy990BdgyQproducts-alerts-alert-history-chart--anomaly-probability-cutoff--dark:- hash: v1.k794b7964.79aa55bc7ee50e205b299b2bde35388df13e0e2276e2266085b2e4afc3211f9d.wTwJM9Itu9VdDNnHqAGyxFvDgIf4HH6XUHwfUaFI38o+ hash: v1.k794b7964.24b4adbdb188cde0541f0f66f73af27bdd04408c31291bf68316bb3817759643.GuBTwp4mmQHHVO07xyvgxbSCEuKylDxNzue0viIzLtsproducts-alerts-alert-history-chart--anomaly-probability-cutoff--light:- hash: v1.k794b7964.2e61e5b6c10e75ab7956910da63540cd59613cedd82cda41d27855350f1fbc79.qyZY692AuFYYlb0O5pP-6-NEzod1fZkG10CjZXEfY1U+ hash: v1.k794b7964.500239b49ffc44daa00a24697ef4946abf9758e01dedee6dbb1d1af3906f257c.nl3i95cuHsjkdCBCnS4xRr8tQF_B2SfUyS4F_g_55LIproducts-alerts-alert-history-chart--default--dark:- hash: v1.k794b7964.506bc7fadd0b3360e3259626a9768352ccd4ce498b4df82d1225cea00ba15e88.0cs6ZhX2Ih--6CDOBuG12ZNyZjupj9ePoqMCW23GvcA+ hash: v1.k794b7964.efa18d82f9a40253504c02eb062d651733a4b9cd5bef60cb826a2d2d4e5aca15.ygobekdfgBV5hQ5lhMqSVntK2thZLJ62elkYyIsup2Aproducts-alerts-alert-history-chart--default--light:- hash: v1.k794b7964.3ae6d078b92dd2de10e90458c4b084cbe643a1843bf8456ea9cedb331fd2407e.YEPALzsZNyAn6dBDA0wVG5asI2MqqY0aMbtqUqICsjE+ hash: v1.k794b7964.a7d3030c73c7d63ac5ebdb9f35f985b226f08b02b51bbca23b57a4cf7bc923ab.wxt6Ij2d2K3YHE_xMHn31yw55jtjg3NumtkOFqIt-pgproducts-alerts-alert-history-chart--percentage-thresholds--dark:- hash: v1.k794b7964.138483e490bdadb225663a058b6bebac6fdc0abf69a32a50b97723217224e9e9._tVpV44HZe6qDHZvZ5eCLaSGDSvXY09rEcKvN44f11U+ hash: v1.k794b7964.2046df03cbbcf8dfe13000c0b206825d4eeb0a245d77018eca9e667cac408220.aQCr7KvmqJfS_vvMr0sCmxpChikqme1d-XafYaz5lnkproducts-alerts-alert-history-chart--percentage-thresholds--light:- hash: v1.k794b7964.1e61e68c1a67541f3c62db5fe55aa22fd0c9b3024e9bfe12b27655e5dbb388a6.lsLlLF6wu8nqCU1mBU5O1rfJFY_Ic44QU_KUv9avfCo+ hash: v1.k794b7964.4bbbbc9b49cda8e42351cc594ad03efa6ee5814ca544fff3744faa9d1a4e3ae1.Yj-kqEp4dDdxh1kcOikNz-_-fGpqJPDT1c_rIf7UCyMproducts-alerts-alert-history-chart--threshold-changed--dark:- hash: v1.k794b7964.93bdb15a9050ddbb6f4d1e370610c6733d71172c6604585c4e7b703cfd47c482.VL615VIicTduqKiolRa_CSYzf5qu-34WKbrSxE4IaQA+ hash: v1.k794b7964.be71ec307fbbba2ac6bd1526a4715e2b0694569a22e238e89b2010c67ec8a572.X1TzLmh_AD3_Z7FDKT6xCtBUaIiCf9pA399uMF_FLHkproducts-alerts-alert-history-chart--threshold-changed--light:- hash: v1.k794b7964.77d32c76ded75923403747e763b286f50914860f056c8696f92d9b089e688a5d.IzqZGt6MiYKjYUPtUCyaGTPvFyo6ZfZdyc4tyc-qISY+ hash: v1.k794b7964.d8da461055012775ff1c2b8fc9d1f5a9c89b29ff26fc55f5d46a3d8cd16dd528.QcTzP3OJNKPkc5oFv-o12pqIzZhAsGe3dx535bJZRpMproducts-alerts-alert-history-chart--truncated-history--dark:- hash: v1.k794b7964.fc0bbe76de7a888aaac89fb7005b869d907866c3d58ed878111973eaf1b13b58.c5uaADCS2xUuOYu5cky5GCe4xJN3E9okpxmnlmSproA+ hash: v1.k794b7964.a6c3e16a4c2d3afbda4f0c6ee8654059c1ce1af118e06ff9684245d7d4e90d56.9SeAY0VADP000GUzOLjde2l3zk2b9byQ_OcXjfqIlJwproducts-alerts-alert-history-chart--truncated-history--light:- hash: v1.k794b7964.4c430430516c67b17d93456382ba5c78638d47c16b3d79536ff897067e1f9ebc.HZQrD0nZW8iu2VoLEoPxk8zKg05AOf9Dz9QdC4ncUqw+ hash: v1.k794b7964.fb04c5eb2dee3e54286be4a599a42b81f81f696254510bc5dc107ce44a182231.fmS-_SPCu4bmN_8mtGiy_Oux8l-ylT8S8UvLt2OtwZoproducts-alerts-alert-modal--create-wizard--dark:hash: v1.k794b7964.e3efb1235db76f2fe8b3ccff465df9b84263211b8648d57a725cfcf3a92c08c9.mTtZUY5-gkDVf9yjhBIR_Cx1_5arKEIEJh-2g-cLQBQproducts-alerts-alert-modal--create-wizard--light:@@ -4813,9 +4813,9 @@ snapshots:products-alerts-shared-components--editor-loading--light:hash: v1.k794b7964.5e3a2827ace05ced5a178649d4d511fde78fbd2efc102c1fd3d5cacc229b8395.GsnqMnxDeg6gkEjtWsWDcrdQRmw4OdCs2s4rfF0WdN4products-alerts-shared-components--evaluation-history--dark:- hash: v1.k794b7964.4c73cdf98a02e35050526eb3d8dbeb6290352aec664d5efeb427061b90ad3805.agcaltLoWhqx3J3mCJW_kDgM2eR3Z8Q1rLkTRISqmS4+ hash: v1.k794b7964.a9888c560e4c6210aaaa5a07a9a45d77d8ed7d03153ce101bd64756d75178e6f.0Ev3YAPnmseOmoneOZ3hw84YpqNVh1esJ6Z-wHE9Pl4products-alerts-shared-components--evaluation-history--light:- hash: v1.k794b7964.c1926b36680c9eb9131bf374492a31d897583cc0219e0c12e31c57406ba42284.6e5ldiw6-7Xry45ZfkhsNoDiozPOldPRDzQ2Y3pFjYk+ hash: v1.k794b7964.f35da1ffd01f5c51ff4d29f62bc9230601a20b9b31a91b6c7d43e2eec1ab7536.Sjs6R9HmlKOBOr_RCzIRRqiSb-BYWrUnX4mHk5f9sZIproducts-alerts-shared-components--notifications--dark:hash: v1.k794b7964.81ff4b2654d65e3866f9dd9e04dfcedb6d1dbbb45fcdf73acfd60153ba263480.Zq6Us8BfcBnrdUHjpISWQFYe5836RgaIlc6eoFwpshEproducts-alerts-shared-components--notifications--light:diff --git a/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsxindex 40537d4b2850..2aeb2f47e140 100644--- a/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx+++ b/products/alerts/frontend/components/AlertEvaluationHistoryChart.tsx@@ -1,17 +1,40 @@-import annotationPlugin from 'chartjs-plugin-annotation'import { useMemo } from 'react'-import { Chart } from 'lib/Chart'-import { useChart } from 'lib/hooks/useChart'+import {+ ReferenceLines,+ ScatterChart,+ type ScatterPoint,+ type ScatterSeries,+ type ScatterTooltipContext,+ TooltipSurface,+ TooltipSwatch,+ useChartTheme,+} from '@posthog/quill-charts'+import { humanFriendlyNumber } from 'lib/utils/numbers'import { pluralize } from 'lib/utils/strings'-Chart.register(annotationPlugin)+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'++const handleChartError = makeChartErrorHandler('alerts-evaluation-history-chart')const ROLLING_WINDOW = 5type PointClassification = 'historical' | 'currentOnly' | 'none'+interface HistoryPointMeta {+ label: string+ classification: PointClassification+}++// Semantic status colors, legible on light and dark chart surfaces: red = fired, orange = would+// fire now, indigo = normal.+const CLASSIFICATION_STYLE: Record<PointClassification, { color: string; shape: 'circle' | 'square' | 'triangle' }> = {+ none: { color: '#6366f1', shape: 'circle' },+ historical: { color: '#dc2626', shape: 'square' },+ currentOnly: { color: '#ea580c', shape: 'triangle' },+}+export interface AlertEvaluationHistoryPoint {label: stringvalue: number@@ -153,143 +176,82 @@ export function AlertEvaluationHistoryChart({return detectSpikesAboveTrend(values, trailingAverage).map((flagged) => (flagged ? 'historical' : 'none'))}, [classifyUnusualWithoutThresholds, hasHistoricalFiringState, points, thresholds, values])- const thresholdAnnotations = useMemo(() => {- if (thresholds.length === 0) {+ const theme = useChartTheme()++ const scatterSeries = useMemo((): ScatterSeries<HistoryPointMeta>[] => {+ const byClass: Record<PointClassification, ScatterPoint<HistoryPointMeta>[]> = {+ none: [],+ historical: [],+ currentOnly: [],+ }+ points.forEach((point, index) => {+ const classification = pointClassifications[index] ?? 'none'+ byClass[classification].push({ x: index, y: point.value, meta: { label: point.label, classification } })+ })+ // Normal points first so flagged markers draw on top.+ return (['none', 'historical', 'currentOnly'] as const)+ .filter((classification) => byClass[classification].length > 0)+ .map((classification) => ({+ key: classification,+ label: classification,+ points: byClass[classification],+ shape: CLASSIFICATION_STYLE[classification].shape,+ color: CLASSIFICATION_STYLE[classification].color,+ }))+ }, [points, pointClassifications])++ const referenceLines = useMemo(+ () =>+ thresholds.map((threshold) => ({+ value: threshold.value,+ label: threshold.label,+ labelPosition: 'start' as const,+ variant: 'alert' as const,+ })),+ [thresholds]+ )++ const yDomain = useMemo((): readonly [number, number] | undefined => {+ if (thresholds.length === 0 || values.length === 0) {return undefined}- return Object.fromEntries(- thresholds.map((threshold, index) => [- `${threshold.direction}-${index}`,- {- type: 'line' as const,- yMin: threshold.value,- yMax: threshold.value,- borderColor:- threshold.direction === 'upper' ? 'rgba(220, 38, 38, 0.72)' : 'rgba(234, 88, 12, 0.75)',- borderWidth: 1.5,- borderDash: [5, 4],- label: {- display: true,- content: threshold.label,- position: 'start' as const,- font: { size: 9 },- color: threshold.direction === 'upper' ? 'rgba(220, 38, 38, 0.95)' : 'rgba(234, 88, 12, 0.95)',- backgroundColor: 'transparent',- },- },- ])- )- }, [thresholds])+ const dataMin = Math.min(...values)+ const dataMax = Math.max(...values)+ const min = Math.min(dataMin, ...thresholds.map((threshold) => threshold.value))+ const max = Math.max(dataMax, ...thresholds.map((threshold) => threshold.value))+ if (min === dataMin && max === dataMax) {+ return undefined+ }+ const headroom = (max - min) * 0.05 || 1+ return [min < dataMin ? min - headroom : min, max > dataMax ? max + headroom : max]+ }, [thresholds, values])- const { canvasRef } = useChart({- getConfig: () => ({- type: 'line' as const,- data: {- labels,- datasets: [- {- label: valueLabel,- data: values,- showLine: false,- borderWidth: 0,- backgroundColor: 'transparent',- fill: false,- pointRadius: (context) => (pointClassifications[context.dataIndex] === 'none' ? 4 : 4.5),- pointHoverRadius: (context) => (pointClassifications[context.dataIndex] === 'none' ? 5 : 5.5),- pointStyle: (context) => {- const classification = pointClassifications[context.dataIndex]- if (classification === 'historical') {- return 'rect'- }- if (classification === 'currentOnly') {- return 'triangle'- }- return 'circle'- },- pointBackgroundColor: (context) => {- const classification = pointClassifications[context.dataIndex]- if (classification === 'historical') {- return 'rgba(220, 38, 38, 0.92)'- }- if (classification === 'currentOnly') {- return 'rgba(234, 88, 12, 0.85)'- }- return 'transparent'- },- pointBorderColor: (context) => {- const classification = pointClassifications[context.dataIndex]- if (classification === 'historical') {- return 'rgba(127, 29, 29, 1)'- }- if (classification === 'currentOnly') {- return 'rgba(154, 52, 18, 1)'- }- return 'rgba(99, 102, 241, 0.95)'- },- pointBorderWidth: 1.75,- },- ],- },- options: {- responsive: true,- maintainAspectRatio: false,- interaction: { mode: 'nearest' as const, axis: 'x' as const, intersect: false },- plugins: {- legend: { display: false },- ...(thresholdAnnotations ? { annotation: { annotations: thresholdAnnotations } } : {}),- tooltip: {- enabled: true,- callbacks: {- title: (items) => (items[0] ? String(items[0].label) : ''),- label: (context) => {- const value = context.parsed.y- if (value == null || Number.isNaN(value)) {- return context.dataset.label ?? ''- }- const classification = pointClassifications[context.dataIndex]- let suffix = ''- if (classification === 'historical') {- suffix = hasHistoricalFiringState- ? ' (triggered the alert)'- : thresholds.length > 0- ? ' (outside threshold)'- : ' (unusual compared to recent values)'- } else if (classification === 'currentOnly') {- suffix = ' (would trigger the alert now)'- }- return `${valueLabel}: ${formatValue(value)}${suffix}`- },- },- },- },- scales: {- x: {- display: true,- ticks: { maxRotation: 45, minRotation: 0, autoSkip: true, maxTicksLimit: 6, font: { size: 9 } },- grid: { display: true, color: 'rgba(0,0,0,0.06)', drawTicks: false },- },- y: {- display: true,- position: 'left' as const,- ticks: {- maxTicksLimit: 5,- font: { size: 10 },- callback: (value: string | number) => formatValue(Number(value)),- },- grid: { color: 'rgba(0,0,0,0.06)' },- },- },- },- }),- deps: [- chartSeries,- valueLabel,- thresholdAnnotations,- pointClassifications,- hasHistoricalFiringState,- formatValue,- ],- })+ const renderTooltip = (ctx: ScatterTooltipContext<HistoryPointMeta>): JSX.Element => {+ const { point } = ctx+ const classification = point.meta?.classification ?? 'none'+ let suffix = ''+ if (classification === 'historical') {+ suffix = hasHistoricalFiringState+ ? ' (triggered the alert)'+ : thresholds.length > 0+ ? ' (outside threshold)'+ : ' (unusual compared to recent values)'+ } else if (classification === 'currentOnly') {+ suffix = ' (would trigger the alert now)'+ }+ return (+ <TooltipSurface>+ <div className="font-semibold">{point.meta?.label}</div>+ <div className="flex items-center gap-2">+ <TooltipSwatch color={point.color} />+ <span>+ {valueLabel}: <strong className="tabular-nums">{formatValue(point.y)}</strong>+ {suffix}+ </span>+ </div>+ </TooltipSurface>+ )+ }const historicalCount = pointClassifications.filter((classification) => classification === 'historical').lengthconst currentOnlyCount = pointClassifications.filter((classification) => classification === 'currentOnly').length@@ -331,8 +293,24 @@ export function AlertEvaluationHistoryChart({return (<div className="space-y-2"><p className="text-muted text-xs mb-0">{historyCaption}</p>- <div className="h-56 w-full min-h-56">- <canvas ref={canvasRef} />+ <div className="h-56 w-full min-h-56 flex flex-col">+ <ScatterChart<HistoryPointMeta>+ series={scatterSeries}+ theme={theme}+ config={{+ xAxis: {+ domain: [-0.5, Math.max(points.length - 0.5, 0.5)],+ tickFormatter: (value) => labels[Math.round(value)] ?? '',+ },+ yAxis: { domain: yDomain, tickFormatter: (value) => formatValue(value) },+ showGrid: true,+ tooltip: { enabled: true },+ }}+ tooltip={renderTooltip}+ onError={handleChartError}+ >+ <ReferenceLines lines={referenceLines} />+ </ScatterChart></div><p className="text-muted text-xs mb-0">{summary}</p>{hasHistoricalFiringState && currentOnlyCount > 0 ? (