Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(logs): pick grouped log instances from the newest rows with a fu… (#110378)

Bryan Ciaraldi65e748e98a72
diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
index ce1dcac2ea5e..4158dffa4d5c 100644
--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
@@ -1,6 +1,7 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
@@ -10,10 +11,15 @@ import { LogEntryLevel } from '~/types'
import {
buildGroupedLogsQuery,
+ groupedLogsSliceRows,
groupLogs,
+ LOG_GROUP_MAX_SLICE_ROWS,
+ LOG_GROUP_ROWS_PER_GROUP,
+ LOG_GROUP_TOTAL_LOGS_LIMIT,
LogEntry,
LogEntryParams,
logsViewerLogic,
+ shouldRetryGroupedLogsWithoutSlice,
toAbsoluteClickhouseTimestamp,
} from './logsViewerLogic'
@@ -204,7 +210,107 @@ describe('logsViewerLogic', () => {
const firstPage = buildGroupedLogsQuery(makeParams(), 10, 0)
const secondPage = buildGroupedLogsQuery(makeParams(), 10, 10)
- expect(firstPage.replace('OFFSET 0', 'OFFSET 10')).toEqual(secondPage)
+ expect(
+ firstPage
+ .replace('OFFSET 0', 'OFFSET 10')
+ .replace(`LIMIT ${10 * LOG_GROUP_ROWS_PER_GROUP}`, `LIMIT ${20 * LOG_GROUP_ROWS_PER_GROUP}`)
+ ).toEqual(secondPage)
+ })
+
+ it.each([
+ { description: 'first page', args: [10, 0], expected: `LIMIT ${10 * LOG_GROUP_ROWS_PER_GROUP}` },
+ { description: 'later page', args: [10, 20], expected: `LIMIT ${30 * LOG_GROUP_ROWS_PER_GROUP}` },
+ ] as { description: string; args: [number, number]; expected: string }[])(
+ 'newest-first groups a slice of the newest rows sized for offset + limit groups ($description)',
+ ({ args, expected }) => {
+ const query = buildGroupedLogsQuery(makeParams({ order: 'DESC' }), ...args)
+
+ expect(query).toContain('FROM (')
+ expect(query).toContain(expected)
+ }
+ )
+
+ it.each([
+ { description: 'oldest-first', params: { order: 'ASC' as const }, args: [10, 0] },
+ {
+ description: 'pages past the slice cap',
+ params: {},
+ args: [10, LOG_GROUP_MAX_SLICE_ROWS / LOG_GROUP_ROWS_PER_GROUP],
+ },
+ ] as { description: string; params: Partial<LogEntryParams>; args: [number, number] }[])(
+ 'uses the full GROUP BY for $description',
+ ({ params, args }) => {
+ const request = makeParams(params)
+
+ expect(groupedLogsSliceRows(request, ...args)).toBeNull()
+ expect(buildGroupedLogsQuery(request, ...args)).not.toContain('FROM (')
+ }
+ )
+ })
+
+ describe('shouldRetryGroupedLogsWithoutSlice', () => {
+ const entriesFor = (instanceIds: string[], linesEach: number = 1): LogEntry[] =>
+ instanceIds.flatMap((id) =>
+ Array.from({ length: linesEach }, (_, i) =>
+ makeEntry(id, `2024-01-15 10:00:${String(i % 60).padStart(2, '0')}`)
+ )
+ )
+
+ it.each([
+ { description: 'a full page of groups', ids: 10, linesEach: 1, expected: false },
+ { description: 'a short page', ids: 3, linesEach: 1, expected: true },
+ { description: 'an empty page', ids: 0, linesEach: 1, expected: true },
+ {
+ description: 'a short page that hit the line cap',
+ ids: 2,
+ linesEach: LOG_GROUP_TOTAL_LOGS_LIMIT / 2,
+ expected: false,
+ },
+ ])('$description -> retry: $expected', ({ ids, linesEach, expected }) => {
+ const instanceIds = Array.from({ length: ids }, (_, i) => `instance-${i}`)
+
+ expect(shouldRetryGroupedLogsWithoutSlice(entriesFor(instanceIds, linesEach), 10)).toBe(expected)
+ })
+ })
+
+ describe('grouped logs loading', () => {
+ const rowsFor = (instanceCount: number): any[][] =>
+ Array.from({ length: instanceCount }, (_, i) => [`instance-${i}`, '2024-01-15 10:00:00', 'info', 'msg'])
+
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ { description: 'a full sliced page is used as is', firstPageInstances: 10, expectedQueries: 1 },
+ {
+ description: 'a short sliced page is re-run with the full GROUP BY',
+ firstPageInstances: 3,
+ expectedQueries: 2,
+ },
+ ])('$description', async ({ firstPageInstances, expectedQueries }) => {
+ const querySpy = jest
+ .spyOn(api, 'queryHogQL')
+ .mockResolvedValueOnce({ results: rowsFor(firstPageInstances) } as any)
+ .mockResolvedValue({ results: rowsFor(3) } as any)
+
+ const logic = logsViewerLogic({ sourceType: 'hog_function', sourceId: 'fn-1', disableUrlSync: true })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadGroupedLogsSuccess'])
+
+ const groupedQueries = querySpy.mock.calls
+ .map(([query]) => String(query))
+ .filter((query) => query.includes('GROUP BY instance_id'))
+ expect(groupedQueries).toHaveLength(expectedQueries)
+ expect(groupedQueries[0]).toContain('FROM (')
+ if (expectedQueries === 2) {
+ expect(groupedQueries[1]).not.toContain('FROM (')
+ }
+ logic.unmount()
})
})
diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
index 1e3a17550890..c596e406ef7c 100644
--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
@@ -29,6 +29,9 @@ export const POLLING_INTERVAL = 5000
export const LOG_VIEWER_LIMIT = 100
export const LOG_GROUP_LIMIT = 10
export const LOG_GROUP_TOTAL_LOGS_LIMIT = 5000
+// Bounds cost only: a short sliced page falls back to the full GROUP BY in loadGroupedLogs.
+export const LOG_GROUP_ROWS_PER_GROUP = 10000
+export const LOG_GROUP_MAX_SLICE_ROWS = 1_000_000
export type LogsViewerLogicProps = {
logicKey?: string
@@ -127,16 +130,7 @@ const buildSearchFilters = ({ searchGroups, levels, instanceId }: LogEntryParams
return query
}
-const loadLogs = async (request: LogEntryParams): Promise<LogEntry[]> => {
- const query = hogql`
- SELECT instance_id, timestamp, level, message
- FROM log_entries
- WHERE 1=1
- ${hogql.raw(buildBoundaryFilters(request))}
- ${hogql.raw(buildSearchFilters(request))}
- ORDER BY timestamp ${hogql.raw(request.order)}
- LIMIT ${request.limit ?? LOG_VIEWER_LIMIT}`
-
+const queryLogEntries = async (query: HogQLQueryString, request: LogEntryParams): Promise<LogEntry[]> => {
const response = await api.queryHogQL(
query,
{ scene: 'HogFunction', productKey: 'pipeline_destinations' },
@@ -160,6 +154,41 @@ const loadLogs = async (request: LogEntryParams): Promise<LogEntry[]> => {
)
}
+const loadLogs = async (request: LogEntryParams): Promise<LogEntry[]> => {
+ const query = hogql`
+ SELECT instance_id, timestamp, level, message
+ FROM log_entries
+ WHERE 1=1
+ ${hogql.raw(buildBoundaryFilters(request))}
+ ${hogql.raw(buildSearchFilters(request))}
+ ORDER BY timestamp ${hogql.raw(request.order)}
+ LIMIT ${request.limit ?? LOG_VIEWER_LIMIT}`
+
+ return await queryLogEntries(query, request)
+}
+
+// An instance in the newest-rows slice has its latest row there too, so the order matches the full GROUP BY
+// without its per-instance state. A slice of the oldest rows can understate max(timestamp), so ASC can't.
+export const groupedLogsSliceRows = (
+ request: LogEntryParams,
+ groupLimit: number,
+ groupOffset: number
+): number | null => {
+ if (request.order !== 'DESC') {
+ return null
+ }
+ const rows = (groupOffset + groupLimit) * LOG_GROUP_ROWS_PER_GROUP
+ return rows <= LOG_GROUP_MAX_SLICE_ROWS ? rows : null
+}
+
+// A page cut by the line cap loses the same groups under the full GROUP BY, so only short pages retry.
+export const shouldRetryGroupedLogsWithoutSlice = (entries: LogEntry[], groupLimit: number): boolean => {
+ if (entries.length >= LOG_GROUP_TOTAL_LOGS_LIMIT) {
+ return false
+ }
+ return new Set(entries.map((entry) => entry.instanceId)).size < groupLimit
+}
+
// Grouped pagination keyset-pages over instance groups by offsetting the group subquery, ordered by
// most recent activity. We deliberately do NOT paginate with a `timestamp < cursor` boundary: batch
// workflows emit hundreds of instances within the same millisecond, so a timestamp cursor (truncated
@@ -168,8 +197,25 @@ const loadLogs = async (request: LogEntryParams): Promise<LogEntry[]> => {
export const buildGroupedLogsQuery = (
request: LogEntryParams,
groupLimit: number,
- groupOffset: number = 0
+ groupOffset: number = 0,
+ sliceRows: number | null = groupedLogsSliceRows(request, groupLimit, groupOffset)
): HogQLQueryString => {
+ const groupSource =
+ sliceRows !== null
+ ? hogql`(
+ SELECT instance_id, timestamp
+ FROM log_entries
+ WHERE 1=1
+ ${hogql.raw(buildBoundaryFilters(request))}
+ ${hogql.raw(buildSearchFilters(request))}
+ ORDER BY timestamp DESC
+ LIMIT ${sliceRows}
+ )`
+ : hogql`log_entries
+ WHERE 1=1
+ ${hogql.raw(buildBoundaryFilters(request))}
+ ${hogql.raw(buildSearchFilters(request))}`
+
return hogql`
SELECT instance_id, timestamp, level, message
FROM log_entries
@@ -177,10 +223,7 @@ export const buildGroupedLogsQuery = (
${hogql.raw(buildBoundaryFilters(request))}
AND instance_id in (
SELECT instance_id
- FROM log_entries
- WHERE 1=1
- ${hogql.raw(buildBoundaryFilters(request))}
- ${hogql.raw(buildSearchFilters(request))}
+ FROM ${hogql.raw(groupSource)}
GROUP BY instance_id
ORDER BY max(timestamp) ${hogql.raw(request.order)}, instance_id DESC
LIMIT ${groupLimit}
@@ -195,29 +238,15 @@ const loadGroupedLogs = async (
groupLimit: number = LOG_GROUP_LIMIT,
groupOffset: number = 0
): Promise<LogEntry[]> => {
- const query = buildGroupedLogsQuery(request, groupLimit, groupOffset)
+ const run = (sliceRows: number | null): Promise<LogEntry[]> =>
+ queryLogEntries(buildGroupedLogsQuery(request, groupLimit, groupOffset, sliceRows), request)
- const response = await api.queryHogQL(
- query,
- { scene: 'HogFunction', productKey: 'pipeline_destinations' },
- {
- refresh: 'force_blocking',
- filtersOverride: {
- date_from: request.dateFrom ?? '-7d',
- date_to: request.dateTo,
- },
- }
- )
-
- return response.results.map(
- (result): LogEntry => ({
- instanceId: result[0],
- timestamp: dayjs(result[1]),
- rawTimestamp: result[1],
- level: result[2].toUpperCase(),
- message: result[3],
- })
- )
+ const sliceRows = groupedLogsSliceRows(request, groupLimit, groupOffset)
+ const entries = await run(sliceRows)
+ if (sliceRows !== null && shouldRetryGroupedLogsWithoutSlice(entries, groupLimit)) {
+ return await run(null)
+ }
+ return entries
}
export const groupLogs = (logs: LogEntry[]): GroupedLogEntry[] => {