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
7 changes: 7 additions & 0 deletions .changeset/fix-parametric-aggregate-cast-distributed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/common-utils': patch
'@hyperdx/api': patch
'@hyperdx/app': patch
---

fix: inline parametric aggregate function arguments instead of passing as query parameters
214 changes: 214 additions & 0 deletions packages/common-utils/src/__tests__/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1549,3 +1549,217 @@ describe('parseKeyPath', () => {
]);
});
});

describe('parametric aggregate arguments are inlined as literals', () => {
const buildMetadata = () => {
const realCache = new (
jest.requireActual('../core/metadata') as any
).MetadataCache();
return new Metadata(mockClickhouseClient, realCache);
};

beforeEach(() => {
(mockClickhouseClient.query as jest.Mock).mockReset();
});

it('emits groupUniqArray(N)(Value) with a literal N — not a CAST-wrapped query parameter', async () => {
const md = buildMetadata();

(mockClickhouseClient.query as jest.Mock).mockResolvedValueOnce({
json: () => Promise.resolve({ data: [] }),
});

await md.getAllFieldsAndValues({
databaseName: 'default',
tableName: 'otel_logs',
connectionId: 'conn-1',
metadataMVs: {
keyRollupTable: 'otel_logs_key_rollup_15m',
kvRollupTable: 'otel_logs_kv_rollup_15m',
granularity: '15 minute',
},
dateRange: [
new Date('2026-05-11T16:00:00Z'),
new Date('2026-05-11T17:00:00Z'),
],
maxValuesPerKey: 20,
});

const call = (mockClickhouseClient.query as jest.Mock).mock.calls[0][0];
expect(call.query).toContain('groupUniqArray(20)(Value)');
expect(call.query).not.toMatch(
/groupUniqArray\(\{[^}]+:Int32\}\)\(Value\)/,
);
expect(Object.values(call.query_params)).not.toContain(20);
});

it('emits groupUniqArrayArray(N)(keys) with a literal N in the sampledKeys query', async () => {
const md = buildMetadata();

(mockClickhouseClient.query as jest.Mock)
.mockResolvedValueOnce({
json: () =>
Promise.resolve({
data: [
{
name: 'LogAttributes',
type: 'Map(String, String)',
default_type: '',
default_expression: '',
comment: '',
codec_expression: '',
ttl_expression: '',
},
],
}),
})
.mockResolvedValueOnce({
json: () => Promise.resolve({ data: [{ keysArr: [] }] }),
});

await md.getMapKeys({
databaseName: 'otel',
tableName: 'generic_logs',
column: 'LogAttributes',
connectionId: 'conn-1',
maxKeys: 500,
});

const sampledKeysCall = (mockClickhouseClient.query as jest.Mock).mock
.calls[1][0];
expect(sampledKeysCall.query).toContain('groupUniqArrayArray(500)(keys)');
expect(sampledKeysCall.query).not.toMatch(
/groupUniqArrayArray\(\{[^}]+:Int32\}\)\(keys\)/,
);
});

describe('rejects bad values supplied for the parametric aggregate N argument', () => {
const badValues: Array<[string, unknown]> = [
['null', null],
['string', '20'],
['NaN', Number.NaN],
['object', {}],
['boolean', true],
['negative integer', -1],
['float', 1.5],
['Infinity', Number.POSITIVE_INFINITY],
];

it.each(badValues)(
'getAllFieldsAndValues throws when maxValuesPerKey is %s and never queries ClickHouse',
async (_label, badValue) => {
const md = buildMetadata();

await expect(
md.getAllFieldsAndValues({
databaseName: 'default',
tableName: 'otel_logs',
connectionId: 'conn-1',
metadataMVs: {
keyRollupTable: 'otel_logs_key_rollup_15m',
kvRollupTable: 'otel_logs_kv_rollup_15m',
granularity: '15 minute',
},
dateRange: [
new Date('2026-05-11T16:00:00Z'),
new Date('2026-05-11T17:00:00Z'),
],
maxValuesPerKey: badValue as number,
}),
).rejects.toThrow(/maxValuesPerKey must be a non-negative integer/);

expect(mockClickhouseClient.query).not.toHaveBeenCalled();
},
);

it.each(badValues)(
'getMapKeys throws when maxKeys is %s and never runs the sampledKeys query',
async (_label, badValue) => {
const md = buildMetadata();

(mockClickhouseClient.query as jest.Mock).mockResolvedValueOnce({
json: () =>
Promise.resolve({
data: [
{
name: 'LogAttributes',
type: 'Map(String, String)',
default_type: '',
default_expression: '',
comment: '',
codec_expression: '',
ttl_expression: '',
},
],
}),
});

await expect(
md.getMapKeys({
databaseName: 'otel',
tableName: 'generic_logs',
column: 'LogAttributes',
connectionId: 'conn-1',
maxKeys: badValue as number,
}),
).rejects.toThrow(/maxKeys must be a non-negative integer/);

expect(mockClickhouseClient.query).toHaveBeenCalledTimes(1);
const onlyCall = (mockClickhouseClient.query as jest.Mock).mock
.calls[0][0];
expect(onlyCall.query).not.toContain('groupUniqArrayArray');
},
);

it('error message includes the offending value for easy debugging', async () => {
const md = buildMetadata();

await expect(
md.getAllFieldsAndValues({
databaseName: 'default',
tableName: 'otel_logs',
connectionId: 'conn-1',
metadataMVs: {
keyRollupTable: 'otel_logs_key_rollup_15m',
kvRollupTable: 'otel_logs_kv_rollup_15m',
granularity: '15 minute',
},
dateRange: [
new Date('2026-05-11T16:00:00Z'),
new Date('2026-05-11T17:00:00Z'),
],
maxValuesPerKey: 'oops' as unknown as number,
}),
).rejects.toThrow('got: oops');
});

it('accepts the valid boundary case maxValuesPerKey=0 (degenerate but well-formed)', async () => {
const md = buildMetadata();

(mockClickhouseClient.query as jest.Mock).mockResolvedValueOnce({
json: () => Promise.resolve({ data: [] }),
});

await expect(
md.getAllFieldsAndValues({
databaseName: 'default',
tableName: 'otel_logs',
connectionId: 'conn-1',
metadataMVs: {
keyRollupTable: 'otel_logs_key_rollup_15m',
kvRollupTable: 'otel_logs_kv_rollup_15m',
granularity: '15 minute',
},
dateRange: [
new Date('2026-05-11T16:00:00Z'),
new Date('2026-05-11T17:00:00Z'),
],
maxValuesPerKey: 0,
}),
).resolves.toEqual([]);

const call = (mockClickhouseClient.query as jest.Mock).mock.calls[0][0];
expect(call.query).toContain('groupUniqArray(0)(Value)');
});
});
});
17 changes: 14 additions & 3 deletions packages/common-utils/src/core/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ import {
export const DEFAULT_METADATA_MAX_ROWS_TO_READ = 3e6;
const DEFAULT_MAX_KEYS = 1000;

// See https://github.com/hyperdxio/hyperdx/issues/2163. Inlining a validated
// integer literal avoids the `_CAST` wrapper entirely.
const inlineNonNegativeInt = (value: number, label: string): string => {
if (!Number.isInteger(value) || value < 0) {
throw new Error(
`${label} must be a non-negative integer, got: ${String(value)}`,
);
}
return String(value);
};

export class MetadataCache {
private cache = new Map<string, any>();
private pendingQueries = new Map<string, Promise<any>>();
Expand Down Expand Up @@ -490,7 +501,7 @@ export class Metadata {
: DEFAULT_METADATA_MAX_ROWS_TO_READ,
}}
)
SELECT groupUniqArrayArray(${{ Int32: maxKeys }})(keys) as keysArr
SELECT groupUniqArrayArray(${{ UNSAFE_RAW_SQL: inlineNonNegativeInt(maxKeys, 'maxKeys') }})(keys) as keysArr
FROM sampledKeys`;
} else {
sql = chSql`
Expand Down Expand Up @@ -1588,12 +1599,12 @@ export class Metadata {
? chSql`LIMIT ${{ Int32: maxKeys }}`
: chSql``;
const sql = chSql`
SELECT ColumnIdentifier, Key, groupUniqArray(${{ Int32: maxValuesPerKey }})(Value) AS Values
SELECT ColumnIdentifier, Key, groupUniqArray(${{ UNSAFE_RAW_SQL: inlineNonNegativeInt(maxValuesPerKey, 'maxValuesPerKey') }})(Value) AS Values
FROM ${tableExpr({ database: databaseName, table: metadataMVs.kvRollupTable })}
WHERE Value != ''
AND ${timeFilter}
GROUP BY ColumnIdentifier, Key
ORDER BY ColumnIdentifier = 'NativeColumn' DESC, ColumnIdentifier, Key
ORDER BY ColumnIdentifier = 'NativeColumn' DESC, ColumnIdentifier = 'ResourceAttributes' DESC, ColumnIdentifier, Key
Comment thread
knudtty marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this change just to surface ResourceAttributes before other columns before hitting the limit?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's not super related to the other changes here but one I keep noticing

${limitClause}
`;

Expand Down
Loading