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 viewer volume chart with quill charts (#83220)

Sam Penningtonf49cf5783992
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1d7f9fa38550..796b65c9364c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -577,9 +577,9 @@ snapshots:
components-hogcharts-barchart--grouped--light:
hash: v1.k794b7964.03cf5aea076941f1c72940a8ef54320900b81e98ca85e6674d3bcffb1248ecc9.9jxIF7qRonS1YfjjqPD0m8UQc-Ud-3ew5RUtQh5IOqk
components-hogcharts-barchart--hatched-bars--dark:
- hash: v1.k794b7964.013dbdd0502538368745b1c26e0cd2a5f3b0728a3b601fdf67a25365f6001581.oAdsc4dQiNuxFicZQb3YdWpSfkXRbrMNy7hth6a6TXw
+ hash: v1.k794b7964.6261887537d9c02c140db15599f6fb80d75c70c0fbaaec9a1a39eee759b1e795.a8vJ2DDVa8nWaQLoccAbmm3rFsJz5d_OgLt8n6ShW6w
components-hogcharts-barchart--hatched-bars--light:
- hash: v1.k794b7964.073920f88142793533a52faa925fc1b0eef7ef8236cbe23f330ab7b28e79a58e.0tcVwLSfb_hZIgxGSNzSeP0siFbwthVTeee1is2PrF0
+ hash: v1.k794b7964.91fabb6ff0857ad43d6ee660354803170ae0a53c83b14fb7c0a448f208a61113.U46g7PDOpWseIiELLLKCLLvyGI_sGf_RY8IG0jSZamQ
components-hogcharts-barchart--hidden-series--dark:
hash: v1.k794b7964.bffd963b8ac70f817ed0db90173f1e898f7aa19a1df03b90ce0e4c3aebbbb7d8.oP-Z_iQE8f7x8deR7JBK-Crc5if_9vMH4lixukVJO7U
components-hogcharts-barchart--hidden-series--light:
@@ -601,9 +601,9 @@ snapshots:
components-hogcharts-barchart--horizontal-wide-value-labels--light:
hash: v1.k794b7964.cef7cd7e190817224115d35f5402dc94aadc3a033be1e416bd52c6783096c686.U1kVYnyzlZTciZAHczBsbu9LvQ3yVhqGGroHdcjtepI
components-hogcharts-barchart--incomplete-period--dark:
- hash: v1.k794b7964.7d81e34fb7027b4a14847300bef51faf9f255c427eb2ce506402630635a47061.D35g4pAVQjz0SaKEc1lvHHFqZgEO7RgyiXy5hQtKwJA
+ hash: v1.k794b7964.43f3ede0f6af5880a51c85048f3628566d614c8ae12f30cf68e072f2e4a73ae9.PA7sl-J66x4XLCrRMN6G2vPzsljewHVo1C1l5Nd0KPM
components-hogcharts-barchart--incomplete-period--light:
- hash: v1.k794b7964.2f99c6605b24b2b7cd3158262cba4f6073114d7bd1e22ffea1e9b4b98d056d2e.qW78fG0cYDYBUYOY8zQXiRsYK_N7-dQ0reIQAn0BwBA
+ hash: v1.k794b7964.d1184bbd3cb83434ae0743050e06856996678dbc07ea8478f6444e12e7c485d3.xCKaSr-LdXRrMHFpoGvNS5EIlJUZ5xi9kJMZpub_L4w
components-hogcharts-barchart--large-dataset--dark:
hash: v1.k794b7964.095574cf8c5bebb6a162cfb8a34e471063b44373874026b49fd15e51bb722486.FV48NiohLU1O73Z-XFDgEHkEEU6KvGCsu_sNx7axGo4
components-hogcharts-barchart--large-dataset--light:
@@ -6976,6 +6976,18 @@ snapshots:
hash: v1.k794b7964.195aa4a5a39e8f947e17fe67f5c23303b7dd0579c278907761be24a08780be92.t2Zgr2Pj-cL6F6Xx11DpcCyR1L0QQ8fD17WzQNmXbw8
scenes-app-llm-observability-evaluationreportconfig--quill--light:
hash: v1.k794b7964.e6179df07dd55d64e0140d40ac812feb4662e28e5bded7ce2cf9e2575f245626.4iGTruUDV858d17xZIUMJCG2xFeWLagkzakPS2Yw4Ps
+ scenes-app-logs-sparkline--volume-by-severity--dark:
+ hash: v1.k794b7964.ff9970e481267669b2b5c3e97de2daa5027224b3185da86e7841374a1c0ba80e.sStnKO155v5mRB-N445BcUDcc21g3jAW21Y5mDWfENw
+ scenes-app-logs-sparkline--volume-by-severity--light:
+ hash: v1.k794b7964.8de90a8725adae02f3eb5ddff7b67a8b82635f4ee91a6fc8af918f847f3112aa.b71G5RHdgthOOmza6oa2KGdiK2bsMtGDdql7kyjlEUE
+ scenes-app-logs-sparkline--with-incomplete-buckets--dark:
+ hash: v1.k794b7964.d18b5bd8acb1c3cc0a815e002bd50d8382c4ed2bcc0d52975188d10565c094e8.lDTMLtBVAMn0BR_tMDOTiJkqQgTSmRMrBHUVjhcmWng
+ scenes-app-logs-sparkline--with-incomplete-buckets--light:
+ hash: v1.k794b7964.ffcdf956d00fbd9c97d8843d86e1781202ba0da513e45594267dba56443ad824.IjOA2xr2ZUEtBos84aXnc_oogjc71FmgQf0lZGnyndw
+ scenes-app-logs-sparkline--with-visible-row-range--dark:
+ hash: v1.k794b7964.6e7205adb133ed51c4e5c4822801101628929a2670208a3380051bd366ef1014.CjJZblD1hifo0CPfzGvsF5nuJbYoq3jTSZ1ZT9uXJPk
+ scenes-app-logs-sparkline--with-visible-row-range--light:
+ hash: v1.k794b7964.b0f371959dd1ba3224600f73c6ce704356527d7e47eb2059391a4c6c340a098b.-AV9dQHySpjijS8TCrCM0nW459TOjWY356UVly4uCoo
scenes-app-marketing-analytics-cell-actions--campaign-cell-action-globally-mapped--dark:
hash: v1.k794b7964.52cf1cc9ecc8ac0c8dc3ff23da8f0e0f2605629c3df6ecbb5ed9608f570c4784.NtNmI3-76PkNhp-wrgqn8-92duqzx8Svtopeh0m9xw8
scenes-app-marketing-analytics-cell-actions--campaign-cell-action-globally-mapped--light:
diff --git a/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts b/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts
index 8fc6b1ed951b..cd0b5d4e0e0f 100644
--- a/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts
+++ b/packages/quill/packages/charts/src/core/bar-canvas-renderer.test.ts
@@ -217,7 +217,7 @@ describe('hog-charts canvas-renderer (bars)', () => {
bar({ x: 60, dataIndex: 1 }),
bar({ x: 120, dataIndex: 2 }),
])
- expect(ctx.fill).toHaveBeenCalledTimes(3)
+ expect(ctx.fill).toHaveBeenCalledTimes(5)
})
it('fills all bars when partial toIndex is set', () => {
@@ -234,7 +234,7 @@ describe('hog-charts canvas-renderer (bars)', () => {
bar({ x: 60, dataIndex: 1 }),
bar({ x: 120, dataIndex: 2 }),
])
- expect(ctx.fill).toHaveBeenCalledTimes(3)
+ expect(ctx.fill).toHaveBeenCalledTimes(4)
})
it('hatches bars by their dataIndex, not their array position (filtered bars stay correct)', () => {
@@ -264,8 +264,8 @@ describe('hog-charts canvas-renderer (bars)', () => {
Object.defineProperty(ctx, 'fillStyle', original)
}
expect(fillStyleSeen[0]).toBe('#11223344')
- expect(typeof fillStyleSeen[1]).not.toBe('string')
expect(typeof fillStyleSeen[2]).not.toBe('string')
+ expect(typeof fillStyleSeen[4]).not.toBe('string')
})
it('hatches individual bars flagged via bars[i].hatch, including non-contiguous indices', () => {
@@ -296,9 +296,9 @@ describe('hog-charts canvas-renderer (bars)', () => {
} finally {
Object.defineProperty(ctx, 'fillStyle', original!)
}
- expect(typeof fillStyleSeen[0]).not.toBe('string')
- expect(fillStyleSeen[1]).toBe('#55667788')
- expect(typeof fillStyleSeen[2]).not.toBe('string')
+ expect(typeof fillStyleSeen[1]).not.toBe('string')
+ expect(fillStyleSeen[2]).toBe('#55667788')
+ expect(typeof fillStyleSeen[4]).not.toBe('string')
})
it('respects the cornerRadius option', () => {
diff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.ts
index a68f5feb888a..0701232a06be 100644
--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts
+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts
@@ -393,18 +393,26 @@ function resolvePartialIndex(idx: number | undefined, length: number): number |
const hatchPatternCache = new Map<string, CanvasPattern>()
function getHatchPattern(ctx: CanvasRenderingContext2D, color: string): CanvasPattern | string {
- const cached = hatchPatternCache.get(color)
+ // The draw context is transform-scaled to device pixels, so a tile authored in CSS pixels would
+ // be upscaled and blur. Read the ratio off the backing store rather than `window.devicePixelRatio`
+ // for the reason in `clearAndPrepare`: a redraw can run at a different ratio than sized the canvas.
+ const backing = ctx.canvas
+ const dpr = backing && backing.width > 0 ? backing.width / (backing.clientWidth || backing.width) : 1
+ const scale = dpr > 0 && Number.isFinite(dpr) ? dpr : 1
+ const size = 14
+ const key = `${color}@${scale}`
+ const cached = hatchPatternCache.get(key)
if (cached) {
return cached
}
- const size = 14
const patCanvas = document.createElement('canvas')
- patCanvas.width = size
- patCanvas.height = size
+ patCanvas.width = Math.max(1, Math.round(size * scale))
+ patCanvas.height = Math.max(1, Math.round(size * scale))
const patCtx = patCanvas.getContext('2d')
if (!patCtx) {
return color
}
+ patCtx.scale(scale, scale)
patCtx.strokeStyle = color
patCtx.lineWidth = 4
patCtx.beginPath()
@@ -421,7 +429,11 @@ function getHatchPattern(ctx: CanvasRenderingContext2D, color: string): CanvasPa
patCtx.stroke()
const pattern = ctx.createPattern(patCanvas, 'repeat')
if (pattern) {
- hatchPatternCache.set(color, pattern)
+ // Undo the backing scale so one bitmap pixel lands on one device pixel.
+ if (scale !== 1 && typeof pattern.setTransform === 'function' && typeof DOMMatrix === 'function') {
+ pattern.setTransform(new DOMMatrix([1 / scale, 0, 0, 1 / scale, 0, 0]))
+ }
+ hatchPatternCache.set(key, pattern)
return pattern
}
return color
@@ -1156,13 +1168,35 @@ export function drawBars(
// The hatch keeps the bar's own resolved color (per-bar override included) so a
// flagged bar still reads as belonging to its series. Pattern lookups are cached.
const barColor = barColorAt(series, bar.dataIndex)
- ctx.fillStyle = useHatch ? getHatchPattern(ctx, barColor) : makeBarFill(ctx, barColor, bar, fillStyle)
ctx.beginPath()
traceRoundedBarPath(ctx, bar.x, bar.y, bar.width, bar.height, cornerRadius, bar.corners)
+ if (useHatch) {
+ drawHatchedBarFill(ctx, barColor)
+ continue
+ }
+ ctx.fillStyle = makeBarFill(ctx, barColor, bar, fillStyle)
ctx.fill()
}
}
+// Deliberately higher than the `BAR_TRACK_*` pair above, which the same construction uses. A track
+// is a backdrop meant to recede, whereas a flagged bar carries the bucket's actual count, so at
+// track alpha it would read as an empty bucket rather than one that is still filling.
+const HATCHED_BAR_BASE_ALPHA = 0.25
+const HATCHED_BAR_HATCH_ALPHA = 0.65
+
+/** Fills the already-traced path as a hatched bar. Owns save/restore. */
+function drawHatchedBarFill(ctx: CanvasRenderingContext2D, color: string): void {
+ ctx.save()
+ ctx.globalAlpha = HATCHED_BAR_BASE_ALPHA
+ ctx.fillStyle = color
+ ctx.fill()
+ ctx.globalAlpha = HATCHED_BAR_HATCH_ALPHA
+ ctx.fillStyle = getHatchPattern(ctx, color)
+ ctx.fill()
+ ctx.restore()
+}
+
// Tracks render as a tinted base under hatched stripes — same construction as the legacy
// funnel backdrop (`var(--series-color)` behind `repeating-linear-gradient` stripes), so the
// whole region reads as continuously filled rather than as bare stripes on the background.
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index c42206015347..ddd28737c4f6 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -25,6 +25,7 @@ import { logDetailsModalLogic } from './LogDetailsModal/logDetailsModalLogic'
import { LogsDisplayBar } from './LogsDisplayBar'
import { logsViewerLogic } from './logsViewerLogic'
import { LogsSparkline } from './LogsViewerSparkline'
+import type { LogsViewerSparklineProps } from './LogsViewerSparkline'
const SCROLL_INTERVAL_MS = 16 // ~60fps
const SCROLL_AMOUNT_PX = 8
@@ -79,6 +80,14 @@ export function LogsViewer({
)
}
+/** `visibleRowDateRange` changes on every scroll tick, so it is subscribed here rather than in
+ * `LogsViewerContent`, where it would re-render the row list and facet rail on each one.
+ * `LogsSparkline` stays prop-driven so it can render in a story without the keyed logic. */
+function ConnectedLogsSparkline(props: Omit<LogsViewerSparklineProps, 'visibleRowDateRange'>): JSX.Element | null {
+ const { visibleRowDateRange } = useValues(logsViewerLogic)
+ return <LogsSparkline {...props} visibleRowDateRange={visibleRowDateRange} />
+}
+
function LogsViewerContent({
showFullScreenButton,
showSavedViewsButton,
@@ -295,7 +304,7 @@ function LogsViewerContent({
const sparklineSection = (
<>
- <LogsSparkline
+ <ConnectedLogsSparkline
sparklineData={sparklineData}
sparklineLoading={sparklineLoading}
onDateRangeChange={setDateRange}
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/LogsViewerSparkline.stories.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/LogsViewerSparkline.stories.tsx
new file mode 100644
index 000000000000..3c3f9e1823d8
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/LogsViewerSparkline.stories.tsx
@@ -0,0 +1,78 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+
+import { OTHER_BREAKDOWN_LABEL } from 'products/logs/frontend/sparklineOtherBreakdown'
+
+import { LogsSparkline, LogsSparklineData } from './index'
+
+const BUCKET_SECONDS = 90
+const BUCKETS = 48
+const FIRST_BUCKET = Date.parse('2026-08-06T09:00:00Z')
+
+const SEVERITY_PROFILES: { name: string; color: string; baseline: number }[] = [
+ { name: 'info', color: 'brand-blue', baseline: 320 },
+ { name: 'warn', color: 'warning', baseline: 90 },
+ { name: 'error', color: 'danger', baseline: 40 },
+ { name: OTHER_BREAKDOWN_LABEL, color: 'muted', baseline: 25 },
+]
+
+function buildSparklineData(): LogsSparklineData {
+ const dates = Array.from({ length: BUCKETS }, (_, bucket) =>
+ new Date(FIRST_BUCKET + bucket * BUCKET_SECONDS * 1000).toISOString()
+ )
+ return {
+ dates,
+ data: SEVERITY_PROFILES.map(({ name, color, baseline }) => ({
+ name,
+ color,
+ values: dates.map((_, bucket) => Math.round(baseline * (1 + 0.4 * Math.sin(bucket / 5)))),
+ })),
+ }
+}
+
+const meta: Meta<typeof LogsSparkline> = {
+ title: 'Scenes-App/Logs/Sparkline',
+ component: LogsSparkline,
+ args: {
+ sparklineData: buildSparklineData(),
+ sparklineLoading: false,
+ displayTimezone: 'UTC',
+ breakdownBy: 'severity',
+ collapsed: false,
+ },
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ mockDate: '2026-08-06',
+ featureFlags: [FEATURE_FLAGS.LOGS_SPARKLINE_SERVICE_BREAKDOWN],
+ // Bars paint asynchronously (ResizeObserver, then rAF); chromium alone keeps the snapshot stable.
+ testOptions: { snapshotBrowsers: ['chromium'] },
+ },
+ render: (args) => (
+ <div className="w-[900px]">
+ <LogsSparkline {...args} />
+ </div>
+ ),
+}
+
+export default meta
+
+type Story = StoryObj<typeof LogsSparkline>
+
+export const VolumeBySeverity: Story = {}
+
+export const WithIncompleteBuckets: Story = {
+ args: {
+ incompleteBarIndices: [45, 46, 47],
+ },
+}
+
+export const WithVisibleRowRange: Story = {
+ args: {
+ visibleRowDateRange: {
+ date_from: new Date(FIRST_BUCKET + 12 * BUCKET_SECONDS * 1000).toISOString(),
+ date_to: new Date(FIRST_BUCKET + 22 * BUCKET_SECONDS * 1000).toISOString(),
+ },
+ },
+}
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.test.ts b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.test.ts
new file mode 100644
index 000000000000..89ccfeecda16
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.test.ts
@@ -0,0 +1,29 @@
+import { highlightedBucketRange, selectedDateRange } from './bucketRanges'
+
+const BUCKETS = [0, 60_000, 120_000, 180_000]
+const BUCKET_TIMES = BUCKETS.map((ms) => new Date(ms).toISOString())
+
+describe('bucketRanges', () => {
+ it('ends a drag selection at the next bucket, so its last bucket is included', () => {
+ expect(selectedDateRange(BUCKET_TIMES, 1, 2)).toEqual({
+ date_from: BUCKET_TIMES[1],
+ date_to: BUCKET_TIMES[3],
+ })
+ })
+
+ it('leaves a drag selection open-ended when it runs to the final bucket', () => {
+ expect(selectedDateRange(BUCKET_TIMES, 2, 3)).toEqual({ date_from: BUCKET_TIMES[2], date_to: null })
+ })
+
+ it('snaps a highlight out to whole buckets', () => {
+ expect(highlightedBucketRange(BUCKETS, 90_000, 150_000)).toEqual({ startIndex: 1, endIndex: 2 })
+ })
+
+ it('highlights the final bucket for a window inside it', () => {
+ expect(highlightedBucketRange(BUCKETS, 190_000, 200_000)).toEqual({ startIndex: 3, endIndex: 3 })
+ })
+
+ it('highlights a lone bucket for a window starting after its start (open-ended width)', () => {
+ expect(highlightedBucketRange([60_000], 90_000, 150_000)).toEqual({ startIndex: 0, endIndex: 0 })
+ })
+})
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.ts b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.ts
new file mode 100644
index 000000000000..98a1e8ca521f
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/bucketRanges.ts
@@ -0,0 +1,54 @@
+import { DateRange } from '~/queries/schema/schema-general'
+
+/**
+ * The end is the *next* bucket's start, so the selection's last bucket stays inclusive.
+ *
+ * Past the final bucket the end must be `null`, not undefined: `utcDateRange` in
+ * `logsViewerFiltersLogic` normalizes via `dayjs(date_to)`, which reads undefined as the current
+ * time and would freeze the end there. `null` is invalid to dayjs, so the range stays open at "now".
+ */
+export function selectedDateRange(bucketTimes: string[], startIndex: number, endIndex: number): DateRange | null {
+ const dateFrom = bucketTimes[startIndex]
+ if (!dateFrom) {
+ return null
+ }
+ return { date_from: dateFrom, date_to: bucketTimes[endIndex + 1] ?? null }
+}
+
+/** Assumes ascending bucket times. */
+function containingBucket(bucketTimesMs: number[], ms: number): number {
+ let index = 0
+ while (index + 1 < bucketTimesMs.length && bucketTimesMs[index + 1] <= ms) {
+ index++
+ }
+ return index
+}
+
+/**
+ * Each end snaps to the bucket containing it, so the highlight covers whole bars. Callers already
+ * pass `fromMs <= toMs` (`visibleRowDateRange` normalises the order), so the ends are not re-sorted.
+ */
+export function highlightedBucketRange(
+ bucketTimesMs: number[],
+ fromMs: number,
+ toMs: number
+): { startIndex: number; endIndex: number } | null {
+ if (bucketTimesMs.length === 0 || !Number.isFinite(fromMs) || !Number.isFinite(toMs)) {
+ return null
+ }
+ // A bucket spans its own start to the next one's, so the charted range ends one interval past
+ // the last start. Measuring it by that start instead would drop a window sitting inside the
+ // final bucket, which is where the newest rows are on the default newest-first view.
+ const lastStart = bucketTimesMs[bucketTimesMs.length - 1]
+ // A lone bucket has no next start to measure its width from, so treat it as open-ended rather
+ // than zero-width — otherwise any window starting after its start (i.e. every row inside it)
+ // would fall past `lastStart` and drop the highlight.
+ const interval = bucketTimesMs.length > 1 ? bucketTimesMs[1] - bucketTimesMs[0] : Number.POSITIVE_INFINITY
+ if (toMs < bucketTimesMs[0] || fromMs > lastStart + interval) {
+ return null
+ }
+ return {
+ startIndex: containingBucket(bucketTimesMs, fromMs),
+ endIndex: containingBucket(bucketTimesMs, toMs),
+ }
+}
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
index a6ee853a3d67..74bd613f8cc3 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
@@ -1,18 +1,23 @@
-import { useValues } from 'kea'
import { useCallback, useMemo } from 'react'
import { IconChevronDown } from '@posthog/icons'
import { LemonButton, LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'
+import { DefaultTooltip, HighlightedRange, TimeSeriesBarChart } from '@posthog/quill-charts'
+import type { DateRangeZoomData, Series, TimeSeriesBarChartConfig, TooltipContext } from '@posthog/quill-charts'
-import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'
+import { useChartConfig, useChartTheme } from 'lib/charts/hooks'
+import { getColorVar } from 'lib/colors'
import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { cn } from 'lib/utils/css-classes'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
import { shortTimeZone } from 'lib/utils/timezones'
import { DateRange, LogsSparklineBreakdownBy } from '~/queries/schema/schema-general'
-import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'
+import type { VisibleLogsTimeRange } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'
+
+import { highlightedBucketRange, selectedDateRange } from './bucketRanges'
export interface LogsSparklineData {
data: {
@@ -21,10 +26,9 @@ export interface LogsSparklineData {
values: number[]
}[]
dates: string[]
- labels: string[]
}
-interface LogsViewerSparklineProps {
+export interface LogsViewerSparklineProps {
sparklineData: LogsSparklineData
sparklineLoading: boolean
onDateRangeChange: (dateRange: DateRange) => void
@@ -34,6 +38,7 @@ interface LogsViewerSparklineProps {
collapsed?: boolean
onToggleCollapse?: () => void
incompleteBarIndices?: number[]
+ visibleRowDateRange?: VisibleLogsTimeRange | null
}
const BREAKDOWN_OPTIONS: { value: LogsSparklineBreakdownBy; label: string }[] = [
@@ -51,97 +56,103 @@ export function LogsSparkline({
collapsed = false,
onToggleCollapse,
incompleteBarIndices,
+ visibleRowDateRange,
}: LogsViewerSparklineProps): JSX.Element | null {
const showServiceBreakdown = useFeatureFlag('LOGS_SPARKLINE_SERVICE_BREAKDOWN')
+ const theme = useChartTheme()
- const { timeUnit, tickFormat } = useMemo(() => {
+ // Quill's automatic date axis has no seconds mode, and buckets target ~50 across the queried
+ // range, so an hour of logs lands under a minute per bucket and needs explicit formats.
+ const tickFormat = useMemo(() => {
if (!sparklineData.dates.length) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm:ss' }
+ return 'HH:mm:ss'
}
- const firstDate = dayjs(sparklineData.dates[0])
- const lastDate = dayjs(sparklineData.dates[sparklineData.dates.length - 1])
- const hoursDiff = lastDate.diff(firstDate, 'hours')
-
- if (hoursDiff <= 1) {
- return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }
- } else if (hoursDiff <= 6) {
- return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }
- } else if (hoursDiff <= 48) {
- return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }
+ const hoursDiff = dayjs(sparklineData.dates[sparklineData.dates.length - 1]).diff(
+ dayjs(sparklineData.dates[0]),
+ 'hours'
+ )
+ if (hoursDiff <= 6) {
+ return 'HH:mm:ss'
}
- return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }
+ return hoursDiff <= 48 ? 'HH:mm' : 'D MMM HH:mm'
}, [sparklineData.dates])
- const withXScale = useCallback(
- (scale: AnyScaleOptions): AnyScaleOptions => {
- return {
- ...scale,
- type: 'timeseries',
- ticks: {
- display: true,
- maxRotation: 0,
- maxTicksLimit: 6,
- font: {
- size: 10,
- lineHeight: 1,
- },
- callback: function (value: string | number) {
- const d = displayTimezone ? dayjs(value).tz(displayTimezone) : dayjs(value)
- return d.format(tickFormat)
- },
- },
- time: {
- unit: timeUnit,
- },
- } as AnyScaleOptions
- },
- [timeUnit, tickFormat, displayTimezone]
+ const sparklineLabels = useMemo(
+ () => sparklineData.dates.map((date) => dayjs(date).toISOString()),
+ [sparklineData.dates]
)
- const renderLabel = useCallback(
- (label: string): string => {
- const d = displayTimezone ? dayjs(label).tz(displayTimezone) : dayjs(label)
- const tz = displayTimezone === 'UTC' ? 'UTC' : (shortTimeZone(displayTimezone, d.toDate()) ?? 'Local')
- return `${d.format('D MMM YYYY HH:mm:ss')} ${tz}`
- },
- [displayTimezone]
+ const series = useMemo<Series[]>(
+ () =>
+ sparklineData.data.map((timeseries) => ({
+ key: timeseries.name,
+ label: timeseries.name,
+ data: timeseries.values,
+ // The logic hands back vars.scss color names ('danger', 'data-color-1'); a canvas
+ // fill needs a real color. `theme` is a dep so a light/dark flip re-resolves them.
+ color: getColorVar(timeseries.color || 'muted'),
+ // Buckets past the ingestion checkpoint are always a trailing run.
+ ...(incompleteBarIndices?.length
+ ? { stroke: { partial: { fromIndex: Math.min(...incompleteBarIndices) } } }
+ : {}),
+ })),
+ [sparklineData.data, incompleteBarIndices, theme]
)
- const sparklineLabels = useMemo(() => {
- return sparklineData.dates.map((date) => dayjs(date).toISOString())
- }, [sparklineData.dates])
-
- const { visibleRowDateRange } = useValues(logsViewerLogic)
-
- const highlightedRange = useMemo(() => {
- if (!visibleRowDateRange || sparklineData.dates.length === 0) {
- return null
- }
- const firstMs = dayjs(sparklineData.dates[0]).valueOf()
- const lastMs = dayjs(sparklineData.dates[sparklineData.dates.length - 1]).valueOf()
- const clamp = (ms: number): number => Math.min(Math.max(ms, firstMs), lastMs)
- const xMin = clamp(dayjs(visibleRowDateRange.date_from).valueOf())
- const xMax = clamp(dayjs(visibleRowDateRange.date_to).valueOf())
- if (xMax <= xMin) {
+ const highlight = useMemo(() => {
+ if (!visibleRowDateRange || !sparklineLabels.length) {
return null
}
- return { xMin, xMax }
- }, [visibleRowDateRange, sparklineData.dates])
+ return highlightedBucketRange(
+ sparklineLabels.map((label) => dayjs(label).valueOf()),
+ dayjs(visibleRowDateRange.date_from).valueOf(),
+ dayjs(visibleRowDateRange.date_to).valueOf()
+ )
+ }, [visibleRowDateRange, sparklineLabels])
+
+ const config = useChartConfig<TimeSeriesBarChartConfig>(
+ () => ({
+ xAxis: { tickFormatter: (value: string) => dayjs(value).tz(displayTimezone).format(tickFormat) },
+ yAxis: { tickFormatter: humanFriendlyNumber },
+ barCornerRadius: 2,
+ // A service breakdown reaches 13 rows, overflowing the tooltip, so it has to be scrollable.
+ tooltip: { pinnable: true },
+ }),
+ [displayTimezone, tickFormat]
+ )
- const onSelectionChange = useCallback(
- (selection: { startIndex: number; endIndex: number }): void => {
- const dates = sparklineData.dates
- const dateFrom = dates[selection.startIndex]
- const dateTo = dates[selection.endIndex + 1]
+ const tooltipHeader = useCallback(
+ (label: string): string => {
+ const date = dayjs(label).tz(displayTimezone)
+ const tz = displayTimezone === 'UTC' ? 'UTC' : (shortTimeZone(displayTimezone, date.toDate()) ?? 'Local')
+ return `${date.format('D MMM YYYY HH:mm:ss')} ${tz}`
+ },
+ [displayTimezone]
+ )
- if (!dateFrom) {
- return
- }
+ // `hideZeroRows` and `sortedByValue` are `DefaultTooltip` props that `config.tooltip` does not
+ // forward, so a sparse bucket would otherwise list every zero-count series.
+ const renderTooltip = useCallback(
+ (ctx: TooltipContext): JSX.Element => (
+ <DefaultTooltip
+ {...ctx}
+ hideZeroRows
+ sortedByValue
+ valueFormatter={(value: number) => humanFriendlyNumber(value)}
+ labelFormatter={tooltipHeader}
+ />
+ ),
+ [tooltipHeader]
+ )
- onDateRangeChange({
- date_from: dateFrom,
- date_to: dateTo,
- })
+ // Wired straight through rather than via `useDateRangeZoom()`, because that hook's flag would
+ // take this drag away from anyone the rollout has not reached, and it already ships to everyone.
+ const onDateRangeZoom = useCallback(
+ ({ startIndex, endIndex }: DateRangeZoomData): void => {
+ const dateRange = selectedDateRange(sparklineData.dates, startIndex, endIndex)
+ if (dateRange) {
+ onDateRangeChange(dateRange)
+ }
},
[sparklineData.dates, onDateRangeChange]
)
@@ -169,21 +180,22 @@ export function LogsSparkline({
)}
</div>
{!collapsed && (
- <div id="logs-sparkline-content" className="relative h-32">
- {sparklineData.data.length > 0 ? (
- <Sparkline
+ // Quill chart roots are `flex-1`, so the sized box has to be a flex column.
+ <div id="logs-sparkline-content" className="relative h-32 flex flex-col">
+ {series.length > 0 ? (
+ <TimeSeriesBarChart
+ series={series}
labels={sparklineLabels}
- data={sparklineData.data}
- className="w-full h-full"
- onSelectionChange={onSelectionChange}
- withXScale={withXScale}
- renderLabel={renderLabel}
- tooltipRowCutoff={100}
- hideZerosInTooltip
- sortTooltipByCount
- highlightedRange={highlightedRange}
- incompleteBars={incompleteBarIndices?.length ? { indices: incompleteBarIndices } : null}
- />
+ theme={theme}
+ config={config}
+ onDateRangeZoom={onDateRangeZoom}
+ tooltip={renderTooltip}
+ dataAttr="logs-viewer-volume-chart"
+ >
+ {highlight ? (
+ <HighlightedRange start={highlight.startIndex} end={highlight.endIndex} />
+ ) : null}
+ </TimeSeriesBarChart>
) : !sparklineLoading ? (
<div className="h-full text-muted flex items-center justify-center">
No results matching filters
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
index 1798e8def404..843064268ddd 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
@@ -195,15 +195,21 @@ describe('logsViewerDataLogic', () => {
describe('sparklineData selector', () => {
it.each([
- ['null', null, { labels: [], dates: [], data: [] }],
- ['an empty array', [], { labels: [], dates: [], data: [] }],
+ ['null', null, { dates: [], data: [] }],
+ ['an empty array', [], { dates: [], data: [] }],
[
'valid data',
[
{ time: '2024-01-01T00:00:00Z', severity: 'info', count: 5 },
{ time: '2024-01-01T00:01:00Z', severity: 'error', count: 3 },
],
- { labels: expect.any(Array), dates: expect.any(Array), data: expect.any(Array) },
+ {
+ dates: ['2024-01-01T00:00:00Z', '2024-01-01T00:01:00Z'],
+ data: [
+ expect.objectContaining({ name: 'error', values: [0, 3] }),
+ expect.objectContaining({ name: 'info', values: [5, 0] }),
+ ],
+ },
],
])('returns correct data when sparkline is %s', async (_, sparklineInput, expected) => {
logic.actions.setSparkline(sparklineInput as any[] | null)
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index 5b9240cf015e..00c110e3d472 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -24,7 +24,6 @@ import api from 'lib/api'
import { dataColorVars } from 'lib/colors'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { dayjs } from 'lib/dayjs'
-import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
import { teamLogic } from 'scenes/teamLogic'
import {
@@ -184,7 +183,6 @@ export interface logsViewerDataLogicValues {
values: number[]
}[]
dates: string[]
- labels: string[]
}
sparklineIncompleteBarIndices: number[]
sparklineLoading: boolean
@@ -460,7 +458,6 @@ export interface logsViewerDataLogicMeta {
values: number[]
}[]
dates: string[]
- labels: string[]
}
sparklineIncompleteBarIndices: (
sparklineData: {
@@ -470,7 +467,6 @@ export interface logsViewerDataLogicMeta {
values: number[]
}[]
dates: string[]
- labels: string[]
},
liveLogsCheckpoint: string | null,
sparklineLoading: boolean
@@ -865,23 +861,17 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
(s) => [s.sparkline, s.sparklineBreakdownBy],
(sparkline: any[] | null, sparklineBreakdownBy: LogsSparklineBreakdownBy) => {
if (!sparkline) {
- return { labels: [], dates: [], data: [] }
+ return { dates: [], data: [] }
}
const breakdownKey = sparklineBreakdownBy
let lastTime = ''
let i = -1
- const labels: string[] = []
const dates: string[] = []
const accumulated = sparkline.reduce(
(accumulator, currentItem) => {
if (currentItem.time !== lastTime) {
- labels.push(
- humanFriendlyDetailedTime(currentItem.time, 'YYYY-MM-DD', 'HH:mm:ss', {
- timestampStyle: 'absolute',
- })
- )
dates.push(currentItem.time)
lastTime = currentItem.time
i++
@@ -902,6 +892,17 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
{} as Record<string, number[]>
)
+ // A key with no rows in the newest buckets stops accumulating early, leaving an array
+ // shorter than `dates`. Quill requires `data.length === labels.length`: a ragged array
+ // desyncs bar positions and clamps `stroke.partial.fromIndex` onto a complete bar,
+ // rendering it as still-ingesting.
+ const padToDatesLength = (values: number[]): number[] => {
+ while (values.length < dates.length) {
+ values.push(0)
+ }
+ return values
+ }
+
// The endpoint folds everything past its top-N into one bucket under a sentinel key.
// Left as-is that sorts to the front (it starts with '$') and draws as a breakdown
// value literally named "$$_posthog_breakdown_other_$$".
@@ -910,7 +911,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, values], index) => ({
name,
- values: values as number[],
+ values: padToDatesLength(values as number[]),
color:
sparklineBreakdownBy === 'service'
? dataColorVars[index % dataColorVars.length]
@@ -926,10 +927,14 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
const otherValues = accumulated[OTHER_BREAKDOWN_VALUE]
if (otherValues) {
// Last and muted, so it reads as an aggregate rather than as another breakdown value.
- data.push({ name: OTHER_BREAKDOWN_LABEL, values: otherValues as number[], color: 'muted' })
+ data.push({
+ name: OTHER_BREAKDOWN_LABEL,
+ values: padToDatesLength(otherValues as number[]),
+ color: 'muted',
+ })
}
- return { data, labels, dates }
+ return { data, dates }
},
],
// Sparkline bar indices that are still being ingested (incomplete), to be hatched. A bucket is