Skip to content
Merged
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
8 changes: 8 additions & 0 deletions .changeset/adhoc-filter-kv-rewrite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hyperdx/common-utils': patch
'@hyperdx/app': patch
---

fix: use the Map KV items index for ad hoc and dashboard filters on Map keys.
These filters render `toString(Map['k']) = 'v'`, which the `has(<items>, ...)`
rewrite previously skipped, so the query decoded the whole Map for every row.
58 changes: 55 additions & 3 deletions packages/common-utils/src/__tests__/renderChartConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import {
timeFilterExpr,
} from '@/core/renderChartConfig';
import { convertToCategoricalChartConfig } from '@/core/utils';
import { adhocConditionsToFilters } from '@/filters';
import { adhocConditionsToFilters, filtersToQuery } from '@/filters';
import {
BuilderChartConfig,
ChartConfigWithOptDateRange,
DisplayType,
Filter,
MetricsDataType,
QuerySettings,
} from '@/types';
Expand Down Expand Up @@ -1964,18 +1965,23 @@ describe('renderChartConfig', () => {
.mockResolvedValue(new Map());
};

const buildConfig = (condition: string): ChartConfigWithOptDateRange => ({
const buildFiltersConfig = (
filters: Filter[],
): ChartConfigWithOptDateRange => ({
connection: 'test-connection',
from: { databaseName: 'default', tableName: 'otel_logs' },
select: [{ aggFn: 'count', valueExpression: '' }],
where: '',
whereLanguage: 'sql',
filters: [{ type: 'sql', condition }],
filters,
timestampValueExpression: 'Timestamp',
dateRange: [new Date('2025-01-01'), new Date('2025-01-02')],
granularity: '1 minute',
});

const buildConfig = (condition: string) =>
buildFiltersConfig([{ type: 'sql', condition }]);

it('rewrites `Map[key] = value` to has() when a KV items column exists', async () => {
stubKvItemsMetadata();
const sql = parameterizedQueryToSql(
Expand Down Expand Up @@ -2096,6 +2102,52 @@ describe('renderChartConfig', () => {
expect(sql).toContain("SeverityText = 'error'");
});

it('rewrites ad hoc filter conditions on a Map key', async () => {
stubKvItemsMetadata();
const sql = parameterizedQueryToSql(
await renderChartConfig(
buildFiltersConfig(
adhocConditionsToFilters([
{ key: "LogAttributes['country']", operator: '=', value: 'US' },
{ key: "LogAttributes['env']", operator: 'IN', value: 'prod' },
{ key: "LogAttributes['env']", operator: 'IN', value: 'dev' },
]),
),
mockMetadata,
querySettings,
),
);
expect(sql).toContain(
"(has(`LogAttributeItems`, concat('country', '=', 'US'))) AND (hasAny(`LogAttributeItems`, array(concat('env', '=', 'prod'), concat('env', '=', 'dev'))))",
);
expect(sql).not.toContain("toString(LogAttributes['");
});

it('rewrites dashboard filter selections on a Map key', async () => {
stubKvItemsMetadata();
const sql = parameterizedQueryToSql(
await renderChartConfig(
buildFiltersConfig(
filtersToQuery(
{
"LogAttributes['env']": {
included: new Set(['prod', 'dev']),
excluded: new Set(),
},
},
{ stringifyKeys: true },
),
),
mockMetadata,
querySettings,
),
);
expect(sql).toContain(
"hasAny(`LogAttributeItems`, array(concat('env', '=', 'prod'), concat('env', '=', 'dev')))",
);
expect(sql).not.toContain("toString(LogAttributes['env'])");
});

const buildWhereConfig = (where: string): ChartConfigWithOptDateRange => ({
connection: 'test-connection',
from: { databaseName: 'default', tableName: 'otel_logs' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,113 @@ describe('rewriteSqlFilterWithKvItems', () => {
});
});

describe('toString() wrapper', () => {
// Ad hoc and dashboard filters render keys as toString(<key>).
it.each([
[
"toString(LogAttributes['k']) = 'v'",
"has(`LogAttributeItems`, concat('k', '=', 'v'))",
],
[
"toString(LogAttributes['k']) IN ('a')",
"has(`LogAttributeItems`, concat('k', '=', 'a'))",
],
[
"toString(LogAttributes['k']) IN ('a', 'b')",
"hasAny(`LogAttributeItems`, array(concat('k', '=', 'a'), concat('k', '=', 'b')))",
],
])('rewrites %s', (condition, expected) => {
expect(rewriteSqlFilterWithKvItems(condition, defaultLookup)).toBe(
expected,
);
});

it('rewrites wrapped and bare subscripts in the same condition', () => {
expect(
rewriteSqlFilterWithKvItems(
"toString(LogAttributes['a']) = 'x' AND LogAttributes['b'] = 'y'",
defaultLookup,
),
).toBe(
"has(`LogAttributeItems`, concat('a', '=', 'x')) AND has(`LogAttributeItems`, concat('b', '=', 'y'))",
);
});

it.each([
["toString(LogAttributes['k']) = ''", 'empty value'],
["toString(LogAttributes['k']) != 'v'", '!='],
["toString(LogAttributes['k']) NOT IN ('a')", 'NOT IN'],
["toString(LogAttributes['k']) LIKE '%v%'", 'LIKE'],
["toString(ServiceName) = 'v'", 'no subscript'],
["toString(OtherMap['k']) = 'v'", 'map not in lookup'],
["toString(LogAttributes['k'], 'UTC') = 'v'", 'two arguments'],
["lower(LogAttributes['k']) = 'v'", 'other function'],
["toString(toString(LogAttributes['k'])) = 'v'", 'nested toString'],
["TOSTRING(LogAttributes['k']) = 'v'", 'wrong case'],
["toStringCutToZero(LogAttributes['k']) = 'v'", 'name prefix match'],
["'v' = toString(LogAttributes['k'])", 'wrapper on the right'],
["toString(LogAttributes['k']) = toString('v')", 'non-literal value'],
["toString(LogAttributes['k']) = 5", 'numeric value'],
["toString(LogAttributes['k']) IN ('a', '')", 'empty IN value'],
["toString(LogAttributes['k']) IN ('a', 5)", 'numeric IN value'],
["toString(LogAttributes['k']['k2']) = 'v'", 'chained subscript'],
["toString(LogAttributes) = 'v'", 'whole map'],
["match(toString(LogAttributes['k']), '^v')", 'regex'],
["NOT match(toString(LogAttributes['k']), '^v')", 'negated regex'],
])('leaves %s untouched (%s)', condition => {
expect(rewriteSqlFilterWithKvItems(condition, defaultLookup)).toBe(
condition,
);
});

it('rewrites only the eligible side of a mixed OR', () => {
expect(
rewriteSqlFilterWithKvItems(
"toString(LogAttributes['a']) = 'x' OR toString(LogAttributes['b']) != 'y'",
defaultLookup,
),
).toBe(
"has(`LogAttributeItems`, concat('a', '=', 'x')) OR toString(LogAttributes['b']) != 'y'",
);
});

it.each([
"(toString(LogAttributes['k']) = 'v')",
"(toString(LogAttributes['k'])) = 'v'",
])('rewrites the parenthesized %s', condition => {
expect(rewriteSqlFilterWithKvItems(condition, defaultLookup)).toBe(
"has(`LogAttributeItems`, concat('k', '=', 'v'))",
);
});

it('keeps escaped quotes in the value as written', () => {
expect(
rewriteSqlFilterWithKvItems(
"toString(LogAttributes['k']) = 'it''s'",
defaultLookup,
),
).toBe("has(`LogAttributeItems`, concat('k', '=', 'it''s'))");
});

it('falls back to an OR chain for IN without hasAny support', () => {
expect(
rewriteSqlFilterWithKvItems(
"toString(LogAttributes['k']) IN ('a', 'b') AND Severity = 'error'",
legacyLookup,
),
).toBe(
"(has(`LogAttributeItems`, concat('k', '=', 'a')) OR has(`LogAttributeItems`, concat('k', '=', 'b'))) AND Severity = 'error'",
);
});

it('returns an unparseable condition verbatim', () => {
const condition = "toString(LogAttributes['k'] = 'v'";
expect(rewriteSqlFilterWithKvItems(condition, defaultLookup)).toBe(
condition,
);
});
});

describe('hasAny fallback (useHasAny: false)', () => {
it("still rewrites Map['key'] = 'value' to has(...)", () => {
const result = rewriteSqlFilterWithKvItems(
Expand Down
21 changes: 20 additions & 1 deletion packages/common-utils/src/core/renderChartConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,25 @@ function kvItemsConcatSql(
return `concat(${keySql}, ${SqlString.format('?', [separator])}, ${valueSql})`;
}

// Ad hoc and dashboard filters wrap keys in toString(). The KV items rewrite
// only applies to maps whose values are strings, where toString() is a no-op,
// so the wrapper can be dropped.
function unwrapToString(
node: SQLParser.ExpressionValue | SQLParser.ExprList,
): SQLParser.ExpressionValue | SQLParser.ExprList {
if (node.type !== 'function' || !('name' in node)) return node;
const nameParts = node.name.name;
const args = node.args?.value;
if (
nameParts.length !== 1 ||
nameParts[0].value !== 'toString' ||
args?.length !== 1
) {
return node;
}
return args[0];
}

export const rewriteSqlFilterWithKvItems = (
condition: string,
textIndexInfoLookup: TextIndexInfoLookup,
Expand All @@ -431,7 +450,7 @@ export const rewriteSqlFilterWithKvItems = (
if (!('operator' in node)) return;
const op = String(node.operator ?? '').toUpperCase();
if (op !== '=' && op !== 'IN') return;
const left = node.left;
const left = node.left && unwrapToString(node.left);
if (
left?.type !== 'column_ref' ||
('column' in left && typeof left.column === 'string')
Expand Down
Loading