From fe0a0577a435d7fe870e7f43ba3e584d4511cdb0 Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Fri, 4 Dec 2026 14:16:34 -0500 Subject: [PATCH] fix: Prevent windowing on multi-key sort states w/o leading timestamp --- .changeset/quiet-sorts-stay.md | 6 ++ .../SearchResultsToolbar/sortClause.ts | 6 +- .../useOffsetPaginatedQuery.test.tsx | 60 +++++++++++++++ .../src/utils/__tests__/queryParsers.test.ts | 35 +++++++++ packages/app/src/utils/queryParsers.ts | 6 ++ .../search/multi-key-sort-windowing.spec.ts | 56 ++++++++++++++ .../common-utils/src/__tests__/utils.test.ts | 77 +++++++++++++++++++ packages/common-utils/src/core/utils.ts | 54 ++++++++++++- packages/common-utils/src/macros.ts | 3 +- packages/common-utils/src/variables.ts | 36 +-------- 10 files changed, 297 insertions(+), 42 deletions(-) create mode 100644 .changeset/quiet-sorts-stay.md create mode 100644 packages/app/tests/e2e/features/search/multi-key-sort-windowing.spec.ts diff --git a/.changeset/quiet-sorts-stay.md b/.changeset/quiet-sorts-stay.md new file mode 100644 index 0000000000..5bf37c9567 --- /dev/null +++ b/.changeset/quiet-sorts-stay.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +--- + +fix: Don't bucket search queries by time when the leading sort key isn't the timestamp diff --git a/packages/app/src/components/SearchResultsToolbar/sortClause.ts b/packages/app/src/components/SearchResultsToolbar/sortClause.ts index 859a93f22d..fe77e3ca6d 100644 --- a/packages/app/src/components/SearchResultsToolbar/sortClause.ts +++ b/packages/app/src/components/SearchResultsToolbar/sortClause.ts @@ -1,5 +1,7 @@ -import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; -import { findBalancedParens } from '@hyperdx/common-utils/dist/variables'; +import { + findBalancedParens, + splitAndTrimWithBracket, +} from '@hyperdx/common-utils/dist/core/utils'; import { parseAsSortingStateString } from '@/utils/queryParsers'; diff --git a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx index 07eaf60ef5..d642bf5460 100644 --- a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx +++ b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx @@ -309,6 +309,66 @@ describe('useOffsetPaginatedQuery', () => { expect(result.current.data?.window.direction).toEqual('DESC'); }); + const renderWithOrderBy = async (orderBy: any) => { + const config = createMockChartConfig({ + dateRange: [ + new Date('2024-01-01T00:00:00Z'), + new Date('2024-01-02T00:00:00Z'), + ] as [Date, Date], + orderBy, + }); + mockReader.read + .mockResolvedValueOnce({ + done: false, + value: [ + { json: () => ['timestamp', 'message'] }, + { json: () => ['DateTime', 'String'] }, + ], + }) + .mockResolvedValueOnce({ done: true }); + const { result } = renderHook(() => useOffsetPaginatedQuery(config), { + wrapper, + }); + await waitFor(() => expect(result.current.isLoading).toBe(false)); + return result; + }; + + it.each([ + ['a multi-key string', 'Duration DESC, Timestamp DESC'], + [ + 'a multi-key sort folded into one valueExpression', + [{ valueExpression: 'Duration DESC, Timestamp', ordering: 'DESC' }], + ], + [ + 'a tuple whose timestamp is not the leading key', + '(Duration, Timestamp) DESC', + ], + ])( + 'should not use time windows when the leading key is not the timestamp (%s)', + async (_name, orderBy) => { + const result = await renderWithOrderBy(orderBy); + + expect(result.current.data?.window.startTime).toEqual( + new Date('2024-01-01T00:00:00Z'), + ); + expect(result.current.data?.window.endTime).toEqual( + new Date('2024-01-02T00:00:00Z'), + ); + expect(result.current.hasNextPage).toEqual(false); + }, + ); + + it('should still use time windows when the timestamp leads a multi-key sort', async () => { + const result = await renderWithOrderBy('Timestamp DESC, Duration DESC'); + + expect(result.current.data?.window.endTime).toEqual( + new Date('2024-01-02T00:00:00Z'), + ); + expect(result.current.data?.window.startTime).not.toEqual( + new Date('2024-01-01T00:00:00Z'), + ); + }); + it('should finish pagination when windowing is not being used', async () => { const config = createMockChartConfig({ dateRange: [ diff --git a/packages/app/src/utils/__tests__/queryParsers.test.ts b/packages/app/src/utils/__tests__/queryParsers.test.ts index 1e94b6d8c7..cc010fde7b 100644 --- a/packages/app/src/utils/__tests__/queryParsers.test.ts +++ b/packages/app/src/utils/__tests__/queryParsers.test.ts @@ -207,6 +207,41 @@ describe('parseAsSortingStateString', () => { }); }); + it('returns null for a multi-key sort', () => { + expect( + parseAsSortingStateString.parse('Duration DESC, Timestamp DESC'), + ).toBeNull(); + }); + + it('returns null for mixed-direction multi-key sorts', () => { + expect(parseAsSortingStateString.parse('a ASC, b DESC')).toBeNull(); + }); + + it('keeps commas inside a function call as one key', () => { + expect( + parseAsSortingStateString.parse( + 'toStartOfInterval(Timestamp, INTERVAL 1 DAY) DESC', + ), + ).toEqual({ + id: 'toStartOfInterval(Timestamp, INTERVAL 1 DAY)', + desc: true, + }); + }); + + it('keeps a quoted name with spaces as one key', () => { + expect(parseAsSortingStateString.parse('"duration min" ASC')).toEqual({ + id: '"duration min"', + desc: false, + }); + }); + + it('keeps a tuple sort as one key', () => { + expect(parseAsSortingStateString.parse('(a, b) DESC')).toEqual({ + id: '(a, b)', + desc: true, + }); + }); + it('is case-insensitive on the direction', () => { expect(parseAsSortingStateString.parse('Timestamp desc')).toEqual({ id: 'Timestamp', diff --git a/packages/app/src/utils/queryParsers.ts b/packages/app/src/utils/queryParsers.ts index 42e35b7e89..49a88754e8 100644 --- a/packages/app/src/utils/queryParsers.ts +++ b/packages/app/src/utils/queryParsers.ts @@ -1,4 +1,5 @@ import { createParser } from 'nuqs'; +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; import { DashboardFilterValue, DashboardFilterValueSchema, @@ -119,6 +120,11 @@ export const parseAsSortingStateString = createParser({ if (!match) { return null; } + // "a DESC, b DESC" is several keys; folding it into one id would hide the + // leading key from the windowing check. + if (splitAndTrimWithBracket(match[1]).length > 1) { + return null; + } return { id: match[1], desc: match[2].toUpperCase() === 'DESC', diff --git a/packages/app/tests/e2e/features/search/multi-key-sort-windowing.spec.ts b/packages/app/tests/e2e/features/search/multi-key-sort-windowing.spec.ts new file mode 100644 index 0000000000..bf5c9140ee --- /dev/null +++ b/packages/app/tests/e2e/features/search/multi-key-sort-windowing.spec.ts @@ -0,0 +1,56 @@ +import { SearchPage } from '../../page-objects/SearchPage'; +import { expect, test } from '../../utils/base-test'; +import { DEFAULT_TRACES_SOURCE_NAME } from '../../utils/constants'; + +// Bounds are bind parameters: the SQL names them and the URL carries values. +const TIME_RANGE_PREDICATE = + /Timestamp\s*>=\s*fromUnixTimestamp64Milli\(\{(\w+):Int64\}\)\s*AND\s*Timestamp\s*<=\s*fromUnixTimestamp64Milli\(\{(\w+):Int64\}\)/; +const RANGE_MS = 24 * 60 * 60 * 1000; + +test.describe( + 'Search with a multi-key Order By', + { tag: ['@search', '@full-stack'] }, + () => { + test('does not bucket by time window when the leading sort key is not the timestamp', async ({ + page, + }) => { + test.setTimeout(60000); + const searchPage = new SearchPage(page); + + const rowQuerySpansMs: number[] = []; + // query_id marks ClickHouse queries from the app. + page.on('request', request => { + const url = new URL(request.url()); + const body = request.postData() ?? ''; + if ( + url.searchParams.has('query_id') && + /ORDER BY\s+Duration DESC,\s*Timestamp DESC\s+LIMIT/.test(body) + ) { + const range = body.match(TIME_RANGE_PREDICATE); + if (range) { + const start = Number(url.searchParams.get(`param_${range[1]}`)); + const end = Number(url.searchParams.get(`param_${range[2]}`)); + rowQuerySpansMs.push(end - start); + } + } + }); + + const to = Date.now(); + const from = to - RANGE_MS; + await page.goto( + `/search?isLive=false&from=${from}&to=${to}&source=${encodeURIComponent( + DEFAULT_TRACES_SOURCE_NAME, + )}&orderBy=${encodeURIComponent( + encodeURIComponent('Duration DESC, Timestamp DESC'), + )}`, + ); + await searchPage.table.waitForRowsToPopulate(); + + expect(rowQuerySpansMs.length).toBeGreaterThan(0); + // A windowed query covers one narrow slice (1 to 15 minutes at first). + for (const span of rowQuerySpansMs) { + expect(span).toBeGreaterThanOrEqual(RANGE_MS - 1000); + } + }); + }, +); diff --git a/packages/common-utils/src/__tests__/utils.test.ts b/packages/common-utils/src/__tests__/utils.test.ts index 3d3bb6af68..6e909bcdfe 100644 --- a/packages/common-utils/src/__tests__/utils.test.ts +++ b/packages/common-utils/src/__tests__/utils.test.ts @@ -766,6 +766,83 @@ describe('utils', () => { expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); }); + it('should return false if a multi-key sort is collapsed into one valueExpression with a non-timestamp leading key', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: [ + { valueExpression: 'Duration DESC, Timestamp', ordering: 'DESC' }, + ], + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); + }); + + it('should return false if only a later key in a tuple is the timestamp', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: '(Duration, Timestamp) DESC', + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); + }); + + it('should return false for a multi-key string whose leading key is not the timestamp', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: 'Duration DESC, Timestamp DESC', + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); + }); + + it('should return false for a tuple valueExpression whose leading key is not the timestamp', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: [ + { valueExpression: '(Duration, Timestamp)', ordering: 'DESC' }, + ], + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); + }); + + it('should return true when the timestamp leads a multi-key sort', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: 'Timestamp ASC, Duration', + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(true); + }); + + it('should not split on commas inside the leading key function', () => { + const config = { + timestampValueExpression: + 'toStartOfInterval(Timestamp, INTERVAL 1 DAY)', + orderBy: 'toStartOfInterval(Timestamp, INTERVAL 1 DAY) DESC, Duration', + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(true); + }); + + it('should ignore parentheses inside quoted strings when unwrapping the leading key', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: "(concat(')', Duration), Timestamp) DESC", + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(false); + }); + + it('should return true for a parenthesized single timestamp key', () => { + const config = { + timestampValueExpression: 'Timestamp', + orderBy: '(Timestamp) DESC', + } as BuilderChartConfigWithDateRange; + + expect(isTimestampExpressionInFirstOrderBy(config)).toBe(true); + }); + it('should return true if the first ordering column is the timestampValueExpression', () => { const config = { timestampValueExpression: 'Timestamp', diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index c611a20ae7..7b2aa5f950 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -1237,6 +1237,54 @@ export const removeTrailingDirection = (s: string) => { return s; }; +/** + * Index of the `)` closing the `(` at `start`, or -1 when it is unclosed. + * + * Quote-aware: parens inside single- or double-quoted strings don't count, so + * `$__conditionalAll(col = 'a)b', $name)` terminates where it should. + */ +export function findBalancedParens(input: string, start: number): number { + let depth = 0; + let inSingleQuote = false; + let inDoubleQuote = false; + + for (let i = start; i < input.length; i++) { + const c = input.charAt(i); + + if (c === '"' && !inSingleQuote && !isQuoteEscapedByBackslash(input, i)) { + inDoubleQuote = !inDoubleQuote; + continue; + } + if (c === "'" && !inDoubleQuote && !isQuoteEscapedByBackslash(input, i)) { + inSingleQuote = !inSingleQuote; + continue; + } + if (inSingleQuote || inDoubleQuote) continue; + + if (c === '(') { + depth++; + } else if (c === ')') { + depth--; + if (depth === 0) return i; + } + } + + return -1; +} + +// A sort expression can hold several keys ("a DESC, b DESC") or a tuple +// ("(a, b) DESC"); only the first key decides the leading sort. +const getLeadingSortKey = (expression: string): string => { + let key = splitAndTrimWithBracket(expression)[0] ?? ''; + key = removeTrailingDirection(key); + + if (key.startsWith('(') && findBalancedParens(key, 0) === key.length - 1) { + key = splitAndTrimWithBracket(key.slice(1, -1))[0] ?? ''; + } + + return key; +}; + export const isTimestampExpressionInFirstOrderBy = ( config: BuilderChartConfigWithOptTimestamp, ) => { @@ -1253,9 +1301,9 @@ export const isTimestampExpressionInFirstOrderBy = ( config.timestampValueExpression, ); - return timestampValueExpressions.some(tve => - firstOrderingExpression.includes(tve), - ); + const leadingKey = getLeadingSortKey(firstOrderingExpression); + + return timestampValueExpressions.some(tve => leadingKey.includes(tve)); }; export const isFirstOrderByAscending = ( diff --git a/packages/common-utils/src/macros.ts b/packages/common-utils/src/macros.ts index 5c98c342e1..e0a264ed54 100644 --- a/packages/common-utils/src/macros.ts +++ b/packages/common-utils/src/macros.ts @@ -7,7 +7,7 @@ import { PromqlMacroName, } from './core/promql'; import { injectPromqlLabelMatchers } from './core/promqlLabelInjection'; -import { splitAndTrimWithBracket } from './core/utils'; +import { findBalancedParens, splitAndTrimWithBracket } from './core/utils'; import { MacroExpansionError, MalformedMacroArgsError } from './macroErrors'; import { RawSqlQueryParam, renderQueryParam } from './rawSqlParams'; import { @@ -23,7 +23,6 @@ import { import { expandTemplate, expandVariableToken, - findBalancedParens, hasVariableMacro, VARIABLE_MACRO_NAMES, VariableContext, diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index d03d4c45ea..a27ad3255c 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -4,6 +4,7 @@ import { partition } from 'lodash'; import { getPromqlSeries } from './core/promql'; import { escapeSqlString, + findBalancedParens, isQuoteEscapedByBackslash, splitAndTrimWithBracket, } from './core/utils'; @@ -225,41 +226,6 @@ export function findCommentEnd(input: string, start: number): number { const isWordChar = (char: string | undefined) => char !== undefined && /[A-Za-z0-9_]/.test(char); -/** - * Index of the `)` closing the `(` at `start`, or -1 when it is unclosed. - * - * Quote-aware: parens inside single- or double-quoted strings don't count, so - * `$__conditionalAll(col = 'a)b', $name)` terminates where it should. - */ -export function findBalancedParens(input: string, start: number): number { - let depth = 0; - let inSingleQuote = false; - let inDoubleQuote = false; - - for (let i = start; i < input.length; i++) { - const c = input.charAt(i); - - if (c === '"' && !inSingleQuote && !isQuoteEscapedByBackslash(input, i)) { - inDoubleQuote = !inDoubleQuote; - continue; - } - if (c === "'" && !inDoubleQuote && !isQuoteEscapedByBackslash(input, i)) { - inSingleQuote = !inSingleQuote; - continue; - } - if (inSingleQuote || inDoubleQuote) continue; - - if (c === '(') { - depth++; - } else if (c === ')') { - depth--; - if (depth === 0) return i; - } - } - - return -1; -} - /** * Split a template into text and macro/variable token spans in a single left-to-right pass. *