Skip to content

: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.

feat(logs): render the anomaly band chart with quill charts (#83204)

Sam Penningtona8fa2eccca58
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8835de05be81..f7ef3d50b45e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4616,6 +4616,10 @@ snapshots:
hash: v1.k794b7964.ff05bda7e439902c963d4cee0889351a3cace04ef2e149494544b1bc60794347.JKw0gsl8CIiVdeLk4DndxZFLr2oZ7kYNBIxNotCuVCQ
lemon-ui-visual-image-diff-viewer--small-image--light:
hash: v1.k794b7964.ed31587820d0216f2281ec8e610da8cb9fe8cb45f9c13e0280f17771cf84994a.spusB2C8AKwu5Tv0KOr8pkjDxgEZw5jcOlEikYAzKWI
+ logs-anomalybandchart--observed-vs-expected--dark:
+ hash: v1.k794b7964.1c836e86ad8a54b69f37f78d9e18495500c5833ba27c298f8388adbea6da717d.UqfZ7Ar68xRSa97H71uy9HNMBFW_2Iy-_8fT0oLb4jw
+ logs-anomalybandchart--observed-vs-expected--light:
+ hash: v1.k794b7964.e43d3161f7310bd2dea0b1750791bdd13f03df5a7c1f03e72181b40a4e14eb5f._e8vPOX93NKaP89p7WgrZW73BWtfCtBPcVGA0g6Vfw8
logs-logsfiltervolumesparkline--volume-by-service--dark:
hash: v1.k794b7964.e1872546be635b378270c73689340083b3af5a318a302372c8db68edfaf232df.T7cwZzY2SaTMk7nKYYhotxV3cmnDaQ1-Cy5dm3fUH2c
logs-logsfiltervolumesparkline--volume-by-service--light:
diff --git a/products/logs/frontend/LogsAnomalies.tsx b/products/logs/frontend/LogsAnomalies.tsx
index d437e6c8fe3c..6408eead85fa 100644
--- a/products/logs/frontend/LogsAnomalies.tsx
+++ b/products/logs/frontend/LogsAnomalies.tsx
@@ -1,11 +1,14 @@
import { useActions, useValues } from 'kea'
+import { combineUrl, router } from 'kea-router'
+import { IconUndo } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'
import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
import type { LogMessage } from '~/queries/schema/schema-general'
@@ -21,7 +24,7 @@ import {
type LogsAnomalyScanSeriesApi,
type LogsAnomalyVerdictEnumApi,
} from 'products/logs/frontend/generated/api.schemas'
-import { SCAN_WINDOW_OPTIONS, logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'
+import { SCAN_WINDOW_OPTIONS, type ScanRange, logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'
const VERDICT_TAG: Record<LogsAnomalyVerdictEnumApi, { label: string; type: LemonTagType }> = {
spike: { label: 'Spike', type: 'danger' },
@@ -140,13 +143,21 @@ function ScanResults({ result }: { result: LogsAnomalyScanResponseApi }): JSX.El
from <TZLabel time={result.eval_start} /> to <TZLabel time={result.eval_end} />.
</LemonBanner>
)}
- <BandCharts series={result.series} />
+ <BandCharts series={result.series} serviceName={result.service_name} />
<LearningStatus series={result.series} lookbackDays={result.lookback_days} />
</div>
)
}
-function BandCharts({ series }: { series: LogsAnomalyScanSeriesApi[] }): JSX.Element | null {
+function BandCharts({
+ series,
+ serviceName,
+}: {
+ series: LogsAnomalyScanSeriesApi[]
+ serviceName: string
+}): JSX.Element | null {
+ const { zoomedRange, scanDisabledReason } = useValues(logsAnomaliesLogic)
+ const { zoomToRange, resetZoom } = useActions(logsAnomaliesLogic)
const withBuckets = series.filter((s) => s.buckets.length > 0)
if (withBuckets.length === 0) {
return null
@@ -155,21 +166,52 @@ function BandCharts({ series }: { series: LogsAnomalyScanSeriesApi[] }): JSX.Ele
<div className="flex flex-col gap-2" data-attr="logs-anomalies-band-charts">
<h3 className="mb-0">Observed vs expected</h3>
<div className="text-secondary text-sm">
- Log volume per 5 minute bucket against the learned band. Marked points fell outside the band.
+ Log volume per 5 minute bucket against the learned band. Marked points fell outside the band. Drag
+ across a chart to scan a narrower window, or click a bucket to read its logs.
</div>
{withBuckets.map((s) => (
<div key={s.severity} className="rounded border bg-surface-primary p-3">
<div className="mb-2 flex items-center gap-2">
<LogTag level={s.severity as LogMessage['severity_text']} />
<span className="text-secondary text-xs">{s.stage ? STAGE_LABEL[s.stage] : 'Not scored'}</span>
+ {/* Per chart rather than in the toolbar: you drag on a chart, so the way back
+ has to be next to the chart you dragged on. */}
+ {zoomedRange && (
+ <LemonButton
+ className="ml-auto"
+ size="xsmall"
+ type="secondary"
+ icon={<IconUndo />}
+ onClick={resetZoom}
+ disabledReason={scanDisabledReason}
+ data-attr="logs-anomalies-reset-zoom"
+ >
+ Reset zoom
+ </LemonButton>
+ )}
</div>
- <AnomalyBandChart buckets={s.buckets} />
+ <AnomalyBandChart
+ buckets={s.buckets}
+ onZoom={zoomToRange}
+ onBucketClick={(range) => openLogsForBucket(serviceName, s.severity, range)}
+ />
</div>
))}
</div>
)
}
+function openLogsForBucket(serviceName: string, severity: string, range: ScanRange): void {
+ router.actions.push(
+ combineUrl(urls.logs(), {
+ activeTab: 'viewer',
+ serviceNames: serviceName,
+ severityLevels: severity,
+ dateRange: { date_from: range.dateFrom, date_to: range.dateTo },
+ }).url
+ )
+}
+
function ConstraintsBanner({ result }: { result: LogsAnomalyScanResponseApi }): JSX.Element | null {
if (!result.degraded && !result.eval_clipped && result.binding_constraints.length === 0) {
return null
diff --git a/products/logs/frontend/components/AnomalyBandChart.stories.tsx b/products/logs/frontend/components/AnomalyBandChart.stories.tsx
new file mode 100644
index 000000000000..7ae7c96b8690
--- /dev/null
+++ b/products/logs/frontend/components/AnomalyBandChart.stories.tsx
@@ -0,0 +1,66 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import type { LogsAnomalyScanBucketApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { AnomalyBandChart } from './AnomalyBandChart'
+
+const BUCKET_MINUTES = 5
+const BUCKETS = 72
+const FIRST_BUCKET = Date.parse('2026-08-06T04:00:00Z')
+
+/** Buckets that exercise every state the chart draws: a learned band, an anomalous spike and drop
+ * against it, a silence, and a trailing unscored stretch where the band has to break. */
+function buildBuckets(): LogsAnomalyScanBucketApi[] {
+ return Array.from({ length: BUCKETS }, (_, index) => {
+ const time = new Date(FIRST_BUCKET + index * BUCKET_MINUTES * 60_000).toISOString()
+ // A slow sine keeps the baseline uneven without a random source.
+ const expected = Math.round(400 + 120 * Math.sin(index / 5))
+ const scored = index < BUCKETS - 8
+ const verdict = index === 24 ? 'spike' : index === 44 ? 'drop' : index === 52 ? 'silence' : null
+ const observed =
+ verdict === 'spike'
+ ? expected * 4
+ : verdict === 'drop'
+ ? Math.round(expected * 0.2)
+ : verdict === 'silence'
+ ? 0
+ : expected
+
+ return {
+ time,
+ observed,
+ expected: scored ? expected : null,
+ lower: scored ? Math.round(expected * 0.6) : null,
+ upper: scored ? Math.round(expected * 1.4) : null,
+ stage: scored ? 'mature' : null,
+ verdict,
+ }
+ })
+}
+
+const meta: Meta<typeof AnomalyBandChart> = {
+ title: 'Logs/AnomalyBandChart',
+ component: AnomalyBandChart,
+ args: {
+ buckets: buildBuckets(),
+ },
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ mockDate: '2026-08-06',
+ // The line and band paint asynchronously (ResizeObserver → rAF); chromium alone keeps the
+ // snapshot stable.
+ testOptions: { snapshotBrowsers: ['chromium'], waitForSelector: 'canvas[aria-label]' },
+ },
+ render: (args) => (
+ <div className="w-[720px] rounded border bg-surface-primary p-3">
+ <AnomalyBandChart {...args} />
+ </div>
+ ),
+}
+
+export default meta
+
+/** What `LogsAnomalies` renders per severity: observed volume against the learned band, with the
+ * anomalous buckets marked and the unscored tail left as a gap. */
+export const ObservedVsExpected: StoryObj<typeof AnomalyBandChart> = {}
diff --git a/products/logs/frontend/components/AnomalyBandChart.test.ts b/products/logs/frontend/components/AnomalyBandChart.test.ts
index 32b186110313..7be03b03979f 100644
--- a/products/logs/frontend/components/AnomalyBandChart.test.ts
+++ b/products/logs/frontend/components/AnomalyBandChart.test.ts
@@ -1,6 +1,6 @@
import type { LogsAnomalyScanBucketApi } from 'products/logs/frontend/generated/api.schemas'
-import { buildBandChartData } from './AnomalyBandChart'
+import { bucketRange, buildBandChartData } from './AnomalyBandChart'
function bucket(overrides: Partial<LogsAnomalyScanBucketApi>): LogsAnomalyScanBucketApi {
return {
@@ -15,32 +15,56 @@ function bucket(overrides: Partial<LogsAnomalyScanBucketApi>): LogsAnomalyScanBu
}
}
-describe('buildBandChartData', () => {
- it('keeps unscored band values as null instead of coercing to zero', () => {
- // A null band coerced to 0 would render every unscored region as a
- // drop to zero, which is exactly the misreading the chart must avoid.
- const data = buildBandChartData([
- bucket({}),
- bucket({ time: '2026-08-06T10:05:00Z', expected: null, lower: null, upper: null, stage: null }),
- ])
- expect(data.lower).toEqual([4, null])
- expect(data.upper).toEqual([21, null])
- expect(data.observed).toEqual([12, 12])
- })
+describe('AnomalyBandChart', () => {
+ describe('buildBandChartData', () => {
+ it('leaves unscored band values non-finite instead of coercing to zero', () => {
+ // A null band coerced to 0 would render every unscored region as a
+ // drop to zero, which is exactly the misreading the chart must avoid.
+ // The band breaks at a non-finite value, which is how the gap is drawn.
+ const data = buildBandChartData([
+ bucket({}),
+ bucket({ time: '2026-08-06T10:05:00Z', expected: null, lower: null, upper: null, stage: null }),
+ ])
+ expect(data.lower).toEqual([4, NaN])
+ expect(data.upper).toEqual([21, NaN])
+ expect(data.observed).toEqual([12, 12])
+ })
+
+ it('carries verdicts positionally so anomalous points can be highlighted', () => {
+ const data = buildBandChartData([
+ bucket({}),
+ bucket({ time: '2026-08-06T10:05:00Z', observed: 47, verdict: 'spike' }),
+ ])
+ expect(data.verdicts).toEqual([null, 'spike'])
+ })
- it('carries verdicts positionally so anomalous points can be highlighted', () => {
- const data = buildBandChartData([
- bucket({}),
- bucket({ time: '2026-08-06T10:05:00Z', observed: 47, verdict: 'spike' }),
- ])
- expect(data.verdicts).toEqual([null, 'spike'])
+ it('labels buckets with their raw times so the time axis can format them', () => {
+ // Pre-formatted display strings would be printed verbatim by the time axis, which
+ // costs the interval-aware ticks and the tooltip's date header.
+ const data = buildBandChartData([bucket({}), bucket({ time: '2026-08-06T10:05:00Z' })])
+ expect(data.labels).toEqual(['2026-08-06T10:00:00Z', '2026-08-06T10:05:00Z'])
+ })
})
- it('switches label format when the window spans multiple days', () => {
- const sameDay = buildBandChartData([bucket({}), bucket({ time: '2026-08-06T10:05:00Z' })])
- expect(sameDay.labels[0]).toMatch(/^\d{2}:\d{2}$/)
+ describe('bucketRange', () => {
+ const buckets = ['10:00', '10:05', '10:10', '10:15'].map((time) => bucket({ time: `2026-08-06T${time}:00Z` }))
+
+ // Every index names a bucket start. A range ending at the last bucket's start would scan
+ // and link to everything except the bucket the user actually picked, and a single-bucket
+ // click would resolve to an empty window.
+ it.each([
+ { name: 'a drag across buckets', start: 0, end: 2, from: '10:00:00Z', to: '10:15:00.000Z' },
+ { name: 'a click on one bucket', start: 1, end: 1, from: '10:05:00Z', to: '10:10:00.000Z' },
+ { name: 'a right-to-left drag', start: 2, end: 0, from: '10:00:00Z', to: '10:15:00.000Z' },
+ ])('covers whole buckets for $name', ({ start, end, from, to }) => {
+ expect(bucketRange(buckets, start, end)).toEqual({
+ dateFrom: `2026-08-06T${from}`,
+ dateTo: `2026-08-06T${to}`,
+ })
+ })
- const multiDay = buildBandChartData([bucket({}), bucket({ time: '2026-08-07T10:00:00Z' })])
- expect(multiDay.labels[0]).toMatch(/^[A-Z][a-z]{2} \d{1,2} \d{2}:\d{2}$/)
+ it('returns null when the bucket width cannot be derived', () => {
+ expect(bucketRange([bucket({})], 0, 0)).toBeNull()
+ })
})
})
diff --git a/products/logs/frontend/components/AnomalyBandChart.tsx b/products/logs/frontend/components/AnomalyBandChart.tsx
index c99f7b0fff30..8aa3617e9f65 100644
--- a/products/logs/frontend/components/AnomalyBandChart.tsx
+++ b/products/logs/frontend/components/AnomalyBandChart.tsx
@@ -1,140 +1,188 @@
+import { useCallback, useMemo } from 'react'
+
+import {
+ AnomalyPointsLayer,
+ DEFAULT_Y_AXIS_ID,
+ DefaultTooltip,
+ TimeSeriesLineChart,
+ type AnomalyMarker,
+ type DateRangeZoomData,
+ type PointClickData,
+ type Series,
+ type TimeSeriesLineChartConfig,
+ type TooltipContext,
+} from '@posthog/quill-charts'
+
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
import { dayjs } from 'lib/dayjs'
-import { useChart } from 'lib/hooks/useChart'
import { humanFriendlyNumber } from 'lib/utils/numbers'
import type { LogsAnomalyScanBucketApi, LogsAnomalyVerdictEnumApi } from 'products/logs/frontend/generated/api.schemas'
+import type { ScanRange } from 'products/logs/frontend/logsAnomaliesLogic'
+
+const OBSERVED_KEY = 'observed'
export interface BandChartData {
labels: string[]
observed: number[]
- lower: (number | null)[]
- upper: (number | null)[]
+ lower: number[]
+ upper: number[]
verdicts: (LogsAnomalyVerdictEnumApi | null)[]
}
-// Band values stay null for unscored buckets so the chart shows a gap there.
-// Coercing them to 0 would render every unscored region as a drop to zero.
+// Band values stay NaN for unscored buckets so the chart shows a gap there. Coercing them to 0
+// would render every unscored region as a drop to zero.
export function buildBandChartData(buckets: LogsAnomalyScanBucketApi[]): BandChartData {
- const spansMultipleDays =
- buckets.length > 1 && !dayjs(buckets[0].time).isSame(dayjs(buckets[buckets.length - 1].time), 'day')
- const format = spansMultipleDays ? 'MMM D HH:mm' : 'HH:mm'
return {
- labels: buckets.map((bucket) => dayjs(bucket.time).format(format)),
+ // Raw bucket times: the time axis formats the ticks, so it can switch to day boundaries on a
+ // multi-day window without every label being baked at one width.
+ labels: buckets.map((bucket) => bucket.time),
observed: buckets.map((bucket) => bucket.observed),
- lower: buckets.map((bucket) => bucket.lower),
- upper: buckets.map((bucket) => bucket.upper),
+ lower: buckets.map((bucket) => bucket.lower ?? NaN),
+ upper: buckets.map((bucket) => bucket.upper ?? NaN),
verdicts: buckets.map((bucket) => bucket.verdict),
}
}
+/** Matches the verdict tags above each chart, and follows the theme rather than pinning one shade. */
const VERDICT_POINT_COLOR: Record<LogsAnomalyVerdictEnumApi, string> = {
- spike: 'rgba(220, 38, 38, 0.92)',
- drop: 'rgba(234, 88, 12, 0.9)',
- silence: 'rgba(127, 29, 29, 1)',
+ spike: 'var(--danger)',
+ drop: 'var(--warning)',
+ silence: 'var(--danger-dark)',
+}
+
+/** Both indices name a bucket *start*, so the range has to run to the end of the last one. A range
+ * ending at its start would exclude the very bucket the user dragged over or clicked. Bucket width
+ * comes from the first gap rather than the scan's constant, so the two can't drift. */
+export function bucketRange(
+ buckets: LogsAnomalyScanBucketApi[],
+ startIndex: number,
+ endIndex: number
+): ScanRange | null {
+ const [from, to] = startIndex <= endIndex ? [startIndex, endIndex] : [endIndex, startIndex]
+ const start = buckets[from]?.time
+ const end = buckets[to]?.time
+ if (!start || !end || buckets.length < 2) {
+ return null
+ }
+ const bucketMs = Date.parse(buckets[1].time) - Date.parse(buckets[0].time)
+ if (!(bucketMs > 0)) {
+ return null
+ }
+ return { dateFrom: start, dateTo: new Date(Date.parse(end) + bucketMs).toISOString() }
+}
+
+export interface AnomalyBandChartProps {
+ buckets: LogsAnomalyScanBucketApi[]
+ onZoom?: (range: ScanRange) => void
+ onBucketClick?: (range: ScanRange) => void
}
-export function AnomalyBandChart({ buckets }: { buckets: LogsAnomalyScanBucketApi[] }): JSX.Element {
- const data = buildBandChartData(buckets)
-
- const { canvasRef } = useChart({
- getConfig: () => ({
- type: 'line' as const,
- data: {
- labels: data.labels,
- datasets: [
- {
- label: 'Upper band',
- data: data.upper,
- borderColor: 'rgba(59, 130, 246, 0.35)',
- borderWidth: 1,
- pointRadius: 0,
- fill: false,
- spanGaps: false,
- },
- {
- label: 'Lower band',
- data: data.lower,
- borderColor: 'rgba(59, 130, 246, 0.35)',
- backgroundColor: 'rgba(59, 130, 246, 0.12)',
- borderWidth: 1,
- pointRadius: 0,
- fill: '-1',
- spanGaps: false,
- },
- {
- label: 'Observed',
- data: data.observed,
- borderColor: 'rgba(30, 64, 175, 0.9)',
- borderWidth: 1.5,
- fill: false,
- pointRadius: (context) => (data.verdicts[context.dataIndex] ? 4 : 0),
- pointHoverRadius: (context) => (data.verdicts[context.dataIndex] ? 5 : 3),
- pointBackgroundColor: (context) => {
- const verdict = data.verdicts[context.dataIndex]
- return verdict ? VERDICT_POINT_COLOR[verdict] : 'transparent'
- },
- pointBorderColor: (context) => {
- const verdict = data.verdicts[context.dataIndex]
- return verdict ? VERDICT_POINT_COLOR[verdict] : 'transparent'
- },
- },
- ],
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- animation: false as const,
- interaction: { mode: 'nearest' as const, axis: 'x' as const, intersect: false },
- plugins: {
- legend: { display: false },
- tooltip: {
- enabled: true,
- filter: (item) => item.dataset.label === 'Observed',
- callbacks: {
- title: (items) => (items[0] ? String(items[0].label) : ''),
- label: (context) => {
- const bucket = buckets[context.dataIndex]
- const verdict = data.verdicts[context.dataIndex]
- const suffix = verdict ? ` (${verdict})` : ''
- return `Observed: ${humanFriendlyNumber(bucket.observed)}${suffix}`
- },
- afterLabel: (context) => {
- const bucket = buckets[context.dataIndex]
- if (bucket.expected == null || bucket.lower == null || bucket.upper == null) {
- return 'Not scored'
- }
- return `Expected: ${humanFriendlyNumber(bucket.expected)} (band ${humanFriendlyNumber(
- bucket.lower
- )} to ${humanFriendlyNumber(bucket.upper)})`
- },
- },
- },
- },
- scales: {
- x: {
- display: true,
- ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8, font: { size: 9 } },
- grid: { display: false },
- },
- y: {
- display: true,
- beginAtZero: true,
- ticks: {
- maxTicksLimit: 5,
- font: { size: 10 },
- callback: (value: string | number) => humanFriendlyNumber(Number(value)),
- },
- grid: { color: 'rgba(0, 0, 0, 0.06)' },
- },
- },
- },
+export function AnomalyBandChart({ buckets, onZoom, onBucketClick }: AnomalyBandChartProps): JSX.Element {
+ const theme = useChartTheme()
+ const data = useMemo(() => buildBandChartData(buckets), [buckets])
+
+ const series = useMemo<Series[]>(
+ () => [{ key: OBSERVED_KEY, label: 'Observed', data: data.observed }],
+ [data.observed]
+ )
+
+ // A verdict's color varies per bucket, which an area fill can't express, so the anomalous points
+ // are their own overlay rather than a second series.
+ const markers = useMemo<AnomalyMarker[]>(
+ () =>
+ buckets.flatMap((bucket, index) =>
+ bucket.verdict
+ ? [
+ {
+ dataIndex: index,
+ value: bucket.observed,
+ color: VERDICT_POINT_COLOR[bucket.verdict],
+ yAxisId: DEFAULT_Y_AXIS_ID,
+ },
+ ]
+ : []
+ ),
+ [buckets]
+ )
+
+ const config = useChartConfig<TimeSeriesLineChartConfig>(
+ () => ({
+ // Bucket times are UTC, and the scan's own timestamps around this chart render in the
+ // viewer's zone, so the axis reads there too. The scan buckets at a fixed few minutes.
+ xAxis: { timezone: dayjs.tz.guess(), interval: 'minute' },
+ yAxis: { tickFormatter: humanFriendlyNumber },
+ confidenceIntervals: [{ seriesKey: OBSERVED_KEY, lower: data.lower, upper: data.upper }],
}),
- deps: [buckets],
- })
+ [data.lower, data.upper]
+ )
+
+ const onDateRangeZoom = useMemo(
+ () =>
+ onZoom
+ ? ({ startIndex, endIndex }: DateRangeZoomData) => {
+ const range = bucketRange(buckets, startIndex, endIndex)
+ if (range) {
+ onZoom(range)
+ }
+ }
+ : undefined,
+ [buckets, onZoom]
+ )
+
+ const onPointClick = useMemo(
+ () =>
+ onBucketClick
+ ? ({ dataIndex }: PointClickData) => {
+ const range = bucketRange(buckets, dataIndex, dataIndex)
+ if (range) {
+ onBucketClick(range)
+ }
+ }
+ : undefined,
+ [buckets, onBucketClick]
+ )
+
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext): JSX.Element => {
+ const bucket = buckets[ctx.dataIndex]
+ const verdict = bucket?.verdict
+ return (
+ <DefaultTooltip
+ {...ctx}
+ labelFormatter={(label) => dayjs(label).format('MMM D, HH:mm')}
+ valueFormatter={(value) => `${humanFriendlyNumber(value)}${verdict ? ` (${verdict})` : ''}`}
+ footer={bucket ? bandSummary(bucket) : null}
+ />
+ )
+ },
+ [buckets]
+ )
return (
- <div className="h-40 w-full">
- <canvas ref={canvasRef} />
+ // Quill chart roots are `flex-1`, so the sized box has to be a flex column.
+ <div className="h-40 w-full flex flex-col">
+ <TimeSeriesLineChart
+ series={series}
+ labels={data.labels}
+ theme={theme}
+ config={config}
+ tooltip={renderTooltip}
+ onDateRangeZoom={onDateRangeZoom}
+ onPointClick={onPointClick}
+ dataAttr="logs-anomaly-band-chart"
+ >
+ <AnomalyPointsLayer markers={markers} radius={4} />
+ </TimeSeriesLineChart>
</div>
)
}
+
+function bandSummary(bucket: LogsAnomalyScanBucketApi): string {
+ if (bucket.expected == null || bucket.lower == null || bucket.upper == null) {
+ return 'Not scored'
+ }
+ return `Expected ${humanFriendlyNumber(bucket.expected)} (band ${humanFriendlyNumber(
+ bucket.lower
+ )} to ${humanFriendlyNumber(bucket.upper)})`
+}
diff --git a/products/logs/frontend/logsAnomaliesLogic.tsx b/products/logs/frontend/logsAnomaliesLogic.tsx
index 550ca1d91a59..e308eb02bb23 100644
--- a/products/logs/frontend/logsAnomaliesLogic.tsx
+++ b/products/logs/frontend/logsAnomaliesLogic.tsx
@@ -21,6 +21,12 @@ export const SCAN_WINDOW_OPTIONS: LemonSelectOption<number>[] = [
export const DEFAULT_SCAN_WINDOW_HOURS = 24
+/** An explicit window dragged out on a chart, which overrides the preset until it is cleared. */
+export interface ScanRange {
+ dateFrom: string
+ dateTo: string
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicValues {
currentTeamId: number | null // teamLogic
@@ -29,10 +35,14 @@ export interface logsAnomaliesLogicValues {
scanResultLoading: boolean
serviceName: string | null
windowHours: number
+ zoomedRange: ScanRange | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsAnomaliesLogicActions {
+ resetZoom: () => {
+ value: true
+ }
runScan: () => any
runScanFailure: (
error: string,
@@ -54,6 +64,9 @@ export interface logsAnomaliesLogicActions {
setWindowHours: (windowHours: number) => {
windowHours: number
}
+ zoomToRange: (range: ScanRange) => {
+ range: ScanRange
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -76,6 +89,8 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
actions({
setServiceName: (serviceName: string | null) => ({ serviceName }),
setWindowHours: (windowHours: number) => ({ windowHours }),
+ zoomToRange: (range: ScanRange) => ({ range }),
+ resetZoom: true,
}),
loaders(({ values }) => ({
scanResult: [
@@ -86,11 +101,12 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
return values.scanResult
}
const now = dayjs.utc()
+ const { zoomedRange } = values
return await logsAnomaliesScanCreate(String(values.currentTeamId), {
serviceName: values.serviceName,
dateRange: {
- date_from: now.subtract(values.windowHours, 'hour').toISOString(),
- date_to: now.toISOString(),
+ date_from: zoomedRange?.dateFrom ?? now.subtract(values.windowHours, 'hour').toISOString(),
+ date_to: zoomedRange?.dateTo ?? now.toISOString(),
},
})
},
@@ -110,6 +126,15 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
setWindowHours: (_, { windowHours }) => windowHours,
},
],
+ zoomedRange: [
+ null as ScanRange | null,
+ {
+ zoomToRange: (_, { range }) => range,
+ resetZoom: () => null,
+ // Picking a preset is the other way back out of a zoom.
+ setWindowHours: () => null,
+ },
+ ],
}),
selectors({
scanDisabledReason: [
@@ -125,10 +150,14 @@ export const logsAnomaliesLogic = kea<logsAnomaliesLogicType>([
},
],
}),
- listeners(() => ({
+ listeners(({ actions }) => ({
runScanFailure: ({ error }) => {
// ApiError already extracts the endpoint's { error } body into the message.
lemonToast.error(error || 'The anomaly scan failed. Try a shorter window.')
},
+ // Zooming rescans on its own, because a drag that left the previous window on screen would
+ // read as having done nothing. The preset select keeps its explicit Scan button.
+ zoomToRange: () => actions.runScan(),
+ resetZoom: () => actions.runScan(),
})),
])