: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): paginate services view with search and 1000-row cap (#81761)
Jon McCallumab4350d6f8a7
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ce857bcb4d53..767b96cf6c84 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -784,10 +784,6 @@ export class ApiRequest {return this.logs(projectId).addPathComponent('sparkline')}- public logsServices(projectId?: ProjectType['id']): ApiRequest {- return this.logs(projectId).addPathComponent('services')- }-public logsHasLogs(projectId?: ProjectType['id']): ApiRequest {return this.logs(projectId).addPathComponent('has_logs')}@@ -2851,29 +2847,6 @@ const api = {async sparkline({ query, signal }: { query: Omit<LogsQuery, 'kind'>; signal?: AbortSignal }): Promise<any[]> {return new ApiRequest().logsSparkline().create({ signal, data: { query } })},- async services({ query, signal }: { query: Omit<LogsQuery, 'kind'>; signal?: AbortSignal }): Promise<{- services: {- service_name: string- log_count: number- error_count: number- error_rate: number- volume_share_pct?: number- severity_breakdown?: {- debug: number- info: number- warn: number- error: number- }- active_rules?: { rule_id: string; rule_name: string; summary_string: string }[]- }[]- sparkline: { time: string; service_name: string; count: number }[]- summary?: {- top_services_count: number- top_services_volume_share_pct: number- }- }> {- return new ApiRequest().logsServices().create({ signal, data: { query } })- },async hasLogs(): Promise<boolean> {return new ApiRequest().logsHasLogs()diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 35bd5c5358a1..ffed8e85d7a8 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -546,6 +546,14 @@ class _LogsServicesBodySerializer(serializers.Serializer):help_text="Restrict the aggregation to these service names.",)searchTerm = serializers.CharField(required=False, help_text="Full-text search term to filter log bodies.")+ serviceNameSearch = serializers.CharField(+ required=False,+ max_length=200,+ help_text=(+ "Case-insensitive substring match on service name, applied before aggregation. "+ "Use to reach services beyond the response cap."+ ),+ )filterGroup = serializers.ListField(child=_LogPropertyFilterSerializer(),required=False,@@ -700,11 +708,21 @@ class _LogsServicesSummarySerializer(serializers.Serializer):class _LogsServicesResponseSerializer(serializers.Serializer):services = _LogsServiceAggregateSerializer(many=True,- help_text="Per-service aggregates, ordered by log_count descending. Capped at 25 services.",+ help_text="Per-service aggregates, ordered by log_count descending. Capped at 1000 services.",)sparkline = _LogsServicesSparklineBucketSerializer(many=True,- help_text="Time-bucketed counts broken down by service, for plotting volume over time.",+ help_text=(+ "Time-bucketed counts broken down by service, for plotting volume over time. "+ "Covers only the top 25 services in this response; re-request with `serviceNames` "+ "to get sparklines for specific services."+ ),+ )+ total_services = serializers.IntegerField(+ help_text=(+ "True distinct service count for the window and filters, unaffected by the 1000-service "+ "cap on `services`. Greater than the length of `services` when the response is truncated."+ ),)summary = _LogsServicesSummarySerializer(required=False,@@ -1489,7 +1507,11 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),)- runner = ServicesQueryRunner(team=self.team, query=query)+ runner = ServicesQueryRunner(+ team=self.team,+ query=query,+ service_name_search=query_data.get("serviceNameSearch") or None,+ )response = runner.run(ExecutionMode.CALCULATE_BLOCKING_ALWAYS,analytics_props=get_request_analytics_properties(request),diff --git a/products/logs/backend/services_query_runner.py b/products/logs/backend/services_query_runner.pyindex 270a4ac8dac0..955c4363839f 100644--- a/products/logs/backend/services_query_runner.py+++ b/products/logs/backend/services_query_runner.py@@ -1,3 +1,4 @@+from functools import cached_propertyfrom typing import Anyimport re2@@ -5,13 +6,13 @@ import re2from posthog.schema import CachedLogsQueryResponse, LogsQueryfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.hogql_queries.query_runner import AnalyticsQueryRunner-from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixin+from products.logs.backend.logs_query_runner import LogsQueryResponse, LogsQueryRunnerMixin, ilike_patternfrom products.logs.backend.models import LogsExclusionRule# Three-valued logic for evaluating a rule's filter_group against a partial record@@ -163,12 +164,30 @@ def _sampling_rule_summary(rule: LogsExclusionRule) -> str:return str(rule.rule_type)+# Response caps. SERVICES_LIMIT bounds the per-request payload against+# user-controlled service_name cardinality (a misconfigured SDK can emit a+# unique name per pod or instance). Names beyond the cap stay reachable via+# serviceNameSearch, which filters before aggregation.+SERVICES_LIMIT = 1000+# Sparklines are fetched per displayed page: the bucket grid is+# time × service and the sparkline query's row LIMIT would silently drop the+# most recent buckets if scoped to all SERVICES_LIMIT names at once.+SPARKLINE_SERVICES_LIMIT = 25++class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):"""Returns per-service aggregates (volume, error count, error rate) and sparkline data."""query: LogsQuerycached_response: CachedLogsQueryResponse+ def __init__(self, *args: Any, service_name_search: str | None = None, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ # Not part of the query object, so it never reaches the cache key. Safe+ # only while the services endpoint runs CALCULATE_BLOCKING_ALWAYS; a move+ # to any cached execution mode requires this on LogsQuery instead.+ self.service_name_search = service_name_search.strip() if service_name_search else None+def _calculate(self) -> LogsQueryResponse:aggregates_response = execute_hogql_query(query_type="LogsQuery",@@ -182,12 +201,13 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnsettings=self.settings,)- # The table only renders sparklines for the services in the aggregates- # result (top 25 by volume), so scope the sparkline scan to those names- # rather than every service in the window: service_name is in the table's- # sort key, so the IN filter prunes the scan, and it removes the chance of- # the row LIMIT truncating a displayed service's trend.- top_service_names = [row[0] for row in aggregates_response.results]+ # Sparklines cover only the top services by volume; callers wanting+ # trends for other rows re-request with `serviceNames` scoped to the+ # rows they display. service_name is in the table's sort key, so the IN+ # filter prunes the scan, and the bounded name list keeps the grid of+ # time × service rows under the sparkline query's row LIMIT (which+ # truncates the most recent buckets first).+ top_service_names = [row[0] for row in aggregates_response.results[:SPARKLINE_SERVICES_LIMIT]]sparkline_rows: list[Any] = []if top_service_names:sparkline_response = execute_hogql_query(@@ -203,6 +223,26 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn)sparkline_rows = sparkline_response.results+ # True distinct-service count, unaffected by SERVICES_LIMIT — the UI+ # uses it to disclose truncation. An aggregates result under the cap is+ # already the complete distinct set, so only run the extra count when+ # the cap was actually hit.+ if len(aggregates_response.results) < SERVICES_LIMIT:+ total_services = len(aggregates_response.results)+ else:+ total_response = execute_hogql_query(+ query_type="LogsQuery",+ query=self._total_services_query(),+ modifiers=self.modifiers,+ team=self.team,+ workload=Workload.LOGS,+ timings=self.timings,+ limit_context=self.limit_context,+ filters=self.query_date_range.to_hogql_filters(),+ settings=self.settings,+ )+ total_services = int(total_response.results[0][0]) if total_response.results else 0+enabled_rules = list(LogsExclusionRule.objects.filter(team_id=self.team.pk, enabled=True).order_by("priority", "created_at"))@@ -273,6 +313,7 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnresults={"services": services,"sparkline": sparkline,+ "total_services": total_services,"summary": {"top_services_count": top_n,"top_services_volume_share_pct": top_share,@@ -283,6 +324,25 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunndef to_query(self) -> ast.SelectQuery:return self._aggregates_query()+ @cached_property+ def _where_with_search(self) -> ast.Expr:+ base = self.where()+ if not self.service_name_search:+ return base+ search = parse_expr(+ "service_name ILIKE {pattern}",+ placeholders={"pattern": ast.Constant(value=ilike_pattern(self.service_name_search))},+ )+ return ast.And(exprs=[base, search])++ def _total_services_query(self) -> ast.SelectQuery:+ query = parse_select(+ "SELECT uniq(service_name) FROM logs WHERE {where}",+ placeholders={"where": self._where_with_search},+ )+ assert isinstance(query, ast.SelectQuery)+ return query+def _aggregates_query(self) -> ast.SelectQuery:query = parse_select("""@@ -304,10 +364,11 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn)GROUP BY service_nameORDER BY log_count DESC- LIMIT 25+ LIMIT {limit}""",placeholders={- "where": self.where(),+ "where": self._where_with_search,+ "limit": ast.Constant(value=SERVICES_LIMIT),},)assert isinstance(query, ast.SelectQuery)@@ -331,7 +392,7 @@ class ServicesQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunn"time_field": ast.Call(name="toStartOfMinute", args=[ast.Field(chain=["timestamp"])])if self.query_date_range.interval_name != "second"else ast.Field(chain=["timestamp"]),- "where": self.where(),+ "where": self._where_with_search,"service_names": ast.Tuple(exprs=[ast.Constant(value=str(sn)) for sn in service_names]),},)diff --git a/products/logs/backend/test/test_services_query_runner.py b/products/logs/backend/test/test_services_query_runner.pyindex 1f979515dc33..0d2ae850b726 100644--- a/products/logs/backend/test/test_services_query_runner.py+++ b/products/logs/backend/test/test_services_query_runner.py@@ -5,12 +5,14 @@ from typing import Anyimport pytestfrom freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom parameterized import parameterizedfrom rest_framework import statusfrom posthog.clickhouse.client import sync_execute+from products.logs.backend import services_query_runnerfrom products.logs.backend.services_query_runner import rule_could_apply_to_service@@ -178,17 +180,18 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):{sql}""")- def _services(self, date_from: str, date_to: str) -> dict:+ def _services(self, date_from: str, date_to: str, service_name_search: str | None = None) -> dict:+ query: dict[str, Any] = {+ "dateRange": {"date_from": date_from, "date_to": date_to},+ "severityLevels": [],+ "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},+ "serviceNames": [],+ }+ if service_name_search is not None:+ query["serviceNameSearch"] = service_name_searchresponse = self.client.post(f"/api/projects/{self.team.id}/logs/services",- data={- "query": {- "dateRange": {"date_from": date_from, "date_to": date_to},- "severityLevels": [],- "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},- "serviceNames": [],- }- },+ data={"query": query},)self.assertEqual(response.status_code, status.HTTP_200_OK)return response.json()@@ -235,9 +238,8 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):@freeze_time("2025-12-16T10:33:00Z")def test_sparkline_covers_exactly_the_returned_services(self):- # The sparkline must line up exactly with the aggregates result: never a- # service the table won't render (extra), and never a displayed service- # missing its trend (the row-cap truncation the scoping fix removes).+ # Exact equality holds because the fixture's 12 services fit within+ # SPARKLINE_SERVICES_LIMIT; past the limit only the top services get a trend.result = self._services("2025-12-16T00:00:00Z", "2025-12-16T23:59:59Z")service_names = {s["service_name"] for s in result["services"]}sparkline_services = {row["service_name"] for row in result["sparkline"]}@@ -245,6 +247,46 @@ class TestServicesQueryDateRange(ClickhouseTestMixin, APIBaseTest):self.assertTrue(service_names)self.assertEqual(sparkline_services, service_names)+ # The tests below pass absolute date ranges instead of freezing time: the first+ # request of a test process imports the URLconf, and transitively pydantic.v1,+ # whose date subclasses cannot be built while freezegun has datetime.date patched.+ def test_cap_limits_services_but_not_total_count(self):+ with patch.object(services_query_runner, "SERVICES_LIMIT", 5):+ result = self._services("2025-12-16T00:00:00Z", "2025-12-16T23:59:59Z")++ self.assertEqual(len(result["services"]), 5)+ self.assertEqual(result["total_services"], 12)+ # The cap keeps the highest-volume services: every kept fixture service has+ # 97+ rows, so the smallest two (11 and 3 rows) are the ones cut.+ self.assertTrue(all(s["log_count"] >= 97 for s in result["services"]))++ def test_sparkline_scoped_to_top_services_when_over_limit(self):+ with patch.object(services_query_runner, "SPARKLINE_SERVICES_LIMIT", 3):+ result = self._services("2025-12-16T00:00:00Z", "2025-12-16T23:59:59Z")++ top_names = {s["service_name"] for s in result["services"][:3]}+ sparkline_services = {row["service_name"] for row in result["sparkline"]}+ self.assertEqual(sparkline_services, top_names)++ @parameterized.expand(+ [+ (+ "case_insensitive_substring",+ "CDP",+ {"cdp-legacy-events-consumer", "cdp-api", "cdp-api-webhooks", "cdp-behavioural-events-consumer"},+ ),+ # Unescaped, "%_" matches every service name; no fixture name contains+ # a literal %, _, or backslash.+ ("wildcards_matched_literally", "%_", set()),+ ("backslash_matched_literally", "\\", set()),+ ]+ )+ def test_service_name_search(self, _name: str, search: str, expected_names: set[str]):+ result = self._services("2025-12-16T00:00:00Z", "2025-12-16T23:59:59Z", service_name_search=search)++ self.assertEqual({s["service_name"] for s in result["services"]}, expected_names)+ self.assertEqual(result["total_services"], len(expected_names))+if __name__ == "__main__":pytest.main([__file__, "-v"])diff --git a/products/logs/frontend/LogsScene.stories.tsx b/products/logs/frontend/LogsScene.stories.tsxindex c40d2f90166a..d57772d80fc0 100644--- a/products/logs/frontend/LogsScene.stories.tsx+++ b/products/logs/frontend/LogsScene.stories.tsx@@ -1,7 +1,8 @@import { Meta } from '@storybook/react'-import { router } from 'kea-router'+import { combineUrl, router } from 'kea-router'import { useEffect } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { sampleOne } from 'lib/utils/arrays'import { dateStringToDayJs } from 'lib/utils/dateFilters'@@ -337,6 +338,85 @@ const valuesMock: MockSignature = async ({ request }) => {return [200, results]}+// Synthetic per-service aggregates for the Services tab: a realistic head of+// named services and a long generated tail, so pagination and the truncation+// banner both render.+const SERVICE_HEAD: [string, number, number][] = [+ // [name, log_count, error_rate]+ ['checkout-api', 4_182_330, 0.0021],+ ['ingestion-worker', 3_411_089, 0.0004],+ ['payments-gateway', 2_207_555, 0.1391],+ ['email-renderer', 1_876_002, 0.0102],+ ['session-recorder', 1_412_776, 0.0009],+ ['feature-flag-evaluator', 988_120, 0.0001],+ ['batch-exporter', 745_990, 0.0356],+ ['webhook-dispatcher', 512_304, 0.0044],+]++const SERVICES_FIXTURE = [+ ...SERVICE_HEAD,+ ...Array.from({ length: 992 }, (_, i): [string, number, number] => [+ `batch-worker-${String(i + 1).padStart(3, '0')}`,+ 400_000 - i * 400,+ 0.001,+ ]),+].map(([service_name, log_count, error_rate]) => {+ const error_count = Math.round(log_count * error_rate)+ const warn = Math.round(log_count * 0.05)+ const debug = Math.round(log_count * 0.2)+ return {+ service_name,+ log_count,+ error_count,+ error_rate,+ severity_breakdown: { debug, info: log_count - debug - warn - error_count, warn, error: error_count },+ active_rules: [],+ }+})++const servicesMock: MockSignature = async ({ request }) => {+ await delayIfNotTestRunner()+ const body = (await request.json()) as Record<string, any>+ const query = body.query ?? {}++ let services = SERVICES_FIXTURE+ if (query.serviceNameSearch) {+ const term = String(query.serviceNameSearch).toLowerCase()+ services = services.filter((s) => s.service_name.toLowerCase().includes(term))+ }+ const totalServices = services.length + (query.serviceNameSearch ? 0 : 287) // pretend a tail beyond the cap exists+ if (query.serviceNames?.length) {+ services = services.filter((s) => query.serviceNames.includes(s.service_name))+ }+ services = services.slice(0, 1000)++ const totalLogs = services.reduce((acc, s) => acc + s.log_count, 0)+ const sparklineFor = services.slice(0, 25)+ const sparkline = sparklineFor.flatMap((s) =>+ Array.from({ length: 24 }, (_, hour) => ({+ time: dayjs('2023-02-17T00:00:00Z').add(hour, 'hour').toISOString(),+ service_name: s.service_name,+ count: Math.max(1, Math.round((s.log_count / 24) * (0.6 + 0.8 * Math.abs(Math.sin(hour + s.log_count))))),+ }))+ )++ return [+ 200,+ {+ services: services.map((s) => ({+ ...s,+ volume_share_pct: totalLogs ? Math.round((10000 * s.log_count) / totalLogs) / 100 : 0,+ })),+ sparkline,+ total_services: totalServices,+ summary: {+ top_services_count: Math.min(5, services.length),+ top_services_volume_share_pct: 68.4,+ },+ },+ ]+}+export default {title: 'Scenes-App/Logs',decorators: [@@ -350,6 +430,7 @@ export default {post: {'/api/environments/:team_id/logs/query': queryMock,'/api/environments/:team_id/logs/sparkline': sparklineMock,+ '/api/environments/:team_id/logs/services': servicesMock,},}),],@@ -374,3 +455,16 @@ export function LogsScene(): JSX.Element {LogsScene.parameters = {featureFlags: [],}++export function LogsSceneServicesTab(): JSX.Element {+ useEffect(() => {+ router.actions.push(combineUrl(urls.logs(), { activeTab: 'services' }).url)+ }, [])+ return <App />+}+LogsSceneServicesTab.parameters = {+ featureFlags: [FEATURE_FLAGS.LOGS_SERVICES_VIEW],+ testOptions: {+ waitForSelector: '.LemonTable',+ },+}diff --git a/products/logs/frontend/components/LogsServices/LogsServices.tsx b/products/logs/frontend/components/LogsServices/LogsServices.tsxindex 2d3d108be9ef..dc8b7c5ed811 100644--- a/products/logs/frontend/components/LogsServices/LogsServices.tsx+++ b/products/logs/frontend/components/LogsServices/LogsServices.tsx@@ -3,7 +3,16 @@ import { combineUrl } from 'kea-router'import { useEffect, useMemo, useState } from 'react'import { IconShare } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonSelect, LemonTable, LemonTag, Tooltip, lemonToast } from '@posthog/lemon-ui'+import {+ LemonBanner,+ LemonButton,+ LemonInput,+ LemonSelect,+ LemonTable,+ LemonTag,+ Tooltip,+ lemonToast,+} from '@posthog/lemon-ui'import type { LemonTableColumns } from '@posthog/lemon-ui'import { Sparkline } from 'lib/components/Sparkline'@@ -14,7 +23,7 @@ import { urls } from 'scenes/urls'import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'-import { logsServicesLogic, ServiceRow } from './logsServicesLogic'+import { logsServicesLogic, SERVICES_PAGE_SIZE, ServiceRow } from './logsServicesLogic'/** Collapsed Rules column shows this many rule chips before "+ N more". */const RULES_PREVIEW_COUNT = 3@@ -152,9 +161,19 @@ function copyServiceDeepLink(serviceName: string): void {}export function LogsServices(): JSX.Element {- const { services, servicesDataLoading, sparklineByService, dateFrom, servicesSummary } =- useValues(logsServicesLogic)- const { setDateFrom } = useActions(logsServicesLogic)+ const {+ services,+ pageRows,+ page,+ searchTerm,+ servicesDataLoading,+ sorting,+ sparklineByService,+ dateFrom,+ servicesSummary,+ totalServices,+ } = useValues(logsServicesLogic)+ const { setDateFrom, setPage, setSearchTerm, setSorting } = useActions(logsServicesLogic)const { openLogsViewerModal } = useActions(logsViewerModalLogic)const samplingRulesUi = useFeatureFlag(LogsFeatureFlagKeys.dropRules)@@ -194,13 +213,13 @@ export function LogsServices(): JSX.Element {{row.service_name}</span>),- sorter: (a, b) => a.service_name.localeCompare(b.service_name),+ sorter: true,},{title: 'Log volume',dataIndex: 'log_count',render: (_, row) => humanFriendlyNumber(row.log_count),- sorter: (a, b) => a.log_count - b.log_count,+ sorter: true,align: 'right',},{@@ -231,7 +250,7 @@ export function LogsServices(): JSX.Element {const type = row.error_rate > 0.1 ? 'danger' : row.error_rate > 0.01 ? 'warning' : 'success'return <LemonTag type={type}>{pct}%</LemonTag>},- sorter: (a, b) => a.error_rate - b.error_rate,+ sorter: true,align: 'right',},...(samplingRulesUi@@ -301,21 +320,51 @@ export function LogsServices(): JSX.Element {{servicesSummary.top_services_volume_share_pct.toFixed(1)}% of traffic in this window.</LemonBanner>)}+ {totalServices > services.length && (+ <LemonBanner type="info" className="mb-0">+ Showing the top {humanFriendlyNumber(services.length)} of {humanFriendlyNumber(totalServices)}{' '}+ {searchTerm ? 'matching services' : 'services'} by volume.{' '}+ {searchTerm ? 'Refine your search to see the rest.' : 'Use search to find the rest.'}+ </LemonBanner>+ )}<div className="flex items-center justify-between gap-2"><h3 className="m-0">Services</h3>- <LemonSelect- size="small"- value={dateFrom}- onChange={(value) => value && setDateFrom(value)}- options={DATE_OPTIONS}- />+ <div className="flex items-center gap-2">+ <LemonInput+ size="small"+ type="search"+ placeholder="Search services"+ value={searchTerm}+ onChange={setSearchTerm}+ />+ <LemonSelect+ size="small"+ value={dateFrom}+ onChange={(value) => value && setDateFrom(value)}+ options={DATE_OPTIONS}+ />+ </div></div>+ {/* Pagination and sorting are controlled by the logic (which passes in the+ pre-sorted page slice) so it knows which rows are visible and can lazy-load+ their sparklines; the backend only sparklines the top rows per request. */}<LemonTablecolumns={columns}- dataSource={services}+ dataSource={pageRows}loading={servicesDataLoading}- defaultSorting={{ columnKey: 'log_count', order: -1 }}- emptyState="No services found in this time range"+ sorting={sorting}+ onSort={(newSorting) => setSorting(newSorting)}+ useURLForSorting={false}+ pagination={{+ controlled: true,+ pageSize: SERVICES_PAGE_SIZE,+ currentPage: page,+ entryCount: services.length,+ onForward: () => setPage(page + 1),+ onBackward: () => setPage(page - 1),+ useUrl: false,+ }}+ emptyState={searchTerm ? 'No services match your search' : 'No services found in this time range'}rowKey="service_name"size="small"/>diff --git a/products/logs/frontend/components/LogsServices/logsServicesLogic.test.ts b/products/logs/frontend/components/LogsServices/logsServicesLogic.test.tsnew file mode 100644index 000000000000..b1f719983530--- /dev/null+++ b/products/logs/frontend/components/LogsServices/logsServicesLogic.test.ts@@ -0,0 +1,98 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { logsServicesCreate } from 'products/logs/frontend/generated/api'+import type { _LogsServicesResponseApi } from 'products/logs/frontend/generated/api.schemas'++import { logsServicesLogic } from './logsServicesLogic'++jest.mock('products/logs/frontend/generated/api', () => ({+ __esModule: true,+ logsServicesCreate: jest.fn(),+}))++// 30 services (2 pages of 25): svc-1..svc-29 by descending volume, plus the+// backend's placeholder name for empty service_name as the lowest-volume row.+const SERVICES = Array.from({ length: 30 }, (_, i) => ({+ service_name: i === 29 ? '(no service)' : `svc-${i + 1}`,+ log_count: 1000 - i,+ error_count: 0,+ error_rate: 0,+}))++const INITIAL_RESPONSE: _LogsServicesResponseApi = {+ services: SERVICES,+ // The backend sparklines only the top services of the response.+ sparkline: SERVICES.slice(0, 25).map((s) => ({+ time: '2026-08-12T00:00:00Z',+ service_name: s.service_name,+ count: 1,+ })),+ total_services: 30,+}++// A page-turn response is only read for its sparkline; names arrive with the+// backend's "(no service)" placeholder already applied, same as the initial load.+const PAGE_2_SPARKLINE_RESPONSE: _LogsServicesResponseApi = {+ services: [],+ sparkline: SERVICES.slice(25).map((s) => ({+ time: '2026-08-12T00:00:00Z',+ service_name: s.service_name,+ count: 1,+ })),+ total_services: 0,+}++describe('logsServicesLogic', () => {+ let logic: ReturnType<typeof logsServicesLogic.build>++ beforeEach(() => {+ jest.mocked(logsServicesCreate).mockReset()+ jest.mocked(logsServicesCreate).mockResolvedValueOnce(INITIAL_RESPONSE)+ jest.mocked(logsServicesCreate).mockResolvedValue(PAGE_2_SPARKLINE_RESPONSE)+ initKeaTests()+ logic = logsServicesLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('fetches sparklines only for services the initial response did not cover, once', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logsServicesCreate).toHaveBeenCalledTimes(1)++ await expectLogic(logic, () => {+ logic.actions.setPage(2)+ }).toFinishAllListeners()++ expect(logsServicesCreate).toHaveBeenCalledTimes(2)+ const [, secondCall] = jest.mocked(logsServicesCreate).mock.calls+ // Page 2 holds the 5 lowest-volume rows; the placeholder name maps back+ // to the empty string the backend stores.+ expect(secondCall[1].query.serviceNames).toEqual(['svc-26', 'svc-27', 'svc-28', 'svc-29', ''])+ expect(logic.values.sparklineByService['(no service)']).toBeTruthy()++ // Revisiting an already-fetched page must not refetch.+ await expectLogic(logic, () => {+ logic.actions.setPage(1)+ logic.actions.setPage(2)+ }).toFinishAllListeners()+ expect(logsServicesCreate).toHaveBeenCalledTimes(2)+ })++ it('search reloads aggregates with the term and resets to page 1', async () => {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setPage(2)++ await expectLogic(logic, () => {+ logic.actions.setSearchTerm('api')+ }).toDispatchActions(['setSearchTerm', 'setPage', 'loadServicesData', 'loadServicesDataSuccess'])++ expect(logic.values.page).toBe(1)+ const lastCall = jest.mocked(logsServicesCreate).mock.calls.at(-1)+ expect(lastCall?.[1].query.serviceNameSearch).toBe('api')+ })+})diff --git a/products/logs/frontend/components/LogsServices/logsServicesLogic.ts b/products/logs/frontend/components/LogsServices/logsServicesLogic.tsindex 835a15fa68cc..a6c82c4a0439 100644--- a/products/logs/frontend/components/LogsServices/logsServicesLogic.ts+++ b/products/logs/frontend/components/LogsServices/logsServicesLogic.ts@@ -1,52 +1,52 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'--import { FilterLogicalOperator } from '~/types'--export interface ServiceRow {- service_name: string- log_count: number- error_count: number- error_rate: number- volume_share_pct?: number- severity_breakdown?: {- debug: number- info: number- warn: number- error: number- }- active_rules?: { rule_id: string; rule_name: string; summary_string: string }[]-}+import type { Sorting } from 'lib/lemon-ui/LemonTable'+import { teamLogic } from 'scenes/teamLogic'++import { logsServicesCreate } from 'products/logs/frontend/generated/api'+import type {+ _LogsServiceAggregateApi,+ _LogsServicesResponseApi,+ _LogsServicesSparklineBucketApi,+ _LogsServicesSummaryApi,+} from 'products/logs/frontend/generated/api.schemas'++export type ServiceRow = _LogsServiceAggregateApi-export interface ServiceSparklinePoint {- time: string- service_name: string- count: number+// Must stay at or below the backend's SPARKLINE_SERVICES_LIMIT: a page-turn+// sparkline request covers at most that many names, and names beyond it would+// come back without data.+export const SERVICES_PAGE_SIZE = 25++/** Placeholder the backend substitutes for an empty service name; map back to '' when filtering. */+const NO_SERVICE_LABEL = '(no service)'++const EMPTY_SERVICES_RESPONSE: _LogsServicesResponseApi = {+ services: [],+ sparkline: [],+ total_services: 0,}-export interface ServicesResponse {- services: ServiceRow[]- sparkline: ServiceSparklinePoint[]- summary?: {- top_services_count: number- top_services_volume_share_pct: number- }+const SORT_COMPARATORS: Record<string, (a: ServiceRow, b: ServiceRow) => number> = {+ service_name: (a, b) => a.service_name.localeCompare(b.service_name),+ log_count: (a, b) => a.log_count - b.log_count,+ error_rate: (a, b) => a.error_rate - b.error_rate,}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsServicesLogicValues {+ currentTeamId: number | null // teamLogicdateFrom: string+ page: number+ pageRows: ServiceRow[]+ searchTerm: stringservices: ServiceRow[]- servicesData: ServicesResponse+ servicesData: _LogsServicesResponseApiservicesDataLoading: boolean- servicesSummary:- | {- top_services_count: number- top_services_volume_share_pct: number- }- | undefined+ servicesSummary: _LogsServicesSummaryApi | undefined+ sortedServices: ServiceRow[]+ sorting: Sorting | nullsparklineByService: Record<string,{@@ -54,10 +54,16 @@ export interface logsServicesLogicValues {values: number[]}>+ sparklinePoints: _LogsServicesSparklineBucketApi[]+ sparklineRequested: Record<string, boolean>+ totalServices: number}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsServicesLogicActions {+ ensureSparklinesForPage: () => {+ value: true+ }loadServicesData: () => anyloadServicesDataFailure: (error: string,@@ -67,96 +73,44 @@ export interface logsServicesLogicActions {errorObject?: any}loadServicesDataSuccess: (- servicesData: {- services: {- active_rules?:- | {- rule_id: string- rule_name: string- summary_string: string- }[]- | undefined- error_count: number- error_rate: number- log_count: number- service_name: string- severity_breakdown?:- | {- debug: number- error: number- info: number- warn: number- }- | undefined- volume_share_pct?: number | undefined- }[]- sparkline: {- count: number- service_name: string- time: string- }[]- summary?:- | {- top_services_count: number- top_services_volume_share_pct: number- }- | undefined- },+ servicesData: _LogsServicesResponseApi,payload?: any) => {- servicesData: {- services: {- active_rules?:- | {- rule_id: string- rule_name: string- summary_string: string- }[]- | undefined- error_count: number- error_rate: number- log_count: number- service_name: string- severity_breakdown?:- | {- debug: number- error: number- info: number- warn: number- }- | undefined- volume_share_pct?: number | undefined- }[]- sparkline: {- count: number- service_name: string- time: string- }[]- summary?:- | {- top_services_count: number- top_services_volume_share_pct: number- }- | undefined- }+ servicesData: _LogsServicesResponseApipayload?: any}+ markSparklineRequested: (serviceNames: string[]) => {+ serviceNames: string[]+ }+ mergeSparklinePoints: (points: _LogsServicesSparklineBucketApi[]) => {+ points: _LogsServicesSparklineBucketApi[]+ }setDateFrom: (dateFrom: string) => {dateFrom: string}+ setPage: (page: number) => {+ page: number+ }+ setSearchTerm: (searchTerm: string) => {+ searchTerm: string+ }+ setSorting: (sorting: Sorting | null) => {+ sorting: Sorting | null+ }+ unmarkSparklineRequested: (serviceNames: string[]) => {+ serviceNames: string[]+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface logsServicesLogicMeta {__keaTypeGenInternalSelectorTypes: {- services: (servicesData: ServicesResponse) => ServiceRow[]- servicesSummary: (servicesData: ServicesResponse) =>- | {- top_services_count: number- top_services_volume_share_pct: number- }- | undefined- sparklineByService: (servicesData: ServicesResponse) => Record<+ services: (servicesData: _LogsServicesResponseApi) => ServiceRow[]+ totalServices: (servicesData: _LogsServicesResponseApi) => number+ servicesSummary: (servicesData: _LogsServicesResponseApi) => _LogsServicesSummaryApi | undefined+ sortedServices: (services: _LogsServiceAggregateApi[], sorting: Sorting | null) => ServiceRow[]+ pageRows: (sortedServices: _LogsServiceAggregateApi[], page: number) => ServiceRow[]+ sparklineByService: (sparklinePoints: _LogsServicesSparklineBucketApi[]) => Record<string,{labels: string[]@@ -176,8 +130,17 @@ export type logsServicesLogicType = MakeLogicType<export const logsServicesLogic = kea<logsServicesLogicType>([path(['products', 'logs', 'frontend', 'components', 'LogsServices', 'logsServicesLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeamId']] })),+actions({setDateFrom: (dateFrom: string) => ({ dateFrom }),+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setPage: (page: number) => ({ page }),+ setSorting: (sorting: Sorting | null) => ({ sorting }),+ ensureSparklinesForPage: true,+ markSparklineRequested: (serviceNames: string[]) => ({ serviceNames }),+ unmarkSparklineRequested: (serviceNames: string[]) => ({ serviceNames }),+ mergeSparklinePoints: (points: _LogsServicesSparklineBucketApi[]) => ({ points }),}),reducers({@@ -187,44 +150,112 @@ export const logsServicesLogic = kea<logsServicesLogicType>([setDateFrom: (_, { dateFrom }) => dateFrom,},],+ searchTerm: [+ '' as string,+ {+ setSearchTerm: (_, { searchTerm }) => searchTerm,+ },+ ],+ page: [+ 1 as number,+ {+ setPage: (_, { page }) => Math.max(1, page),+ },+ ],+ sorting: [+ { columnKey: 'log_count', order: -1 } as Sorting | null,+ {+ setSorting: (_, { sorting }) => sorting,+ },+ ],+ // Sparkline buckets accumulate as pages are visited; a fresh aggregate+ // load resets them because the window or filters changed.+ sparklinePoints: [+ [] as _LogsServicesSparklineBucketApi[],+ {+ loadServicesDataSuccess: (_, { servicesData }) => servicesData.sparkline,+ mergeSparklinePoints: (state, { points }) => [...state, ...points],+ },+ ],+ // Tracks only in-flight page fetches; already-covered services are+ // recognized by their presence in sparklineByService.+ sparklineRequested: [+ {} as Record<string, boolean>,+ {+ loadServicesDataSuccess: () => ({}),+ markSparklineRequested: (state, { serviceNames }) => ({+ ...state,+ ...Object.fromEntries(serviceNames.map((name) => [name, true])),+ }),+ unmarkSparklineRequested: (state, { serviceNames }) => {+ const next = { ...state }+ for (const name of serviceNames) {+ delete next[name]+ }+ return next+ },+ },+ ],}),loaders(({ values }) => ({servicesData: [- { services: [], sparkline: [], summary: undefined } as ServicesResponse,+ EMPTY_SERVICES_RESPONSE,{loadServicesData: async () => {- const response = await api.logs.services({+ if (!values.currentTeamId) {+ return EMPTY_SERVICES_RESPONSE+ }+ return await logsServicesCreate(String(values.currentTeamId), {query: {dateRange: { date_from: values.dateFrom },- severityLevels: [],- filterGroup: { type: FilterLogicalOperator.And, values: [] },- serviceNames: [],+ ...(values.searchTerm ? { serviceNameSearch: values.searchTerm } : {}),},})- return response},},],})),selectors({- services: [(s) => [s.servicesData], (data: ServicesResponse): ServiceRow[] => data.services],+ services: [(s) => [s.servicesData], (data: _LogsServicesResponseApi): ServiceRow[] => data.services],++ totalServices: [(s) => [s.servicesData], (data: _LogsServicesResponseApi): number => data.total_services],++ servicesSummary: [(s) => [s.servicesData], (data: _LogsServicesResponseApi) => data.summary],++ sortedServices: [+ (s) => [s.services, s.sorting],+ (services: ServiceRow[], sorting: Sorting | null): ServiceRow[] => {+ if (!sorting || !SORT_COMPARATORS[sorting.columnKey]) {+ return services+ }+ const comparator = SORT_COMPARATORS[sorting.columnKey]+ return [...services].sort((a, b) => comparator(a, b) * sorting.order)+ },+ ],- servicesSummary: [(s) => [s.servicesData], (data: ServicesResponse) => data.summary],+ pageRows: [+ (s) => [s.sortedServices, s.page],+ (sortedServices: ServiceRow[], page: number): ServiceRow[] =>+ sortedServices.slice((page - 1) * SERVICES_PAGE_SIZE, page * SERVICES_PAGE_SIZE),+ ],sparklineByService: [- (s) => [s.servicesData],- (data: ServicesResponse): Record<string, { values: number[]; labels: string[] }> => {+ (s) => [s.sparklinePoints],+ (points: _LogsServicesSparklineBucketApi[]): Record<string, { values: number[]; labels: string[] }> => {const byService: Record<string, Map<string, number>> = {}const allTimes = new Set<string>()- for (const point of data.sparkline) {+ for (const point of points) {allTimes.add(point.time)- if (!byService[point.service_name]) {- byService[point.service_name] = new Map()+ // The backend substitutes NO_SERVICE_LABEL for empty names+ // before serializing, so point names match row names as-is.+ const name = point.service_name+ if (!byService[name]) {+ byService[name] = new Map()}- byService[point.service_name].set(point.time, point.count)+ byService[name].set(point.time, point.count)}const sortedTimes = Array.from(allTimes).sort()@@ -242,10 +273,54 @@ export const logsServicesLogic = kea<logsServicesLogicType>([],}),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({setDateFrom: () => {+ actions.setPage(1)actions.loadServicesData()},+ setSearchTerm: async (_, breakpoint) => {+ actions.setPage(1)+ await breakpoint(300)+ actions.loadServicesData()+ },+ setPage: () => {+ actions.ensureSparklinesForPage()+ },+ setSorting: () => {+ actions.setPage(1)+ },+ loadServicesDataSuccess: () => {+ actions.ensureSparklinesForPage()+ },+ ensureSparklinesForPage: async () => {+ const missing = values.pageRows+ .map((row) => row.service_name)+ .filter((name) => !values.sparklineByService[name] && !values.sparklineRequested[name])+ if (missing.length === 0 || !values.currentTeamId) {+ return+ }+ actions.markSparklineRequested(missing)+ const dateFrom = values.dateFrom+ const searchTerm = values.searchTerm+ let response+ try {+ response = await logsServicesCreate(String(values.currentTeamId), {+ query: {+ dateRange: { date_from: dateFrom },+ serviceNames: missing.map((name) => (name === NO_SERVICE_LABEL ? '' : name)),+ },+ })+ } catch {+ // Unmark so revisiting the page retries instead of showing+ // permanently empty sparklines.+ actions.unmarkSparklineRequested(missing)+ return+ }+ if (values.dateFrom !== dateFrom || values.searchTerm !== searchTerm) {+ return+ }+ actions.mergeSparklinePoints(response.sparkline)+ },})),afterMount(({ actions }) => {diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex c652ac6b260e..3dbfa57d9713 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -2013,6 +2013,11 @@ export interface _LogsServicesBodyApi {serviceNames?: string[]/** Full-text search term to filter log bodies. */searchTerm?: string+ /**+ * Case-insensitive substring match on service name, applied before aggregation. Use to reach services beyond the response cap.+ * @maxLength 200+ */+ serviceNameSearch?: string/** Property filters for the query. */filterGroup?: _LogPropertyFilterApi[]}@@ -2067,10 +2072,12 @@ export interface _LogsServicesSummaryApi {}export interface _LogsServicesResponseApi {- /** Per-service aggregates, ordered by log_count descending. Capped at 25 services. */+ /** Per-service aggregates, ordered by log_count descending. Capped at 1000 services. */services: _LogsServiceAggregateApi[]- /** Time-bucketed counts broken down by service, for plotting volume over time. */+ /** Time-bucketed counts broken down by service, for plotting volume over time. Covers only the top 25 services in this response; re-request with `serviceNames` to get sparklines for specific services. */sparkline: _LogsServicesSparklineBucketApi[]+ /** True distinct service count for the window and filters, unaffected by the 1000-service cap on `services`. Greater than the length of `services` when the response is truncated. */+ total_services: number/** Roll-up stats for the Services tab header. */summary?: _LogsServicesSummaryApi}diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.tsindex b14c84e5eb98..43e8dddf7d20 100644--- a/products/logs/frontend/generated/api.zod.ts+++ b/products/logs/frontend/generated/api.zod.ts@@ -1621,6 +1621,8 @@ export const LogsSamplingRulesReorderCreateBody = /* @__PURE__ */ zod.object({),})+export const logsServicesCreateBodyQueryOneServiceNameSearchMax = 200+export const LogsServicesCreateBody = /* @__PURE__ */ zod.object({query: zod.object({@@ -1654,6 +1656,13 @@ export const LogsServicesCreateBody = /* @__PURE__ */ zod.object({.optional().describe('Restrict the aggregation to these service names.'),searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies.'),+ serviceNameSearch: zod+ .string()+ .max(logsServicesCreateBodyQueryOneServiceNameSearchMax)+ .optional()+ .describe(+ 'Case-insensitive substring match on service name, applied before aggregation. Use to reach services beyond the response cap.'+ ),filterGroup: zod.array(zod.object({diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a273e32f0b6e..0117787ea7de 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -79522,6 +79522,11 @@ export namespace Schemas {serviceNames?: string[];/** Full-text search term to filter log bodies. */searchTerm?: string;+ /**+ * Case-insensitive substring match on service name, applied before aggregation. Use to reach services beyond the response cap.+ * @maxLength 200+ */+ serviceNameSearch?: string;/** Property filters for the query. */filterGroup?: _LogPropertyFilter[];}@@ -79546,10 +79551,12 @@ export namespace Schemas {}export interface _LogsServicesResponse {- /** Per-service aggregates, ordered by log_count descending. Capped at 25 services. */+ /** Per-service aggregates, ordered by log_count descending. Capped at 1000 services. */services: _LogsServiceAggregate[];- /** Time-bucketed counts broken down by service, for plotting volume over time. */+ /** Time-bucketed counts broken down by service, for plotting volume over time. Covers only the top 25 services in this response; re-request with `serviceNames` to get sparklines for specific services. */sparkline: _LogsServicesSparklineBucket[];+ /** True distinct service count for the window and filters, unaffected by the 1000-service cap on `services`. Greater than the length of `services` when the response is truncated. */+ total_services: number;/** Roll-up stats for the Services tab header. */summary?: _LogsServicesSummary;}diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.tsindex 731f15f7a31a..fb1d00eca595 100644--- a/services/mcp/src/generated/logs/api.ts+++ b/services/mcp/src/generated/logs/api.ts@@ -4977,6 +4977,8 @@ export const LogsServicesCreateParams = /* @__PURE__ */ zod.object({),})+export const logsServicesCreateBodyQueryOneServiceNameSearchMax = 200+export const LogsServicesCreateBody = /* @__PURE__ */ zod.object({query: zod.object({@@ -5010,6 +5012,13 @@ export const LogsServicesCreateBody = /* @__PURE__ */ zod.object({.optional().describe('Restrict the aggregation to these service names.'),searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies.'),+ serviceNameSearch: zod+ .string()+ .max(logsServicesCreateBodyQueryOneServiceNameSearchMax)+ .optional()+ .describe(+ 'Case-insensitive substring match on service name, applied before aggregation. Use to reach services beyond the response cap.'+ ),filterGroup: zod.array(zod.object({diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.jsonindex 319c2c4a42d2..e9c6a0f6c0c5 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/logs-services-create.json@@ -88,6 +88,11 @@},"type": "array"},+ "serviceNameSearch": {+ "description": "Case-insensitive substring match on service name, applied before aggregation. Use to reach services beyond the response cap.",+ "maxLength": 200,+ "type": "string"+ },"severityLevels": {"description": "Filter by log severity levels.","items": {