: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(logs): per-pattern trend sparklines in the patterns view (#68251)
Jon McCallum09f46d5ecdf4
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex 8d1a28397f49..8c992994cf9f 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -1,6 +1,7 @@import osimport reimport datetime as dt+from bisect import bisect_rightfrom collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import TypeVar@@ -55,6 +56,8 @@ class MinedPattern:last_seen: dt.datetimeexamples: list[str]services: list[str]+ # Raw sample counts per caller-supplied time bucket (empty when no buckets given).+ bucket_counts: list[int]@dataclass@@ -66,6 +69,7 @@ class _Accumulator:error_count: int = 0examples: list[str] = field(default_factory=list)services: list[str] = field(default_factory=list)+ bucket_counts: list[int] = field(default_factory=list)def _prepare_body(body: str, truncate: int) -> str:@@ -86,12 +90,24 @@ def _build_miner(sim_th: float, depth: int, max_clusters: int) -> tuple[LogMaskereturn masker, drain+def _bucket_index(buckets: list[tuple[dt.datetime, dt.datetime]], ts: dt.datetime) -> int | None:+ # Buckets are ordered, non-overlapping, half-open [start, end). bisect on starts finds+ # the only candidate; a timestamp can still fall in a gap between buckets (rows outside+ # the sampled time slices), which is a skip, not an error.+ idx = bisect_right(buckets, ts, key=lambda b: b[0]) - 1+ if idx < 0:+ return None+ start, end = buckets[idx]+ return idx if start <= ts < end else None++def mine_patterns(samples: list[LogSample],*,max_patterns: int | None = None,max_examples: int | None = None,max_services: int | None = None,+ buckets: list[tuple[dt.datetime, dt.datetime]] | None = None,) -> list[MinedPattern]:"""Cluster log bodies into templates via Drain3, aggregated per cluster.@@ -129,6 +145,7 @@ def mine_patterns(template=cluster.get_template(),first_seen=sample.timestamp,last_seen=sample.timestamp,+ bucket_counts=[0] * len(buckets) if buckets else [],)accumulators[cluster_id] = accelse:@@ -146,6 +163,10 @@ def mine_patterns(acc.examples.append(prepared)if sample.service_name not in acc.services and len(acc.services) < max_services:acc.services.append(sample.service_name)+ if buckets:+ bucket_idx = _bucket_index(buckets, sample.timestamp)+ if bucket_idx is not None:+ acc.bucket_counts[bucket_idx] += 1total = len(samples)patterns = [@@ -158,6 +179,7 @@ def mine_patterns(last_seen=acc.last_seen,examples=acc.examples,services=acc.services,+ bucket_counts=acc.bucket_counts,)for acc in accumulators.values()]diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.pyindex c9c225fe92e5..b3b5e42b0cb3 100644--- a/products/logs/backend/patterns_query_runner.py+++ b/products/logs/backend/patterns_query_runner.py@@ -76,6 +76,10 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunndef _slice_count(self) -> int:return _env("LOGS_PATTERNS_SLICE_COUNT", 12, int)+ @cached_property+ def _sparkline_bucket_count(self) -> int:+ return _env("LOGS_PATTERNS_SPARKLINE_BUCKETS", 24, int)+def validate_query_runner_access(self, user: "User") -> bool:# Defensive: this runner is invoked directly via the logs API, never through the generic# /api/projects/:id/query/ endpoint. Mirror LogsQueryRunner and refuse user-initiated@@ -109,7 +113,17 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn)for row in response.results]- patterns = mine_patterns(samples)+ # Sparkline buckets: when the scan is slice-bounded the slices ARE the buckets — they're+ # evenly spaced by construction and rows between them were never eligible, so uniform+ # buckets would render misleading zeros in the gaps. Unsliced windows bucket uniformly.+ buckets = (+ slices+ if slices is not None+ else _uniform_buckets(+ self.query_date_range.date_from(), self.query_date_range.date_to(), self._sparkline_bucket_count+ )+ )+ patterns = mine_patterns(samples, buckets=buckets)# `sampled` mirrors the exact condition `_serialize` uses to extrapolate: it's True# whenever fewer rows were scanned than the window held (hash-mod sampling OR time-slice# bounding), so the flag can never diverge from whether the reported counts are estimates.@@ -121,6 +135,7 @@ class PatternsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn"total_count": total,"sampled": scanned < total,"sample_coverage_pct": round(pool / total * 100, 2) if total else 100.0,+ "sparkline_buckets": [{"start": start.isoformat(), "end": end.isoformat()} for start, end in buckets],})@@ -243,6 +258,12 @@ def _time_slices(return slices+def _uniform_buckets(date_from: dt.datetime, date_to: dt.datetime, count: int) -> list[_TimeSlice]:+ count = max(1, count)+ step = (date_to - date_from) / count+ return [(date_from + step * i, date_from + step * (i + 1)) for i in range(count)]++def _sample_divisor(total: int, sample_limit: int) -> int:# Round up so total / divisor <= sample_limit: the hash-modulo predicate alone bounds the# sample and LIMIT never truncates the subset in (biased) read order.@@ -270,4 +291,5 @@ def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -"last_seen": pattern.last_seen.isoformat(),"examples": pattern.examples,"services": pattern.services,+ "sparkline": [estimate(c) for c in pattern.bucket_counts],}diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex a88cf92d78f0..671bb7a9e112 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -702,6 +702,19 @@ class _LogPatternSerializer(serializers.Serializer):child=serializers.CharField(),help_text="Up to 4 distinct service names this pattern was observed in.",)+ sparkline = serializers.ListField(+ child=serializers.IntegerField(),+ help_text=(+ "Estimated occurrences per time bucket, aligned index-for-index with the response's "+ "`sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows "+ "the volume shape over the window, not exact per-bucket tallies."+ ),+ )+++class _LogsPatternsSparklineBucketSerializer(serializers.Serializer):+ start = serializers.CharField(help_text="Bucket start (ISO 8601, inclusive).")+ end = serializers.CharField(help_text="Bucket end (ISO 8601, exclusive).")class _LogsPatternsResponseSerializer(serializers.Serializer):@@ -731,6 +744,14 @@ class _LogsPatternsResponseSerializer(serializers.Serializer):"query within its execution budget; rows outside the slices could not appear in the sample."),)+ sparkline_buckets = _LogsPatternsSparklineBucketSerializer(+ many=True,+ help_text=(+ "Time buckets that every pattern's `sparkline` aligns to. When the scan was bounded to "+ "time slices, the buckets are the slices themselves (evenly spaced, gaps between them "+ "were never eligible for sampling); otherwise they divide the window uniformly."+ ),+ )class _LogAttributeEntrySerializer(serializers.Serializer):diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.pyindex ad71de33aaba..e6879643ed2d 100644--- a/products/logs/backend/test/test_patterns_query_runner.py+++ b/products/logs/backend/test/test_patterns_query_runner.py@@ -68,6 +68,9 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert by_template["User <*> not found"]["error_count"] == 3assert by_template["User <*> not found"]["estimated_error_count"] == 3assert by_template["User <*> not found"]["services"] == ["auth"]+ # Unsliced windows bucket uniformly; every sampled occurrence lands in some bucket.+ assert len(results["sparkline_buckets"]) == 24+ assert sum(by_template["User <*> not found"]["sparkline"]) == 3@freeze_time(_FROZEN_NOW)def test_sets_sampled_and_caps_scanned_count_above_the_limit(self) -> None:@@ -117,6 +120,10 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):(pattern,) = results["patterns"]assert pattern["count"] == 30assert pattern["estimated_count"] == 60+ # Sliced scans use the slices as sparkline buckets: 6 slices x 5 eligible rows each,+ # extrapolated by the same x2 factor as estimated_count.+ assert len(results["sparkline_buckets"]) == 6+ assert pattern["sparkline"] == [10] * 6@parameterized.expand([diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex fd28370b3f5f..b4a95a470da7 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -3,6 +3,7 @@ import { useValues } from 'kea'import { LemonBanner, LemonTable, LemonTag, Tooltip } from '@posthog/lemon-ui'import type { LemonTableColumns } from '@posthog/lemon-ui'+import { Sparkline } from 'lib/components/Sparkline'import { TZLabel } from 'lib/components/TZLabel'import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'@@ -30,7 +31,9 @@ function renderPatternTemplate(pattern: string): JSX.Element {}export function LogsPatterns({ id }: { id: string }): JSX.Element {- const { patterns, patternsResponse, patternsResponseLoading, patternsError } = useValues(logsPatternsLogic({ id }))+ const { patterns, patternsResponse, patternsResponseLoading, patternsError, sparklineLabels } = useValues(+ logsPatternsLogic({ id })+ )const { sampled, scanned_count, total_count, sample_coverage_pct } = patternsResponse// Estimated counts are rounded (not exact-comma-formatted) and prefixed with "~" so a@@ -57,6 +60,23 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {dataIndex: 'pattern',render: (_, row) => renderPatternTemplate(row.pattern),},+ {+ title: 'Trend',+ key: 'sparkline',+ render: (_, row) =>+ row.sparkline.length ? (+ <div className="w-24 h-6">+ <Sparkline+ data={row.sparkline}+ labels={sparklineLabels}+ className="w-full h-full"+ maximumIndicator={false}+ />+ </div>+ ) : (+ <span className="text-muted">-</span>+ ),+ },{title: 'Count',dataIndex: 'estimated_count',diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsindex 2aafd63fb8c9..d99242633e75 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -31,12 +31,17 @@ const RESPONSE: _LogsPatternsResponseApi = {last_seen: '2026-06-23T12:05:00+00:00',examples: [],services: ['auth'],+ sparkline: [1, 2],},],scanned_count: 3,total_count: 3,sampled: false,sample_coverage_pct: 100,+ sparkline_buckets: [+ { start: '2026-06-23T12:00:00+00:00', end: '2026-06-23T12:30:00+00:00' },+ { start: '2026-06-23T12:30:00+00:00', end: '2026-06-23T13:00:00+00:00' },+ ],}describe('logsPatternsLogic', () => {@@ -96,6 +101,36 @@ describe('logsPatternsLogic', () => {)})+ // The label format flips on a >= 24h window threshold (time-of-day vs date-prefixed) and+ // early-returns on empty buckets — none of the above tests read `sparklineLabels`, so a+ // flipped threshold or a broken dayjs format would otherwise go undetected.+ const labelCases: [string, { start: string; end: string }[], string[]][] = [+ ['empty buckets yield no labels', [], []],+ [+ 'a sub-day window uses time-of-day labels',+ [+ { start: '2026-06-23T12:00:00+00:00', end: '2026-06-23T12:30:00+00:00' },+ { start: '2026-06-23T12:30:00+00:00', end: '2026-06-23T13:00:00+00:00' },+ ],+ ['12:00 – 12:30', '12:30 – 13:00'],+ ],+ [+ 'a multi-day window prefixes the date',+ [+ { start: '2026-06-23T00:00:00+00:00', end: '2026-06-24T00:00:00+00:00' },+ { start: '2026-06-24T00:00:00+00:00', end: '2026-06-25T00:00:00+00:00' },+ ],+ ['Jun 23 00:00 – Jun 24 00:00', 'Jun 24 00:00 – Jun 25 00:00'],+ ],+ ]+ it.each(labelCases)('builds sparkline labels: %s', async (_name, sparkline_buckets, expected) => {+ mockCreate.mockResolvedValue({ ...RESPONSE, sparkline_buckets })+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])+ expect(logic.values.sparklineLabels).toEqual(expected)+ })+it('scopes mining to the embedding viewer pinned filters', async () => {// A scoped embedded viewer (e.g. person/trace logs) pins a filter so Patterns mode// can't mine project-wide logs — assert it reaches the query via `queryFilterGroup`.diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.tsindex 30894885f25c..f54c14544da3 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts@@ -1,6 +1,7 @@import { afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { dayjs } from 'lib/dayjs'import { teamLogic } from 'scenes/teamLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'@@ -23,6 +24,7 @@ const EMPTY_RESPONSE: _LogsPatternsResponseApi = {total_count: 0,sampled: false,sample_coverage_pct: 100,+ sparkline_buckets: [],}// Keyed by the Viewer's `id`: the logic mounts only while the Patterns mode is active (the@@ -96,6 +98,21 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([(s) => [s.patternsResponse],(response: _LogsPatternsResponseApi): _LogPatternApi[] => response.patterns,],+ // Hover labels for the per-pattern sparklines, aligned with each pattern's `sparkline`+ // values. Buckets under a day apart show time-of-day; wider windows include the date.+ sparklineLabels: [+ (s) => [s.patternsResponse],+ (response: _LogsPatternsResponseApi): string[] => {+ const buckets = response.sparkline_buckets+ if (!buckets.length) {+ return []+ }+ const first = dayjs(buckets[0].start)+ const last = dayjs(buckets[buckets.length - 1].end)+ const format = last.diff(first, 'hour') >= 24 ? 'MMM D HH:mm' : 'HH:mm'+ return buckets.map((b) => `${dayjs(b.start).format(format)} – ${dayjs(b.end).format(format)}`)+ },+ ],}),listeners(({ actions }) => {diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 3ee0303e744d..5e45f9397a12 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1091,6 +1091,15 @@ export interface _LogPatternApi {examples: string[]/** Up to 4 distinct service names this pattern was observed in. */services: string[]+ /** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */+ sparkline: number[]+}++export interface _LogsPatternsSparklineBucketApi {+ /** Bucket start (ISO 8601, inclusive). */+ start: string+ /** Bucket end (ISO 8601, exclusive). */+ end: string}export interface _LogsPatternsResponseApi {@@ -1104,6 +1113,8 @@ export interface _LogsPatternsResponseApi {sampled: boolean/** Share of the window's log rows that were eligible for sampling (0–100). Below 100, the scan was bounded to evenly-spaced time slices across the window to keep the query within its execution budget; rows outside the slices could not appear in the sample. */sample_coverage_pct: number+ /** Time buckets that every pattern's `sparkline` aligns to. When the scan was bounded to time slices, the buckets are the slices themselves (evenly spaced, gaps between them were never eligible for sampling); otherwise they divide the window uniformly. */+ sparkline_buckets: _LogsPatternsSparklineBucketApi[]}/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a72e624a7fd1..18428b8617f6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54336,6 +54336,8 @@ export namespace Schemas {examples: string[];/** Up to 4 distinct service names this pattern was observed in. */services: string[];+ /** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */+ sparkline: number[];}/**@@ -54538,6 +54540,13 @@ export namespace Schemas {query: _LogsPatternsBody;}+ export interface _LogsPatternsSparklineBucket {+ /** Bucket start (ISO 8601, inclusive). */+ start: string;+ /** Bucket end (ISO 8601, exclusive). */+ end: string;+ }+export interface _LogsPatternsResponse {/** Mined patterns ordered by `count` descending. */patterns: _LogPattern[];@@ -54549,6 +54558,8 @@ export namespace Schemas {sampled: boolean;/** Share of the window's log rows that were eligible for sampling (0–100). Below 100, the scan was bounded to evenly-spaced time slices across the window to keep the query within its execution budget; rows outside the slices could not appear in the sample. */sample_coverage_pct: number;+ /** Time buckets that every pattern's `sparkline` aligns to. When the scan was bounded to time slices, the buckets are the slices themselves (evenly spaced, gaps between them were never eligible for sampling); otherwise they divide the window uniformly. */+ sparkline_buckets: _LogsPatternsSparklineBucket[];}export interface _LogsQueryBody {