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): hash still-processing sparkline bars past the ingestion checkpoint (#67074)

Frank Hamand62e6e024bfd7
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsx
index 995b4deb9109..ed415e7aaecb 100644
--- a/frontend/src/lib/components/Sparkline.tsx
+++ b/frontend/src/lib/components/Sparkline.tsx
@@ -2,6 +2,7 @@ import annotationPlugin from 'chartjs-plugin-annotation'
import clsx from 'clsx'
import { useMemo, useRef, useState } from 'react'
+import { IconWarning } from '@posthog/icons'
import { Popover } from '@posthog/lemon-ui'
import { Chart, ScaleOptions, TooltipModel } from 'lib/Chart'
@@ -82,6 +83,42 @@ export interface SparklineProps {
* clamped; pass `null`/`undefined` to clear.
*/
highlightedRange?: { startIndex: number; endIndex: number } | null
+ /**
+ * Bar indices that are still being ingested (incomplete). Those bars render with a faded
+ * diagonal-hatch fill, and hovering one adds `tooltip` to the hover tooltip. Used to flag the
+ * most recent bucket(s) when ingestion hasn't caught up. Pass `null`/`undefined` or an empty
+ * `indices` array to clear.
+ */
+ incompleteBars?: { indices: number[]; tooltip?: string } | null
+}
+
+/**
+ * Build a faded diagonal-hatch CanvasPattern for an incomplete bar: a translucent fill of the series
+ * colour overlaid with hatch lines, so the bar reads as "still loading" while keeping its colour.
+ */
+function createHashedPattern(color: string): CanvasPattern | string {
+ const size = 6
+ const canvas = document.createElement('canvas')
+ canvas.width = size
+ canvas.height = size
+ const ctx = canvas.getContext('2d')
+ if (!ctx) {
+ return color
+ }
+ ctx.fillStyle = hexToRGBA(color, 0.25)
+ ctx.fillRect(0, 0, size, size)
+ ctx.strokeStyle = hexToRGBA(color, 0.6)
+ ctx.lineWidth = 1
+ // Three offset diagonals so the hatch tiles seamlessly across the bar.
+ ctx.beginPath()
+ ctx.moveTo(0, size)
+ ctx.lineTo(size, 0)
+ ctx.moveTo(-1, 1)
+ ctx.lineTo(1, -1)
+ ctx.moveTo(size - 1, size + 1)
+ ctx.lineTo(size + 1, size - 1)
+ ctx.stroke()
+ return ctx.createPattern(canvas, 'repeat') ?? color
}
export function Sparkline({
@@ -105,6 +142,7 @@ export function Sparkline({
referenceLines,
renderTooltipValue,
highlightedRange,
+ incompleteBars,
}: SparklineProps): JSX.Element {
const tooltipRef = useRef<HTMLDivElement | null>(null)
@@ -112,6 +150,8 @@ export function Sparkline({
const dragStartRef = useRef<{ index: number; x: number } | null>(null)
const [isDragging, setIsDragging] = useState(false)
+ const incompleteBarSet = useMemo(() => new Set(incompleteBars?.indices ?? []), [incompleteBars])
+
const adjustedData: SparklineTimeSeries[] = useMemo(() => {
const arrayData = Array.isArray(data)
? data.length > 0 && typeof data[0] === 'object'
@@ -220,13 +260,22 @@ export function Sparkline({
datasets: adjustedData.map((timeseries) => {
const seriesColor = getColorVar(timeseries.color || 'muted')
const hoverColor = getColorVar(timeseries.hoverColor || timeseries.color || 'muted')
+ // Incomplete (still-ingesting) bars get a faded hatch of the series colour so
+ // they read as "not final" without losing which series they belong to.
+ const hatched = incompleteBarSet.size > 0 ? createHashedPattern(seriesColor) : null
+ const fillFor = (
+ base: string
+ ): typeof base | CanvasPattern | ((ctx: { dataIndex: number }) => string | CanvasPattern) =>
+ hatched
+ ? (ctx: { dataIndex: number }) => (incompleteBarSet.has(ctx.dataIndex) ? hatched : base)
+ : base
return {
label: timeseries.name,
data: timeseries.values,
minBarLength: 0,
categoryPercentage: 0.9, // Slightly tighter bar spacing than the default 0.8
- backgroundColor: seriesColor,
- hoverBackgroundColor: hoverColor,
+ backgroundColor: fillFor(seriesColor),
+ hoverBackgroundColor: fillFor(hoverColor),
borderColor: seriesColor,
borderWidth: type === 'line' ? 2 : 0,
pointRadius: 0,
@@ -335,11 +384,13 @@ export function Sparkline({
type,
referenceLines,
highlightedRange,
+ incompleteBars,
],
})
const dataPointCount = adjustedData[0]?.values?.length || 0
const finalClassName = clsx(
+ 'relative',
dataPointCount > 16 ? 'w-64' : dataPointCount > 8 ? 'w-48' : dataPointCount > 4 ? 'w-32' : 'w-24',
className
)
@@ -435,33 +486,41 @@ export function Sparkline({
<Popover
visible={tooltipVisible}
overlay={
- <InsightTooltip
- embedded
- hideInspectActorsSection
- showHeader={!!labels}
- altTitle={
- toolTipDataPoints.length > 0
- ? renderLabel
- ? renderLabel(toolTipDataPoints[0].label)
- : toolTipDataPoints[0].label
- : ''
- }
- seriesData={toolTipDataPoints
- .map((dp, i) => ({
- id: i,
- dataIndex: 0,
- datasetIndex: 0,
- order: i,
- label: dp.dataset.label,
- color: dp.dataset.borderColor as string,
- count: (dp.dataset.data?.[dp.dataIndex] as number) || 0,
- }))
- .filter((item) => !hideZerosInTooltip || item.count > 0)
- .sort((a, b) => (sortTooltipByCount ? b.count - a.count : a.order - b.order))}
- renderSeries={(value) => value}
- renderCount={(count) => (renderTooltipValue ?? humanFriendlyNumber)(count)}
- rowCutoff={tooltipRowCutoff}
- />
+ <>
+ {incompleteBarSet.has(toolTipDataPoints[0]?.dataIndex) && (
+ <div className="flex items-center gap-1 px-2 pt-1 text-xs text-warning">
+ <IconWarning className="shrink-0" />
+ {incompleteBars?.tooltip ?? 'Some logs are still processing'}
+ </div>
+ )}
+ <InsightTooltip
+ embedded
+ hideInspectActorsSection
+ showHeader={!!labels}
+ altTitle={
+ toolTipDataPoints.length > 0
+ ? renderLabel
+ ? renderLabel(toolTipDataPoints[0].label)
+ : toolTipDataPoints[0].label
+ : ''
+ }
+ seriesData={toolTipDataPoints
+ .map((dp, i) => ({
+ id: i,
+ dataIndex: 0,
+ datasetIndex: 0,
+ order: i,
+ label: dp.dataset.label,
+ color: dp.dataset.borderColor as string,
+ count: (dp.dataset.data?.[dp.dataIndex] as number) || 0,
+ }))
+ .filter((item) => !hideZerosInTooltip || item.count > 0)
+ .sort((a, b) => (sortTooltipByCount ? b.count - a.count : a.order - b.order))}
+ renderSeries={(value) => value}
+ renderCount={(count) => (renderTooltipValue ?? humanFriendlyNumber)(count)}
+ rowCutoff={tooltipRowCutoff}
+ />
+ </>
}
placement="bottom-start"
padded={false}
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index e3ae4708bec1..369a308793a7 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -570,7 +570,10 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
"resource_fingerprint": str(result[11]),
"instrumentation_scope": result[12],
"event_name": result[13],
- "live_logs_checkpoint": result[14],
+ # ClickHouse returns naive datetimes; tag as UTC like timestamp/observed_timestamp
+ # so the schema's AwareDatetime serializes with an offset rather than as a naive
+ # string the frontend would misparse in non-UTC timezones.
+ "live_logs_checkpoint": result[14].replace(tzinfo=ZoneInfo("UTC")) if result[14] else None,
}
)
diff --git a/products/logs/backend/sparkline_query_runner.py b/products/logs/backend/sparkline_query_runner.py
index d285d085f4ba..8d23e748704b 100644
--- a/products/logs/backend/sparkline_query_runner.py
+++ b/products/logs/backend/sparkline_query_runner.py
@@ -1,3 +1,5 @@
+from zoneinfo import ZoneInfo
+
from posthog.schema import LogsSparklineBreakdownBy
from posthog.hogql import ast
@@ -53,7 +55,9 @@ class SparklineQueryRunner(LogsQueryRunner):
breakdown_value = result[1] if result[1] not in (None, "") else "(no value)"
results.append(
{
- "time": result[0],
+ # Tag the bucket time as UTC so it serializes with an offset, matching the log
+ # row timestamp and the live_logs_checkpoint the frontend compares it against.
+ "time": result[0].replace(tzinfo=ZoneInfo("UTC")) if result[0] else result[0],
result_key: breakdown_value,
"count": result[2],
"bytes_uncompressed": result[3],
diff --git a/products/logs/backend/test/test_sparkline_api.py b/products/logs/backend/test/test_sparkline_api.py
index ae4819fb5344..43c6b4c1db30 100644
--- a/products/logs/backend/test/test_sparkline_api.py
+++ b/products/logs/backend/test/test_sparkline_api.py
@@ -1,5 +1,6 @@
import os
import json
+from datetime import datetime
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -47,3 +48,7 @@ class TestSparklineApi(ClickhouseTestMixin, APIBaseTest):
def test_sparkline(self, _name, query_params, expected_count):
buckets = self._sparkline(query_params)
self.assertEqual(sum(bucket["count"] for bucket in buckets), expected_count)
+ # Bucket times must serialize timezone-aware so the frontend doesn't misparse them as
+ # local time when comparing against the (UTC) live_logs_checkpoint.
+ for bucket in buckets:
+ self.assertIsNotNone(datetime.fromisoformat(bucket["time"]).tzinfo)
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
index b1f47a59105c..2cd6cd94f8f2 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx
@@ -109,8 +109,15 @@ function LogsViewerContent({
const { orderBy, sparklineBreakdownBy, sparklineCollapsed, facetRailCollapsed, viewMode } =
useValues(logsViewerConfigLogic)
const { setOrderBy, setSparklineBreakdownBy, toggleSparklineCollapsed } = useActions(logsViewerConfigLogic)
- const { logsLoading, parsedLogs, sparklineData, sparklineLoading, hasMoreLogsToLoad, totalLogsMatchingFilters } =
- useValues(logsViewerDataLogic)
+ const {
+ logsLoading,
+ parsedLogs,
+ sparklineData,
+ sparklineLoading,
+ sparklineIncompleteBarIndices,
+ hasMoreLogsToLoad,
+ totalLogsMatchingFilters,
+ } = useValues(logsViewerDataLogic)
const { runQuery, fetchNextLogsPage } = useActions(logsViewerDataLogic)
const { setDateRange, zoomDateRange } = useActions(logsViewerFiltersLogic)
const showFacetRail = useFeatureFlag('LOGS_FACET_RAIL')
@@ -293,6 +300,7 @@ function LogsViewerContent({
onBreakdownByChange={setSparklineBreakdownBy}
collapsed={sparklineCollapsed}
onToggleCollapse={toggleSparklineCollapsed}
+ incompleteBarIndices={sparklineIncompleteBarIndices}
/>
<SceneDivider />
</>
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
index d2653a972d7a..bdd1ff7ff56c 100644
--- a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx
@@ -33,6 +33,7 @@ interface LogsViewerSparklineProps {
onBreakdownByChange: (breakdownBy: LogsSparklineBreakdownBy) => void
collapsed?: boolean
onToggleCollapse?: () => void
+ incompleteBarIndices?: number[]
}
const BREAKDOWN_OPTIONS: { value: LogsSparklineBreakdownBy; label: string }[] = [
@@ -49,6 +50,7 @@ export function LogsSparkline({
onBreakdownByChange,
collapsed = false,
onToggleCollapse,
+ incompleteBarIndices,
}: LogsViewerSparklineProps): JSX.Element | null {
const showServiceBreakdown = useFeatureFlag('LOGS_SPARKLINE_SERVICE_BREAKDOWN')
@@ -197,6 +199,7 @@ export function LogsSparkline({
hideZerosInTooltip
sortTooltipByCount
highlightedRange={highlightedRange}
+ incompleteBars={incompleteBarIndices?.length ? { indices: incompleteBarIndices } : null}
/>
) : !sparklineLoading ? (
<div className="h-full text-muted flex items-center justify-center">
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
index fa799691a051..89d241861d15 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
@@ -145,6 +145,58 @@ describe('logsViewerDataLogic', () => {
})
})
+ describe('sparklineIncompleteBarIndices selector', () => {
+ // 60s buckets ending at 00:02:00; last bucket start = 00:02:00.
+ const buckets = [
+ { time: '2024-01-01T00:00:00Z', severity: 'info', count: 5 },
+ { time: '2024-01-01T00:01:00Z', severity: 'info', count: 3 },
+ { time: '2024-01-01T00:02:00Z', severity: 'info', count: 2 },
+ ]
+ // Same buckets but the trailing three are empty.
+ const emptyTailBuckets = [
+ { time: '2024-01-01T00:00:00Z', severity: 'info', count: 5 },
+ { time: '2024-01-01T00:01:00Z', severity: 'info', count: 0 },
+ { time: '2024-01-01T00:02:00Z', severity: 'info', count: 0 },
+ { time: '2024-01-01T00:03:00Z', severity: 'info', count: 0 },
+ ]
+
+ it.each([
+ ['checkpoint is null', buckets, null, []],
+ ['there are fewer than two buckets', buckets.slice(0, 1), '2024-01-01T00:00:30Z', []],
+ ['the checkpoint has caught up to the latest bar', buckets, '2024-01-01T00:01:50Z', []],
+ ['the checkpoint lags the latest bucket start by a quarter bar', buckets, '2024-01-01T00:01:30Z', [1, 2]],
+ ['more than two empty buckets lag — only the latest bar', emptyTailBuckets, '2024-01-01T00:01:00Z', [3]],
+ [
+ 'more than two buckets lag but one has data — all of them',
+ [
+ { time: '2024-01-01T00:00:00Z', severity: 'info', count: 5 },
+ { time: '2024-01-01T00:01:00Z', severity: 'info', count: 0 },
+ { time: '2024-01-01T00:02:00Z', severity: 'info', count: 1 },
+ { time: '2024-01-01T00:03:00Z', severity: 'info', count: 0 },
+ ],
+ '2024-01-01T00:01:00Z',
+ [1, 2, 3],
+ ],
+ ])('returns the right indices when %s', async (_, sparklineInput, checkpoint, expected) => {
+ logic.actions.setSparkline(sparklineInput as any[])
+ logic.actions.setLiveLogsCheckpoint(checkpoint)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.sparklineIncompleteBarIndices).toEqual(expected)
+ })
+
+ it('clears the indices when a new query starts, until a fresh checkpoint lands', async () => {
+ logic.actions.setSparkline(buckets as any[])
+ logic.actions.setLiveLogsCheckpoint('2024-01-01T00:01:30Z')
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.sparklineIncompleteBarIndices).toEqual([1, 2])
+
+ logic.actions.clearLogs()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.sparklineIncompleteBarIndices).toEqual([])
+ })
+ })
+
describe('query failure event capture', () => {
beforeEach(() => {
jest.clearAllMocks()
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index a29c16bef59a..470ffcd20e0e 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -180,6 +180,9 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
{ persist: false },
{
setLiveLogsCheckpoint: (_, { liveLogsCheckpoint }) => liveLogsCheckpoint,
+ // Drop the stale checkpoint when a new query starts so the still-loading region
+ // can't flash against the previous query's data before the fresh one lands.
+ clearLogs: () => null,
},
],
liveTailExpired: [
@@ -296,6 +299,12 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
actions.setHasMoreLogsToLoad(!!response.hasMore)
actions.setNextCursor(response.nextCursor ?? null)
actions.setMaxExportableLogs(response.maxExportableLogs)
+ // The checkpoint (fixed per query, identical on every row) marks the latest
+ // timestamp ingestion is known to have fully caught up to — used to flag the
+ // still-loading tail of the sparkline.
+ if (response.results.length > 0) {
+ actions.setLiveLogsCheckpoint(response.results[0].live_logs_checkpoint ?? null)
+ }
return response.results
},
fetchNextLogsPage: async ({ limit }, breakpoint) => {
@@ -477,6 +486,51 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
return { data, labels, dates }
},
],
+ // Sparkline bar indices that are still being ingested (incomplete), to be hatched. A bucket is
+ // incomplete when its end is past the ingestion checkpoint. The latest bucket is the in-progress
+ // bar so the checkpoint always trails "now" a little; we only flag anything once the checkpoint
+ // lags the latest bucket's *start* by at least a quarter of a bar, otherwise ingestion is
+ // effectively caught up. When the lag spans more than two buckets but they're all empty, we flag
+ // only the latest bar rather than hatching a wide empty stretch. Bucket times and the checkpoint
+ // are both UTC ISO strings, so the relative comparison is timezone-safe.
+ //
+ // Empty while the sparkline query is in flight or before a fresh checkpoint lands (it's cleared
+ // on each new query); otherwise the hatch flickers mid-load as new data and a new checkpoint race.
+ sparklineIncompleteBarIndices: [
+ (s) => [s.sparklineData, s.liveLogsCheckpoint, s.sparklineLoading],
+ (
+ sparklineData: { dates: string[]; data: { values: number[] }[] },
+ liveLogsCheckpoint: string | null,
+ sparklineLoading: boolean
+ ): number[] => {
+ const { dates, data } = sparklineData
+ if (sparklineLoading || !liveLogsCheckpoint || dates.length < 2) {
+ return []
+ }
+ const firstBucketMs = dayjs(dates[0]).valueOf()
+ const lastBucketMs = dayjs(dates[dates.length - 1]).valueOf()
+ const intervalMs = dayjs(dates[1]).valueOf() - firstBucketMs
+ if (intervalMs <= 0) {
+ return []
+ }
+ const checkpointMs = dayjs(liveLogsCheckpoint).valueOf()
+ if (!Number.isFinite(checkpointMs) || lastBucketMs - checkpointMs < intervalMs * 0.25) {
+ return []
+ }
+ const incomplete = dates.reduce<number[]>((indices, date, index) => {
+ if (dayjs(date).valueOf() + intervalMs > checkpointMs) {
+ indices.push(index)
+ }
+ return indices
+ }, [])
+ const bucketTotal = (index: number): number =>
+ data.reduce((sum, series) => sum + (series.values[index] ?? 0), 0)
+ if (incomplete.length > 2 && incomplete.every((index) => bucketTotal(index) === 0)) {
+ return [dates.length - 1]
+ }
+ return incomplete
+ },
+ ],
totalLogsMatchingFilters: [
(s) => [s.sparkline],
(sparkline): number => sparkline?.reduce((sum: number, item: any) => sum + item.count, 0) ?? 0,