Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/quiet-sorts-stay.md
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down
35 changes: 35 additions & 0 deletions packages/app/src/utils/__tests__/queryParsers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
6 changes: 6 additions & 0 deletions packages/app/src/utils/queryParsers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createParser } from 'nuqs';
import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils';
import {
DashboardFilterValue,
DashboardFilterValueSchema,
Expand Down Expand Up @@ -119,6 +120,11 @@ export const parseAsSortingStateString = createParser<SortingState[number]>({
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',
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}
});
},
);
77 changes: 77 additions & 0 deletions packages/common-utils/src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
54 changes: 51 additions & 3 deletions packages/common-utils/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
) => {
Expand All @@ -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));
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
};

export const isFirstOrderByAscending = (
Comment thread
pulpdrew marked this conversation as resolved.
Resolved
Expand Down
3 changes: 1 addition & 2 deletions packages/common-utils/src/macros.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -23,7 +23,6 @@ import {
import {
expandTemplate,
expandVariableToken,
findBalancedParens,
hasVariableMacro,
VARIABLE_MACRO_NAMES,
VariableContext,
Expand Down
Loading
Loading