: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
fix(logs): collapse the sparkline tail into an "other" bucket in ClickHouse (#78275)
Frank Hamand353f474efb7a
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 72f6126c8015..4bfd28bf99bf 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -29527,6 +29527,10 @@"$ref": "#/definitions/LogsSparklineBreakdownBy","description": "Field to break down sparkline data by (used only by sparkline endpoint)"},+ "sparklineRankBy": {+ "$ref": "#/definitions/LogsSparklineRankBy",+ "description": "Metric used to rank breakdown values before the tail is collapsed into a single \"other\" bucket, so the returned row count stays bounded (used only by sparkline endpoint). Defaults to ranking by log count."+ },"tags": {"$ref": "#/definitions/QueryLogTags"},@@ -29622,6 +29626,11 @@"enum": ["severity", "service"],"type": "string"},+ "LogsSparklineRankBy": {+ "description": "Metric the sparkline ranks breakdown values by before collapsing the tail into an \"other\" bucket",+ "enum": ["count", "bytes"],+ "type": "string"+ },"MADDetectorConfig": {"additionalProperties": false,"properties": {diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 99654b6a3efb..52b7b0547648 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3586,6 +3586,9 @@ export interface LogMessage {/** Field to break down sparkline data by */export type LogsSparklineBreakdownBy = 'severity' | 'service'+/** Metric the sparkline ranks breakdown values by before collapsing the tail into an "other" bucket */+export type LogsSparklineRankBy = 'count' | 'bytes'+/** @title LogsOrderBy */export type LogsOrderBy = 'latest' | 'earliest'@@ -3618,6 +3621,12 @@ export interface LogsQuery extends DataNode<LogsQueryResponse> {after?: string/** Field to break down sparkline data by (used only by sparkline endpoint) */sparklineBreakdownBy?: LogsSparklineBreakdownBy+ /**+ * Metric used to rank breakdown values before the tail is collapsed into a single "other"+ * bucket, so the returned row count stays bounded (used only by sparkline endpoint).+ * Defaults to ranking by log count.+ */+ sparklineRankBy?: LogsSparklineRankByresourceFingerprint?: string/** Omit the per-log `attributes` and `resource_attributes` maps from results to keep payloads compact */excludeAttributes?: booleandiff --git a/posthog/schema.py b/posthog/schema.pyindex b3328e696573..76ce2b094007 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -153,6 +153,7 @@ from posthog.schema_enums import (LogSeverityLevel as LogSeverityLevel,LogsOrderBy as LogsOrderBy,LogsSparklineBreakdownBy as LogsSparklineBreakdownBy,+ LogsSparklineRankBy as LogsSparklineRankBy,ManualMetricType as ManualMetricType,MarketingAnalyticsAttributionBreakdown as MarketingAnalyticsAttributionBreakdown,MarketingAnalyticsBaseColumns as MarketingAnalyticsBaseColumns,@@ -26384,6 +26385,14 @@ class LogsQuery(BaseModel):default=None,description=("Field to break down sparkline data by (used only by sparkline endpoint)"),)+ sparklineRankBy: LogsSparklineRankBy | None = Field(+ default=None,+ description=(+ "Metric used to rank breakdown values before the tail is collapsed into a"+ ' single "other" bucket, so the returned row count stays bounded (used only'+ " by sparkline endpoint). Defaults to ranking by log count."+ ),+ )tags: QueryLogTags | None = Noneversion: float | None = Field(default=None, description="version of the node, used for schema migrations")diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex a5743b7efb75..1bc8093ee5a3 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2940,6 +2940,11 @@ class LogsSparklineBreakdownBy(StrEnum):SERVICE = "service"+class LogsSparklineRankBy(StrEnum):+ COUNT = "count"+ BYTES = "bytes"++class NeighborDirection(StrEnum):BEFORE = "before"AFTER = "after"diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 69d15f5cffeb..b52d093d2caf 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -334,6 +334,11 @@ class _LogsSparklineBodySerializer(serializers.Serializer):required=False,help_text='Break down sparkline by "severity" (default) or "service".',)+ sparklineRankBy = serializers.ChoiceField(+ choices=["count", "bytes"],+ required=False,+ help_text='Rank breakdown values by "count" (default) or "bytes" before collapsing the tail into "other".',+ )personId = serializers.CharField(required=False,help_text=(@@ -1300,6 +1305,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):resourceFingerprint=query_data.get("resourceFingerprint", None),personId=query_data.get("personId", None),sparklineBreakdownBy=query_data.get("sparklineBreakdownBy"),+ sparklineRankBy=query_data.get("sparklineRankBy"),)runner = SparklineQueryRunner(team=self.team, query=query)diff --git a/products/logs/backend/sparkline_query_runner.py b/products/logs/backend/sparkline_query_runner.pyindex 8d23e748704b..66d60dde509e 100644--- a/products/logs/backend/sparkline_query_runner.py+++ b/products/logs/backend/sparkline_query_runner.py@@ -1,6 +1,6 @@from zoneinfo import ZoneInfo-from posthog.schema import LogsSparklineBreakdownBy+from posthog.schema import LogsSparklineBreakdownBy, LogsSparklineRankByfrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings@@ -8,6 +8,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workload+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_OTHER_STRING_LABELfrom posthog.models.filters.mixins.utils import cached_propertyfrom products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunner@@ -20,6 +21,19 @@ BREAKDOWN_DB_FIELD: dict[LogsSparklineBreakdownBy, str] = {DEFAULT_BREAKDOWN = LogsSparklineBreakdownBy.SEVERITY+# Column each rank metric orders breakdown values by. Ranking by bytes matters when the caller+# charts bytes: the top talkers by volume are not necessarily the top talkers by size.+RANK_BY_FIELD: dict[LogsSparklineRankBy, str] = {+ LogsSparklineRankBy.COUNT: "event_count",+ LogsSparklineRankBy.BYTES: "bytes_uncompressed",+}++DEFAULT_RANK_BY = LogsSparklineRankBy.COUNT++# How many breakdown values keep their own series before the tail is folded into one "other" row.+# Matches what the sparkline UI charts, so collapsing here discards nothing that would be drawn.+SPARKLINE_TOP_BREAKDOWN_VALUES = 10+# The volume preview must return quickly or fail clearly. Its bytes breakdown sums# `_bytes_uncompressed`, which the minute-aggregate projection doesn't cover, so a# high-volume service can fall back to a full table scan. Cap execution well below the@@ -67,11 +81,14 @@ class SparklineQueryRunner(LogsQueryRunner):return LogsQueryResponse(results=results)def to_query(self) -> ast.SelectQuery:+ # The row count is bounded by construction: the rollup in the joined subquery leaves at most+ # SPARKLINE_TOP_BREAKDOWN_VALUES + 1 breakdown values, and BUCKET_TARGET holds the spine near+ # 50 buckets, so ~550 rows is the ceiling for any range. The LIMIT below is a backstop.query = parse_select("""SELECTam.time_bucket AS time,- {breakdown_field},+ ac.breakdown_value AS breakdown_value,ifNull(ac.event_count, 0) AS count,ifNull(ac.bytes_uncompressed, 0) AS bytes_uncompressedFROM (@@ -93,15 +110,40 @@ class SparklineQueryRunner(LogsQueryRunner):) AS amLEFT JOIN (SELECT- toStartOfInterval({time_field}, {one_interval_period}) AS time,- {breakdown_field},- count() AS event_count,- sum(_bytes_uncompressed) AS bytes_uncompressed- FROM logs- WHERE {where} AND time >= {date_from_start_of_interval} AND time <= {date_to}- GROUP BY {breakdown_field}, time+ time,+ if(breakdown_rank <= {top_n}, breakdown_value, {other_label}) AS breakdown_value,+ sum(event_count) AS event_count,+ sum(bytes_uncompressed) AS bytes_uncompressed+ FROM (+ SELECT+ time,+ breakdown_value,+ event_count,+ bytes_uncompressed,+ dense_rank() OVER (ORDER BY breakdown_total DESC, breakdown_value ASC)+ AS breakdown_rank+ FROM (+ SELECT+ time,+ breakdown_value,+ event_count,+ bytes_uncompressed,+ sum({rank_field}) OVER (PARTITION BY breakdown_value) AS breakdown_total+ FROM (+ SELECT+ toStartOfInterval({time_field}, {one_interval_period}) AS time,+ {breakdown_field} AS breakdown_value,+ count() AS event_count,+ sum(_bytes_uncompressed) AS bytes_uncompressed+ FROM logs+ WHERE {where} AND time >= {date_from_start_of_interval} AND time <= {date_to}+ GROUP BY breakdown_value, time+ )+ )+ )+ GROUP BY time, breakdown_value) AS ac ON am.time_bucket = ac.time- ORDER BY time asc, {breakdown_field} asc+ ORDER BY time asc, breakdown_value ascLIMIT 1000""",placeholders={@@ -116,6 +158,9 @@ class SparklineQueryRunner(LogsQueryRunner):"breakdown_field": ast.Field(chain=[BREAKDOWN_DB_FIELD[self.query.sparklineBreakdownBy or DEFAULT_BREAKDOWN]]),+ "rank_field": ast.Field(chain=[RANK_BY_FIELD[self.query.sparklineRankBy or DEFAULT_RANK_BY]]),+ "top_n": ast.Constant(value=SPARKLINE_TOP_BREAKDOWN_VALUES),+ "other_label": ast.Constant(value=BREAKDOWN_OTHER_STRING_LABEL),},)if not isinstance(query, ast.SelectQuery):diff --git a/products/logs/backend/test/test_sparkline_query_runner.py b/products/logs/backend/test/test_sparkline_query_runner.pyindex 547ae2b9c95b..6f1d9ed35eb7 100644--- a/products/logs/backend/test/test_sparkline_query_runner.py+++ b/products/logs/backend/test/test_sparkline_query_runner.py@@ -1,20 +1,43 @@import osimport json+import uuid+from datetime import datetime, timedeltafrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from django.urls import get_resolver+from rest_framework import statusfrom posthog.clickhouse.client import sync_execute+from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_OTHER_STRING_LABEL++from products.logs.backend.sparkline_query_runner import SPARKLINE_TOP_BREAKDOWN_VALUESclass TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):CLASS_DATA_LEVEL_SETUP = True+ # 25 services over a full day. Before the rollup this was (49 buckets × 25 services) = 1225+ # rows, past the 1000-row cap. Ranked by count every service ties, so the tiebreak on name puts+ # service-000..009 in the top 10; service-024 instead carries almost all of the bytes.+ SERVICE_COUNT = 25+ BUCKET_COUNT = 48+ HEAVY_SERVICE = "service-024"+ BYTES_PER_LOG = 1+ HEAVY_BYTES_PER_LOG = 1_000_000+@classmethoddef setUpTestData(cls):super().setUpTestData()+ # Import the URL tree before any test freezes time. Every test here requests under+ # freeze_time, and the first such request is what imports the URL conf — which reaches+ # pydantic.v1, whose ConstrainedDate subclasses `date`. freezegun has swapped that for+ # FakeDate by then, so the import dies with a metaclass conflict and whichever test happens+ # to run first fails.+ assert get_resolver().url_patterns is not None+with open(os.path.join(os.path.dirname(__file__), "test_logs.jsonnd")) as f:sql = ""for line in f:@@ -27,6 +50,17 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):{sql}""")+ # Inserted once for the class, not per test: ClickHouse rows aren't rolled back between+ # test methods, so inserting this from each test would double the volume the later ones see.+ cls._insert_logs_across_services(+ start="2026-03-01T00:00:00",+ bucket_count=cls.BUCKET_COUNT,+ services={+ name: (cls.HEAVY_BYTES_PER_LOG if name == cls.HEAVY_SERVICE else cls.BYTES_PER_LOG)+ for name in (f"service-{i:03d}" for i in range(cls.SERVICE_COUNT))+ },+ )+def _make_sparkline_api_request(self, query_params, expected_status=status.HTTP_200_OK):response = self.client.post(f"/api/projects/{self.team.id}/logs/sparkline", data={"query": query_params})self.assertEqual(response.status_code, expected_status)@@ -55,3 +89,75 @@ class TestSparklineQueryRunner(ClickhouseTestMixin, APIBaseTest):self.assertEqual(len(response), 49)self.assertEqual(sum(r["count"] for r in response), 900)++ def _service_sparkline(self, rank_by: str | None = None) -> list:+ query_params = {+ "dateRange": {"date_from": "2026-03-01T00:00:00.000000Z", "date_to": "2026-03-02T00:00:00.000000Z"},+ "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},+ "sparklineBreakdownBy": "service",+ }+ if rank_by is not None:+ query_params["sparklineRankBy"] = rank_by+ return self._make_sparkline_api_request(query_params)++ @freeze_time("2026-03-02T00:10:00Z")+ def test_service_breakdown_collapses_the_tail_into_one_other_bucket(self):+ response = self._service_sparkline()++ breakdowns = {r["service"] for r in response}+ # Top 10 keep their own series and everything else folds into one row per bucket, so the+ # response is bounded by buckets × 11 however many services exist.+ self.assertEqual(len(breakdowns), SPARKLINE_TOP_BREAKDOWN_VALUES + 1)+ self.assertIn(BREAKDOWN_OTHER_STRING_LABEL, breakdowns)+ self.assertLess(len(response), 1000)+ # Collapsing must not lose volume — the folded services are summed, not dropped.+ self.assertEqual(sum(r["count"] for r in response), self.SERVICE_COUNT * self.BUCKET_COUNT)+ folded_count = self.SERVICE_COUNT - SPARKLINE_TOP_BREAKDOWN_VALUES+ self.assertEqual(+ sum(r["count"] for r in response if r["service"] == BREAKDOWN_OTHER_STRING_LABEL),+ folded_count * self.BUCKET_COUNT,+ )++ @freeze_time("2026-03-02T00:10:00Z")+ def test_rank_by_bytes_keeps_a_different_top_ten_than_rank_by_count(self):+ # Every service logs the same number of times, but one carries a million-fold more bytes per+ # log. A caller charting bytes has to see that service as its own series; ranking by count+ # would bury the single biggest contributor to the storage projection inside "other".+ by_count = {r["service"] for r in self._service_sparkline(rank_by="count")}+ by_bytes = {r["service"] for r in self._service_sparkline(rank_by="bytes")}++ self.assertNotIn(self.HEAVY_SERVICE, by_count)+ self.assertIn(self.HEAVY_SERVICE, by_bytes)++ expected_bytes = self.BUCKET_COUNT * (self.HEAVY_BYTES_PER_LOG + (self.SERVICE_COUNT - 1) * self.BYTES_PER_LOG)+ for rank_by in ("count", "bytes"):+ response = self._service_sparkline(rank_by=rank_by)+ self.assertEqual(sum(r["bytes_uncompressed"] for r in response), expected_bytes, rank_by)++ @classmethod+ def _insert_logs_across_services(cls, start: str, bucket_count: int, services: dict[str, int]) -> None:+ """One log per (service, 30-minute bucket), cloned off the fixture so the schema stays valid.++ `services` maps service name to the uncompressed byte size charged to each of its logs.+ """+ with open(os.path.join(os.path.dirname(__file__), "test_logs.jsonnd")) as f:+ template = json.loads(f.readline())+ start_at = datetime.fromisoformat(start)+ rows = ""+ for service_name, bytes_per_log in services.items():+ for bucket_index in range(bucket_count):+ log_item = dict(template)+ log_item["team_id"] = cls.team.id+ log_item["uuid"] = str(uuid.uuid4())+ log_item["service_name"] = service_name+ log_item["_bytes_uncompressed"] = bytes_per_log+ # Land mid-bucket so bucket rounding can't move a log into a neighbour.+ timestamp = start_at + timedelta(minutes=30 * bucket_index, seconds=61)+ log_item["timestamp"] = timestamp.strftime("%Y-%m-%d %H:%M:%S.%f")+ log_item["observed_timestamp"] = log_item["timestamp"]+ rows += json.dumps(log_item) + "\n"+ sync_execute(f"""+ INSERT INTO logs+ FORMAT JSONEachRow+ {rows}+ """)diff --git a/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsxindex 6fc270296f0d..4c0bb39708f0 100644--- a/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx+++ b/products/logs/frontend/components/LogsFilterPreview/LogsFilterVolumeSparkline.tsx@@ -50,17 +50,19 @@ export function LogsFilterVolumeSparkline({const generatedKey = useId()const logic = logsFilterVolumePreviewLogic({ previewKey: previewKey ?? generatedKey })const { filterPreview, filterPreviewLoading } = useValues(logic)- const { setFilterGroup, refreshFilterPreview } = useActions(logic)+ const { setPreviewRequest, refreshFilterPreview } = useActions(logic)const hasFilters = filterGroup.values.length > 0// Serialized so a re-render handing us a fresh-but-equal object doesn't re-fire the request.// Mounting runs this too, which covers the edit-mode case of opening a form with filters already set.+ // `metric` is a dependency because the backend ranks by it before collapsing the tail, so+ // switching metric needs a fresh request to get the right top-N back.const serializedFilterGroup = useMemo(() => JSON.stringify(filterGroup), [filterGroup])useEffect(() => {- setFilterGroup(filterGroup)+ setPreviewRequest(filterGroup, metric)// eslint-disable-next-line react-hooks/exhaustive-deps- }, [serializedFilterGroup])+ }, [serializedFilterGroup, metric])const seriesData = useMemo(() => buildSparklineSeries(filterPreview, metric), [filterPreview, metric])const renderInfo = useMemo<LogsFilterVolumeSparklineRenderInfo>(diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.tsindex dacdcec8959a..d08c42da0096 100644--- a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.test.ts@@ -1,4 +1,17 @@-import { LogsFilterPreviewPoint, buildSparklineSeries, formatBytes } from './logsFilterVolumePreview'+import fs from 'fs'+import path from 'path'++import { OTHER_BREAKDOWN_LABEL, OTHER_BREAKDOWN_VALUE } from 'products/logs/frontend/sparklineOtherBreakdown'++import {+ LogsFilterPreviewPoint,+ TOP_SERVICES_LIMIT,+ buildSparklineSeries,+ formatBytes,+} from './logsFilterVolumePreview'++const readSource = (relativePath: string): string =>+ fs.readFileSync(path.join(__dirname, '../../../..', relativePath), 'utf-8')const point = (time: string, service: string, count: number, bytes?: number): LogsFilterPreviewPoint => ({time,@@ -10,6 +23,25 @@ const point = (time: string, service: string, count: number, bytes?: number): Loconst T1 = '2026-08-04T11:00:00Z'const T2 = '2026-08-04T11:30:00Z'+describe('constants shared with the backend', () => {+ it('agrees with the backend on how many breakdown values survive the rollup', () => {+ // The header text promises "top N" and the backend decides N, so drift would make the UI lie.+ const runner = readSource('logs/backend/sparkline_query_runner.py')+ const match = runner.match(/^SPARKLINE_TOP_BREAKDOWN_VALUES = (\d+)$/m)+ expect(match).not.toBeNull()+ expect(Number(match![1])).toEqual(TOP_SERVICES_LIMIT)+ })++ it('uses the same collapsed-bucket sentinel the backend emits', () => {+ // A mismatch would leave the sentinel unrecognised and drawn as a service literally named+ // "$$_posthog_breakdown_other_$$".+ const breakdowns = readSource('../posthog/hogql_queries/insights/utils/breakdowns.py')+ const match = breakdowns.match(/^BREAKDOWN_OTHER_STRING_LABEL = "(.+)"$/m)+ expect(match).not.toBeNull()+ expect(match![1]).toEqual(OTHER_BREAKDOWN_VALUE)+ })+})+describe('buildSparklineSeries', () => {it('stacks one series per service in bucket order', () => {const data = buildSparklineSeries([point(T1, 'api', 3), point(T1, 'worker', 1), point(T2, 'api', 5)], 'count')@@ -25,18 +57,34 @@ describe('buildSparklineSeries', () => {expect(data.firstBucketTime).toEqual(T1)})- it('rolls the long tail past the top 10 into one Others series, preserving the total', () => {+ it('keeps every returned series rather than slicing — the backend already folded the tail', () => {+ // Slicing here again would take the backend's collapsed row and re-collapse it, labelling an+ // aggregate of many services as though it were one more service.const points = Array.from({ length: 13 }, (_, i) => point(T1, `svc-${i}`, 13 - i))const data = buildSparklineSeries(points, 'count')- expect(data.series).toHaveLength(11)- expect(data.series[10].name).toEqual('Others (3 services)')- // svc-10..svc-12 rank last, contributing 3 + 2 + 1.- expect(data.series[10].values).toEqual([6])- expect(data.truncatedServiceCount).toEqual(3)+ expect(data.series).toHaveLength(13)+ expect(data.series.map((s) => s.name)).toEqual(Array.from({ length: 13 }, (_, i) => `svc-${i}`))expect(data.series.reduce((sum, s) => sum + s.values[0], 0)).toEqual(data.total)})+ it('labels the collapsed bucket and pins it last even when it outweighs every service', () => {+ const points = [+ point(T1, 'api', 5),+ point(T2, 'api', 5),+ point(T1, OTHER_BREAKDOWN_VALUE, 900),+ point(T2, OTHER_BREAKDOWN_VALUE, 900),+ ]++ const data = buildSparklineSeries(points, 'count')++ expect(data.series.map((s) => s.name)).toEqual(['api', OTHER_BREAKDOWN_LABEL])+ expect(data.series[1]).toEqual(+ expect.objectContaining({ name: OTHER_BREAKDOWN_LABEL, color: 'muted', values: [900, 900] })+ )+ expect(data.total).toEqual(1810)+ })+it('reads bytes_uncompressed for the bytes metric and treats a missing value as zero', () => {const points = [point(T1, 'api', 100, 2048), point(T2, 'api', 100)]diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.tsindex 21dcd0cfcad2..4c4387a8fd99 100644--- a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreview.ts@@ -2,12 +2,17 @@ import { dataColorVars } from 'lib/colors'import { SparklineTimeSeries } from 'lib/components/Sparkline'import { dayjs } from 'lib/dayjs'+import { OTHER_BREAKDOWN_LABEL, OTHER_BREAKDOWN_VALUE } from 'products/logs/frontend/sparklineOtherBreakdown'++/** Must match `SPARKLINE_TOP_BREAKDOWN_VALUES` in `products/logs/backend/sparkline_query_runner.py`. */export const TOP_SERVICES_LIMIT = 10/*** Mirrors the `LIMIT 1000` in `products/logs/backend/sparkline_query_runner.py`. Rows are- * (bucket × service), and the query orders by time ascending — so once the cap is hit it's the- * *newest* buckets that get dropped, and any total derived from the response is an undercount.+ * (bucket × breakdown value), and the query orders by time ascending — so if the cap were ever hit+ * it would be the *newest* buckets that got dropped, making any total an undercount. The backend+ * now folds the tail into one bucket, which bounds the response at roughly 50 × 11 rows, so this+ * should be unreachable; it stays as a backstop in case the top-N there is ever raised.*/export const SPARKLINE_ROW_LIMIT = 1000@@ -24,7 +29,6 @@ export interface LogsFilterPreviewSeriesData {labels: string[]series: SparklineTimeSeries[]total: number- truncatedServiceCount: number/** Width of one bar/bucket in seconds; needed to translate a per-second rate limit into per-bucket units. */bucketSeconds: number/** Tallest stacked total across buckets; used to position the rate-limit reference line. */@@ -66,25 +70,24 @@ export function buildSparklineSeries(total += value}const labels = timeOrder.map((t) => dayjs(t).format('D MMM HH:mm'))- const rankedServices = Array.from(serviceTotals.entries()).sort(([, a], [, b]) => b - a)- const topServices = rankedServices.slice(0, TOP_SERVICES_LIMIT)- const otherServices = rankedServices.slice(TOP_SERVICES_LIMIT)- const truncatedServiceCount = otherServices.length- const series: SparklineTimeSeries[] = topServices.map(([service], index) => ({- name: service,- color: dataColorVars[index % dataColorVars.length],- values: timeOrder.map((t) => byService.get(service)?.get(t) ?? 0),- }))- if (otherServices.length > 0) {- // Roll up the long tail into a single "Others" series so the chart still adds up to total volume,- // and the rate-limit reference line lines up against an honest stacked max.- const othersValues = timeOrder.map((t) =>- otherServices.reduce((sum, [service]) => sum + (byService.get(service)?.get(t) ?? 0), 0)- )+ // Sorted by volume so colours track the biggest talkers, but deliberately not sliced: the+ // backend already folded everything past the top N into one bucket, ranked by this same metric.+ // Slicing again here would re-collapse the collapsed row and label it as a single service.+ const ranked = Array.from(serviceTotals.entries()).sort(([, a], [, b]) => b - a)+ const valuesFor = (service: string): number[] => timeOrder.map((t) => byService.get(service)?.get(t) ?? 0)+ const series: SparklineTimeSeries[] = ranked+ .filter(([service]) => service !== OTHER_BREAKDOWN_VALUE)+ .map(([service], index) => ({+ name: service,+ color: dataColorVars[index % dataColorVars.length],+ values: valuesFor(service),+ }))+ if (serviceTotals.has(OTHER_BREAKDOWN_VALUE)) {+ // Last and muted, so it reads as an aggregate rather than as another service.series.push({- name: `Others (${otherServices.length} services)`,+ name: OTHER_BREAKDOWN_LABEL,color: 'muted',- values: othersValues,+ values: valuesFor(OTHER_BREAKDOWN_VALUE),})}const bucketSeconds = timeOrder.length >= 2 ? dayjs(timeOrder[1]).diff(dayjs(timeOrder[0]), 'second') : 0@@ -93,7 +96,6 @@ export function buildSparklineSeries(labels,series,total,- truncatedServiceCount,bucketSeconds,chartMax,bucketCount: timeOrder.length,diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.tsindex 55f1389198d0..090ea8142ea8 100644--- a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.test.ts@@ -16,15 +16,19 @@ const nonEmptyGroup: UniversalFiltersGroup = {describe('logsFilterVolumePreviewLogic', () => {let logic: ReturnType<typeof logsFilterVolumePreviewLogic.build>let sparklineCalls: number+ let rankBysSeen: (string | undefined)[]let sparklineFails: booleanbeforeEach(() => {sparklineCalls = 0+ rankBysSeen = []sparklineFails = falseuseMocks({post: {- '/api/environments/:team_id/logs/sparkline/': () => {+ '/api/environments/:team_id/logs/sparkline/': async ({ request }) => {sparklineCalls += 1+ const body = (await request.clone().json()) as { query?: { sparklineRankBy?: string } }+ rankBysSeen.push(body?.query?.sparklineRankBy)return sparklineFails ? [500, { detail: 'boom' }] : [200, SPARKLINE_ROWS]},},@@ -40,7 +44,7 @@ describe('logsFilterVolumePreviewLogic', () => {it('does not query for an empty filter group', async () => {await expectLogic(logic, () => {- logic.actions.setFilterGroup({ type: FilterLogicalOperator.And, values: [] })+ logic.actions.setPreviewRequest({ type: FilterLogicalOperator.And, values: [] }, 'count')}).toFinishAllListeners()expect(logic.values.filterPreview).toBeNull()@@ -49,7 +53,7 @@ describe('logsFilterVolumePreviewLogic', () => {it('loads the preview for a non-empty filter group', async () => {await expectLogic(logic, () => {- logic.actions.setFilterGroup(nonEmptyGroup)+ logic.actions.setPreviewRequest(nonEmptyGroup, 'count')}).toDispatchActions(['loadFilterPreviewSuccess']).toFinishAllListeners()@@ -58,9 +62,38 @@ describe('logsFilterVolumePreviewLogic', () => {expect(sparklineCalls).toEqual(1)})+ it('sends the rank metric so the backend collapses around the right top-N', async () => {+ await expectLogic(logic, () => {+ logic.actions.setPreviewRequest(nonEmptyGroup, 'bytes')+ })+ .toDispatchActions(['loadFilterPreviewSuccess'])+ .toFinishAllListeners()++ expect(rankBysSeen).toEqual(['bytes'])+ })++ it('refetches when only the rank metric changes', async () => {+ // The filter is identical, but a bytes-ranked top-10 is a different set of services from a+ // count-ranked one, so the cached count-ranked response can't be reused.+ await expectLogic(logic, () => {+ logic.actions.setPreviewRequest(nonEmptyGroup, 'count')+ })+ .toDispatchActions(['loadFilterPreviewSuccess'])+ .toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setPreviewRequest(nonEmptyGroup, 'bytes')+ })+ .toDispatchActions(['loadFilterPreviewSuccess'])+ .toFinishAllListeners()++ expect(sparklineCalls).toEqual(2)+ expect(rankBysSeen).toEqual(['count', 'bytes'])+ })+it('drops the previous result when a later filter fails to load', async () => {await expectLogic(logic, () => {- logic.actions.setFilterGroup(nonEmptyGroup)+ logic.actions.setPreviewRequest(nonEmptyGroup, 'count')}).toDispatchActions(['loadFilterPreviewSuccess']).toFinishAllListeners()@@ -70,7 +103,7 @@ describe('logsFilterVolumePreviewLogic', () => {// as if it described the newly selected filter.sparklineFails = trueawait expectLogic(logic, () => {- logic.actions.setFilterGroup({ ...nonEmptyGroup, type: FilterLogicalOperator.Or })+ logic.actions.setPreviewRequest({ ...nonEmptyGroup, type: FilterLogicalOperator.Or }, 'count')}).toDispatchActions(['loadFilterPreviewFailure']).toFinishAllListeners()@@ -80,8 +113,8 @@ describe('logsFilterVolumePreviewLogic', () => {it('debounces rapid filter edits into a single request', async () => {await expectLogic(logic, () => {- logic.actions.setFilterGroup(nonEmptyGroup)- logic.actions.setFilterGroup({ ...nonEmptyGroup, type: FilterLogicalOperator.Or })+ logic.actions.setPreviewRequest(nonEmptyGroup, 'count')+ logic.actions.setPreviewRequest({ ...nonEmptyGroup, type: FilterLogicalOperator.Or }, 'count')}).toDispatchActions(['loadFilterPreviewSuccess']).toFinishAllListeners()diff --git a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.tsindex e8c656312c8a..ec822a3dd1c5 100644--- a/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts+++ b/products/logs/frontend/components/LogsFilterPreview/logsFilterVolumePreviewLogic.ts@@ -5,7 +5,7 @@ import api from 'lib/api'import { FilterLogicalOperator, PropertyGroupFilter, UniversalFiltersGroup } from '~/types'-import { LogsFilterPreviewPoint } from './logsFilterVolumePreview'+import { LogsFilterPreviewMetric, LogsFilterPreviewPoint } from './logsFilterVolumePreview'const EMPTY_FILTER_GROUP: UniversalFiltersGroup = {type: FilterLogicalOperator.And,@@ -31,6 +31,7 @@ export interface logsFilterVolumePreviewLogicValues {filterGroup: UniversalFiltersGroupfilterPreview: LogsFilterPreviewPoint[] | nullfilterPreviewLoading: boolean+ rankBy: LogsFilterPreviewMetric}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -53,8 +54,12 @@ export interface logsFilterVolumePreviewLogicActions {refreshFilterPreview: () => {value: true}- setFilterGroup: (filterGroup: UniversalFiltersGroup) => {+ setPreviewRequest: (+ filterGroup: UniversalFiltersGroup,+ rankBy: LogsFilterPreviewMetric+ ) => {filterGroup: UniversalFiltersGroup+ rankBy: LogsFilterPreviewMetric}}@@ -76,7 +81,10 @@ export const logsFilterVolumePreviewLogic = kea<logsFilterVolumePreviewLogicTypekey(({ previewKey }) => previewKey),actions({- setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),+ setPreviewRequest: (filterGroup: UniversalFiltersGroup, rankBy: LogsFilterPreviewMetric) => ({+ filterGroup,+ rankBy,+ }),refreshFilterPreview: true,}),@@ -84,7 +92,16 @@ export const logsFilterVolumePreviewLogic = kea<logsFilterVolumePreviewLogicTypefilterGroup: [EMPTY_FILTER_GROUP as UniversalFiltersGroup,{- setFilterGroup: (_, { filterGroup }) => filterGroup,+ setPreviewRequest: (_, { filterGroup }) => filterGroup,+ },+ ],+ // The backend ranks breakdown values by this metric before folding the tail into one+ // bucket, so it has to travel with the request: ranking by count would bury the biggest+ // byte contributor inside "other" for a caller charting bytes.+ rankBy: [+ 'count' as LogsFilterPreviewMetric,+ {+ setPreviewRequest: (_, { rankBy }) => rankBy,},],// kea-loaders keeps the last successful value when a request fails. Consumers treat any@@ -112,6 +129,7 @@ export const logsFilterVolumePreviewLogic = kea<logsFilterVolumePreviewLogicTypeseverityLevels: [],serviceNames: [],sparklineBreakdownBy: 'service',+ sparklineRankBy: values.rankBy,},})// The backend returns each row keyed by the breakdown value ('service' here),@@ -123,7 +141,7 @@ export const logsFilterVolumePreviewLogic = kea<logsFilterVolumePreviewLogicType})),listeners(({ actions }) => ({- setFilterGroup: () => {+ setPreviewRequest: () => {actions.loadFilterPreview(null)},refreshFilterPreview: () => {diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.tsindex a8235dce8499..058cac02886e 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts@@ -9,6 +9,7 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/timport { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'+import { OTHER_BREAKDOWN_LABEL, OTHER_BREAKDOWN_VALUE } from 'products/logs/frontend/sparklineOtherBreakdown'import { logsViewerDataLogic, shouldSkipFilterGroupChange } from './logsViewerDataLogic'@@ -183,6 +184,20 @@ describe('logsViewerDataLogic', () => {expect(logic.values.sparklineData).toEqual(expected)})++ it('renders the collapsed bucket as a muted trailing series, not as a literal sentinel', async () => {+ // The sentinel starts with '$', so without special-casing it would sort ahead of every+ // real value and be drawn as a breakdown value named "$$_posthog_breakdown_other_$$".+ logic.actions.setSparkline([+ { time: '2024-01-01T00:00:00Z', severity: 'info', count: 5 },+ { time: '2024-01-01T00:00:00Z', severity: OTHER_BREAKDOWN_VALUE, count: 7 },+ ] as any[])+ await expectLogic(logic).toFinishAllListeners()++ const { data } = logic.values.sparklineData+ expect(data.map((series: { name: string }) => series.name)).toEqual(['info', OTHER_BREAKDOWN_LABEL])+ expect(data[1]).toEqual(expect.objectContaining({ color: 'muted', values: [7] }))+ })})describe('totalLogsMatchingFilters selector', () => {diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.tsindex 233e5ce8363f..d8a39b4718b0 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts@@ -40,6 +40,7 @@ import { JsonType, PropertyGroupFilter, UniversalFiltersGroup, UniversalFiltersGimport { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'+import { OTHER_BREAKDOWN_LABEL, OTHER_BREAKDOWN_VALUE } from 'products/logs/frontend/sparklineOtherBreakdown'import type { ProductIntentProperties } from '../../../../../../frontend/src/lib/utils/product-intents'import type { DateRange, LogSeverityLevel } from '../../../../../../frontend/src/queries/schema/schema-general'@@ -896,7 +897,11 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([{} as Record<string, number[]>)+ // 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_$$".const data = Object.entries(accumulated)+ .filter(([name]) => name !== OTHER_BREAKDOWN_VALUE).sort(([a], [b]) => a.localeCompare(b)).map(([name, values], index) => ({name,@@ -913,6 +918,11 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([trace: 'muted-alt',}[name],}))+ 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' })+ }return { data, labels, dates }},diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 676a07c1270c..8772e974e0b4 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1843,6 +1843,17 @@ export const SparklineBreakdownByEnumApi = {Service: 'service',} as const+/**+ * * `count` - count+ * * `bytes` - bytes+ */+export type SparklineRankByEnumApi = (typeof SparklineRankByEnumApi)[keyof typeof SparklineRankByEnumApi]++export const SparklineRankByEnumApi = {+ Count: 'count',+ Bytes: 'bytes',+} as const+export interface _LogsSparklineBodyApi {/** Date range for the sparkline. Defaults to last hour. */dateRange?: _DateRangeApi@@ -1859,6 +1870,11 @@ export interface _LogsSparklineBodyApi {* * `severity` - severity* * `service` - service */sparklineBreakdownBy?: SparklineBreakdownByEnumApi+ /** Rank breakdown values by "count" (default) or "bytes" before collapsing the tail into "other".+ *+ * * `count` - count+ * * `bytes` - bytes */+ sparklineRankBy?: SparklineRankByEnumApi/** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */personId?: string}diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex 434e02759a17..d542e4e7a2be 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -1776,6 +1776,13 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({.describe('Break down sparkline by \"severity\" (default) or \"service\".\n\n\* `severity` - severity\n\* `service` - service'),+ sparklineRankBy: zod+ .enum(['count', 'bytes'])+ .describe('\* `count` - count\n\* `bytes` - bytes')+ .optional()+ .describe(+ 'Rank breakdown values by \"count\" (default) or \"bytes\" before collapsing the tail into \"other\".\n\n\* `count` - count\n\* `bytes` - bytes'+ ),personId: zod.string().optional()diff --git a/products/logs/frontend/sparklineOtherBreakdown.ts b/products/logs/frontend/sparklineOtherBreakdown.tsnew file mode 100644index 000000000000..ad252af3e293--- /dev/null+++ b/products/logs/frontend/sparklineOtherBreakdown.ts@@ -0,0 +1,14 @@+/**+ * Sentinel the sparkline endpoint labels its collapsed tail with — the same value insights+ * breakdowns use. Duplicated rather than imported from `scenes/insights/utils` to keep that+ * module's graph out of the logs bundle, which is the convention that file already follows (it+ * carries its own "sync this with breakdowns.py" note). A test pins it to the Python constant.+ */+export const OTHER_BREAKDOWN_VALUE = '$$_posthog_breakdown_other_$$'++/**+ * Legend label for the collapsed bucket. Insights spells this "Other (i.e. all remaining values)",+ * which is too long for a sparkline legend, and deliberately dimension-neutral because the same+ * sentinel can stand in for services or severities.+ */+export const OTHER_BREAKDOWN_LABEL = 'Other'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b78c103287df..e9bd17cfe964 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36678,6 +36678,14 @@ export namespace Schemas {Service: 'service',} as const;+ export type LogsSparklineRankBy = typeof LogsSparklineRankBy[keyof typeof LogsSparklineRankBy];+++ export const LogsSparklineRankBy = {+ Count: 'count',+ Bytes: 'bytes',+ } as const;+export interface LogsQuery {/** Cursor for fetching the next page of results */after?: string | null;@@ -36703,6 +36711,8 @@ export namespace Schemas {severityLevels: LogSeverityLevel[];/** Field to break down sparkline data by (used only by sparkline endpoint) */sparklineBreakdownBy?: LogsSparklineBreakdownBy | null;+ /** Metric used to rank breakdown values before the tail is collapsed into a single "other" bucket, so the returned row count stays bounded (used only by sparkline endpoint). Defaults to ranking by log count. */+ sparklineRankBy?: LogsSparklineRankBy | null;tags?: QueryLogTags | null;/** version of the node, used for schema migrations */version?: number | null;@@ -71107,6 +71117,18 @@ export namespace Schemas {Service: 'service',} as const;+ /**+ * * `count` - count+ * * `bytes` - bytes+ */+ export type SparklineRankByEnum = typeof SparklineRankByEnum[keyof typeof SparklineRankByEnum];+++ export const SparklineRankByEnum = {+ Count: 'count',+ Bytes: 'bytes',+ } as const;+/*** Raw cached payload as stored in Redis, or null on a miss.* @nullable@@ -76185,6 +76207,11 @@ export namespace Schemas {* * `severity` - severity* * `service` - service */sparklineBreakdownBy?: SparklineBreakdownByEnum;+ /** Rank breakdown values by "count" (default) or "bytes" before collapsing the tail into "other".+ *+ * * `count` - count+ * * `bytes` - bytes */+ sparklineRankBy?: SparklineRankByEnum;/** Scope results to one person (UUID or numeric ID). Expanded server-side to the person's distinct IDs and matched against the team's configured distinct-id log attribute keys. */personId?: string;}diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 239f06326bc7..c3de375a8f1b 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -5132,6 +5132,13 @@ export const LogsSparklineCreateBody = /* @__PURE__ */ zod.object({.describe('Break down sparkline by \"severity\" (default) or \"service\".\n\n\* `severity` - severity\n\* `service` - service'),+ sparklineRankBy: zod+ .enum(['count', 'bytes'])+ .describe('\* `count` - count\n\* `bytes` - bytes')+ .optional()+ .describe(+ 'Rank breakdown values by \"count\" (default) or \"bytes\" before collapsing the tail into \"other\".\n\n\* `count` - count\n\* `bytes` - bytes'+ ),personId: zod.string().optional()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.jsonindex b625190f6ed4..d29bc9bcc911 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-sparkline-query.json@@ -108,6 +108,11 @@"description": "Break down sparkline by \"severity\" (default) or \"service\".\n\n* `severity` - severity\n* `service` - service","enum": ["severity", "service"],"type": "string"+ },+ "sparklineRankBy": {+ "description": "Rank breakdown values by \"count\" (default) or \"bytes\" before collapsing the tail into \"other\".\n\n* `count` - count\n* `bytes` - bytes",+ "enum": ["count", "bytes"],+ "type": "string"}},"type": "object"