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
10 changes: 10 additions & 0 deletions .changeset/limit-filter-value-reads.md
Original file line number Diff line number Diff line change
@@ -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.
88 changes: 88 additions & 0 deletions packages/common-utils/src/__tests__/metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
144 changes: 94 additions & 50 deletions packages/common-utils/src/core/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -161,6 +164,46 @@ async function* inCompletionOrder<T>(
}
}

/** 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 <T>(task: () => Promise<T>): Promise<T> => {
if (active < max) active++;
// The finishing task hands its slot straight over, so `active` is unchanged.
else await new Promise<void>(resolve => waiting.push(resolve));

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.

🟡 P2 — An aborted read stays in the queue and only settles once some other read frees a slot

In createLimiter, also accept the signal: when it fires, remove the waiter from waiting and reject it right away, instead of calling throwIfAborted only after the task is dequeued. As written, an aborted waiter sits in waiting until an unrelated read finishes. That read may belong to another caller with its own signal, and the limiter is process-wide in the API. So describe_source (packages/api/src/mcp/tools/sources/describeSource.ts:358/407), which awaits getAllKeyValues after its budget aborts, keeps hanging for up to a full read (12–20s per the PR description). The handler outlives its deadline even though no query will be sent.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

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<typeof createLimiter>
>();
const limitTextIndexRead = <T>(
connectionId: string,
signal: AbortSignal | undefined,
task: () => Promise<T>,
): Promise<T> => {
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();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Abort check misses pre-query await

Medium Severity

limitTextIndexRead calls throwIfAborted and then clickhouseClient.query, but the node client only receives abort_signal after processClickhouseSettings awaits getSettings. An abort during that await is ignored, so the read still runs and keeps its limiter slot and proxy socket.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6fff982. Configure here.

};

export type MetricNames = {
names: string[];
/** True when more names matched than `limit`, so the page is incomplete. */
Expand Down Expand Up @@ -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,
}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Queued abort fails shared fetch

Medium Severity

The queued throwIfAborted runs inside the getOrFetch callback, whose cache key does not include signal. An abort rejects that shared pending promise, and the catch resolves it as undefined, so another caller waiting on the same key gets no values even if its own signal is still active.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6fff982. Configure here.

} catch (error) {
// Text-index queries can fail transiently (part merged mid-read,
// unsupported server, etc.). Isolate the failure so sibling
Expand Down Expand Up @@ -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<KeyValues>())
.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<KeyValues>()),
);
return result.data;
} catch (error) {
// See `getMapTextIndexKeyValues` — same isolation rationale.
console.warn(
Expand Down
Loading