From 6fff982cb194776cead68ab62df92710c8a59410 Mon Sep 17 00:00:00 2001 From: Jordan Simonovski Date: Fri, 4 Dec 2026 16:27:06 +1100 Subject: [PATCH] fix(common-utils): run at most four filter value reads at once per connection The search filter panel started every text index values batch together, so on a slow service one page load held about ten proxy sockets per Map column for the whole read. Queue the rest, and drop queued reads whose signal aborted. HDX-6272 --- .changeset/limit-filter-value-reads.md | 10 ++ .../src/__tests__/metadata.test.ts | 88 +++++++++++ packages/common-utils/src/core/metadata.ts | 144 ++++++++++++------ 3 files changed, 192 insertions(+), 50 deletions(-) create mode 100644 .changeset/limit-filter-value-reads.md diff --git a/.changeset/limit-filter-value-reads.md b/.changeset/limit-filter-value-reads.md new file mode 100644 index 000000000..5e7f82891 --- /dev/null +++ b/.changeset/limit-filter-value-reads.md @@ -0,0 +1,10 @@ +--- +'@hyperdx/common-utils': patch +'@hyperdx/app': patch +'@hyperdx/api': patch +--- + +fix: run at most four filter value text index reads at once per connection in +each browser tab or API process. The search filter panel used to start every +batch together, so on a slow service one page load held about ten proxy requests +open per Map column. diff --git a/packages/common-utils/src/__tests__/metadata.test.ts b/packages/common-utils/src/__tests__/metadata.test.ts index 4170e9f37..6b922c6c5 100644 --- a/packages/common-utils/src/__tests__/metadata.test.ts +++ b/packages/common-utils/src/__tests__/metadata.test.ts @@ -1860,6 +1860,94 @@ describe('Metadata', () => { expect(sql).toMatch(/\)\) AND Timestamp >= /); }); + it('runs at most four text index values reads at once per connection', async () => { + setupDefaultLogsSchema(); + let inFlight = 0; + let maxInFlight = 0; + let textIndexReads = 0; + const releases: Array<() => void> = []; + (mockClickhouseClient.query as jest.Mock).mockImplementation( + ({ query }: { query: string }) => { + if (!query.includes('mergeTreeTextIndex')) { + return Promise.resolve({ + json: () => Promise.resolve({ data: [] }), + }); + } + textIndexReads++; + maxInFlight = Math.max(maxInFlight, ++inFlight); + return new Promise(resolve => + releases.push(() => { + inFlight--; + resolve({ json: () => Promise.resolve({ data: [] }) }); + }), + ); + }, + ); + + let settled = false; + const done = metadata + .getAllKeyValues({ + ...baseArgs, + // Own connection, so no other test's reads share the limit. + connectionId: 'limit_test_connection', + keyExpressions: Array.from( + { length: 60 }, + (_, i) => `LogAttributes['key${i}']`, + ), + }) + .finally(() => { + settled = true; + }); + while (!settled) { + await new Promise(resolve => setImmediate(resolve)); + releases.splice(0).forEach(release => release()); + } + await done; + + expect(textIndexReads).toBe(6); + expect(maxInFlight).toBe(4); + }); + + it('does not send a queued text index read once its signal has aborted', async () => { + setupDefaultLogsSchema(); + let textIndexReads = 0; + const releases: Array<() => void> = []; + (mockClickhouseClient.query as jest.Mock).mockImplementation( + ({ query }: { query: string }) => { + if (!query.includes('mergeTreeTextIndex')) { + return Promise.resolve({ + json: () => Promise.resolve({ data: [] }), + }); + } + textIndexReads++; + return new Promise(resolve => + releases.push(() => + resolve({ json: () => Promise.resolve({ data: [] }) }), + ), + ); + }, + ); + + const controller = new AbortController(); + const done = metadata.getAllKeyValues({ + ...baseArgs, + connectionId: 'abort_queue_test_connection', + keyExpressions: Array.from( + { length: 60 }, + (_, i) => `LogAttributes['key${i}']`, + ), + signal: controller.signal, + }); + while (textIndexReads < 4) { + await new Promise(resolve => setImmediate(resolve)); + } + controller.abort(); + releases.splice(0).forEach(release => release()); + await done; + + expect(textIndexReads).toBe(4); + }); + it('inlines map text index key prefixes as escaped literals, not params', async () => { setupDefaultLogsSchema(); diff --git a/packages/common-utils/src/core/metadata.ts b/packages/common-utils/src/core/metadata.ts index 2393b5eed..d86dec3aa 100644 --- a/packages/common-utils/src/core/metadata.ts +++ b/packages/common-utils/src/core/metadata.ts @@ -99,6 +99,9 @@ const TEXT_INDEX_KEYS_PER_QUERY = 10; // Smallest dictionary block size that gets one read per key; see // getMapTextIndexKeyValues. const PER_KEY_TEXT_INDEX_MIN_DICTIONARY_BLOCK_SIZE = 2048; +// Text index values reads in flight per connection. Each holds a proxy socket +// for the whole read, which on a slow service is tens of seconds. HDX-6272 +const MAX_CONCURRENT_TEXT_INDEX_READS = 4; /** * The index read could not be scoped to the requested date range, so it was @@ -161,6 +164,46 @@ async function* inCompletionOrder( } } +/** Runs at most `max` tasks at once; the rest start in call order. */ +function createLimiter(max: number) { + let active = 0; + const waiting: Array<() => void> = []; + return async (task: () => Promise): Promise => { + if (active < max) active++; + // The finishing task hands its slot straight over, so `active` is unchanged. + else await new Promise(resolve => waiting.push(resolve)); + try { + return await task(); + } finally { + const next = waiting.shift(); + if (next) next(); + else active--; + } + }; +} + +// Module-level: each hook builds its own Metadata, but they share a connection. +const textIndexReadLimiters = new Map< + string, + ReturnType +>(); +const limitTextIndexRead = ( + connectionId: string, + signal: AbortSignal | undefined, + task: () => Promise, +): Promise => { + let limiter = textIndexReadLimiters.get(connectionId); + if (!limiter) { + limiter = createLimiter(MAX_CONCURRENT_TEXT_INDEX_READS); + textIndexReadLimiters.set(connectionId, limiter); + } + return limiter(() => { + // The node client ignores a signal that aborted before the query starts. + signal?.throwIfAborted(); + return task(); + }); +}; + export type MetricNames = { names: string[]; /** True when more names matched than `limit`, so the page is incomplete. */ @@ -1941,41 +1984,41 @@ export class Metadata { } const sql = concatChSql(' UNION ALL ', sqlBranches); - return await this.clickhouseClient - .query<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - clickhouse_settings: perKey - ? { - ...this.getClickHouseSettings(), - // The per-key LIMIT bounds each read. A row cap would stop - // the sorted dictionary read partway and leave the keys that - // sort after it with no values. - max_rows_to_read: '0', - } - : { - // shortcut: bounds the shared read, but keys that sort after - // a high-cardinality key can come back with no values; drop - // it if that matters more than the read's cost. - max_rows_to_read: String( - this.getClickHouseSettings().max_rows_to_read ?? - DEFAULT_METADATA_MAX_ROWS_TO_READ, - ), - read_overflow_mode: 'break', - ...this.getClickHouseSettings(), - }, - abort_signal: signal, - }) - .then(res => - res.json<{ column: string; key: string; value: string[] }>(), - ) - .then(d => - d.data.map(row => ({ - key: `${row.column}['${row.key}']`, - value: row.value, - })), - ); + const result = await limitTextIndexRead(connectionId, signal, () => + this.clickhouseClient + .query<'JSON'>({ + query: sql.sql, + query_params: sql.params, + connectionId, + clickhouse_settings: perKey + ? { + ...this.getClickHouseSettings(), + // The per-key LIMIT bounds each read. A row cap would stop + // the sorted dictionary read partway and leave the keys that + // sort after it with no values. + max_rows_to_read: '0', + } + : { + // shortcut: bounds the shared read, but keys that sort after + // a high-cardinality key can come back with no values; drop + // it if that matters more than the read's cost. + max_rows_to_read: String( + this.getClickHouseSettings().max_rows_to_read ?? + DEFAULT_METADATA_MAX_ROWS_TO_READ, + ), + read_overflow_mode: 'break', + ...this.getClickHouseSettings(), + }, + abort_signal: signal, + }) + .then(res => + res.json<{ column: string; key: string; value: string[] }>(), + ), + ); + return result.data.map(row => ({ + key: `${row.column}['${row.key}']`, + value: row.value, + })); } catch (error) { // Text-index queries can fail transiently (part merged mid-read, // unsupported server, etc.). Isolate the failure so sibling @@ -2037,21 +2080,22 @@ export class Metadata { } const sql = concatChSql(' UNION ALL ', sqlBranches); - const values = await this.clickhouseClient - .query<'JSON'>({ - query: sql.sql, - query_params: sql.params, - connectionId, - clickhouse_settings: { - ...this.getClickHouseSettings(), - // See getMapTextIndexKeyValues. - max_rows_to_read: '0', - }, - abort_signal: signal, - }) - .then(res => res.json()) - .then(d => d.data); - return values; + const result = await limitTextIndexRead(connectionId, signal, () => + this.clickhouseClient + .query<'JSON'>({ + query: sql.sql, + query_params: sql.params, + connectionId, + clickhouse_settings: { + ...this.getClickHouseSettings(), + // See getMapTextIndexKeyValues. + max_rows_to_read: '0', + }, + abort_signal: signal, + }) + .then(res => res.json()), + ); + return result.data; } catch (error) { // See `getMapTextIndexKeyValues` — same isolation rationale. console.warn(