From 800a572356f37d95758130d8e21861265950d82a Mon Sep 17 00:00:00 2001 From: Aaron Knudtson <87577305+knudtty@users.noreply.github.com> Date: Tue, 16 Jun 2026 15:05:51 -0400 Subject: [PATCH] fix cast issues --- ...x-parametric-aggregate-cast-distributed.md | 7 + .../src/__tests__/metadata.test.ts | 214 ++++++++++++++++++ packages/common-utils/src/core/metadata.ts | 17 +- 3 files changed, 235 insertions(+), 3 deletions(-) create mode 100644 .changeset/fix-parametric-aggregate-cast-distributed.md diff --git a/.changeset/fix-parametric-aggregate-cast-distributed.md b/.changeset/fix-parametric-aggregate-cast-distributed.md new file mode 100644 index 0000000000..dbf2167c7e --- /dev/null +++ b/.changeset/fix-parametric-aggregate-cast-distributed.md @@ -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 diff --git a/packages/common-utils/src/__tests__/metadata.test.ts b/packages/common-utils/src/__tests__/metadata.test.ts index 2006bf3131..92b2b394d0 100644 --- a/packages/common-utils/src/__tests__/metadata.test.ts +++ b/packages/common-utils/src/__tests__/metadata.test.ts @@ -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)'); + }); + }); +}); diff --git a/packages/common-utils/src/core/metadata.ts b/packages/common-utils/src/core/metadata.ts index 5e80ad7f4a..05ab7b670c 100644 --- a/packages/common-utils/src/core/metadata.ts +++ b/packages/common-utils/src/core/metadata.ts @@ -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(); private pendingQueries = new Map>(); @@ -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` @@ -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 ${limitClause} `;