Skip to content

fix(common-utils): run at most four filter value reads at once per connection - #3901

Merged
jordan-simonovski merged 1 commit into
mainfrom
jordansimonovski/limit-filter-value-reads
Dec 4, 2026
Merged

jordan-simonovski merged 1 commit into
mainfrom
jordansimonovski/limit-filter-value-reads

Conversation

@jordan-simonovski

@jordan-simonovski jordan-simonovski commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The search page filter sidebar now runs at most four text index value reads at once per connection, instead of starting every batch together. On a slow service, one page load used to keep about ten /clickhouse-proxy requests open per Map column for 12-20s each. One user with nine search tabs open pushed every hyperdx-api pod in a prod ReplicaSet over the HyperDXAPI-App-HighSocketHandles alert.

  • Values still stream into the sidebar as each read finishes; the later batches start as earlier ones complete.
  • A read whose abort signal fires while it is queued is dropped without being sent. The node ClickHouse client ignores a signal that aborted before the query started, so without this the MCP describe_source time budget would let queued reads run to completion.
  • The limit is per connection within one browser tab, or within one API process for MCP tools. It does not bound sockets per user across tabs; that would need limiting in the proxy.
  • No breaking changes. No API, schema or stored state is involved.

How to reproduce

Starting point: yarn dev against a ClickHouse service where a log source's LogAttributes Map column has a text index (for example idx_log_attr_items), with enough data that the value reads take a few seconds.

On main:

  1. Open Search for that source, with browser devtools on the Network tab filtered to clickhouse-proxy.
  2. Load the page and watch the filter sidebar requests whose query reads mergeTreeTextIndex: about ten are pending at once per Map column.

On this branch:

  1. Repeat the same steps: at most four of those requests are pending at once, and the sidebar values still fill in.

How to test on Vercel preview

N/A, non-UI change. The sidebar looks the same; only request concurrency changes.

Implementation detail
  • The limiter is module-level and keyed by connectionId because each hook builds its own Metadata instance against the same connection. A per-instance limit would not bound anything.
  • It wraps the query and res.json(), so the slot is held until the response body has been read.
  • It sits inside MetadataCache.getOrFetch, so duplicate requests are still deduped before they queue.
  • Tests cover the limit (60 keys, six reads, at most four in flight) and the dropped queued read after abort. Both fail without the change.
  • Known gap, tracked in HDX-6272: the queue is first in, first out, so "load more" on a facet while the sidebar is still loading waits behind pending batches.

References


Note

Medium Risk
Concurrency change on a hot metadata path that affects proxy socket usage and query timing, but behavior is additive (queue + abort) with no API or schema changes.

Overview
Caps concurrent filter-sidebar text index value reads at four per connectionId (per browser tab or API process), instead of firing every batch at once. A module-level createLimiter queue wraps map- and native-mergeTreeTextIndex reads in getAllKeyValues, holding the slot through query execution and response parsing so proxy sockets aren't piled up on slow services.

Queued reads honor AbortSignal: throwIfAborted() runs when a task dequeues, so aborted requests never hit ClickHouse. Filter values still stream in as reads complete—later batches start when slots free up. Tests assert at most four in-flight reads for 60 keys and that abort after four starts prevents further reads.

Reviewed by Cursor Bugbot for commit 6fff982. Bugbot is set up for automated code reviews on this repo. Configure here.

…nnection

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
@jordan-simonovski
jordan-simonovski requested a review from a team as a code owner December 4, 2026 05:28
@changeset-bot

changeset-bot Bot commented Dec 4, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6fff982

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Patch
@hyperdx/app Patch
@hyperdx/api Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Dec 4, 2026 5:31am UTC
hyperdx-storybook Ready Ready Preview Dec 4, 2026 5:31am UTC

Request Review

@github-actions github-actions Bot added the review/tier-2 Low risk — AI review + quick human skim label Dec 4, 2026
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

🔵 Tier 2 — Low Risk

Small, isolated change with no API route or data model modifications.

Why this tier:

  • Standard feature/fix — introduces new logic or modifies core functionality

Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns.
SLA: Resolve within 4 business hours.

Stats
  • Production files changed: 1
  • Production lines changed: 144 (+ 88 in test files, excluded from tier calculation)
  • Branch: jordansimonovski/limit-filter-value-reads
  • Author: jordan-simonovski

To override this classification, remove the review/tier-2 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 109 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

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

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

2 finding(s): 🔴 0 P0/P1 · 🟡 1 P2 · 🔵 1 P3

1 posted as inline comment(s) on the changed lines. 1 P3 folded at the bottom.

🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/common-utils/src/__tests__/metadata.test.ts:50 — Limit test uses one Metadata instance, so it can't catch a per-instance limiter → Run the reads through two Metadata instances on the same connectionId (for example, two getAllKeyValues calls with different caches), and assert that maxInFlight stays at 4 across both. Also assert that a different connectionId gets its own 4 slots. The PR says the limiter is module-level because each hook builds its own Metadata. A regression that moved the limiter onto the instance would still pass this test, since only one instance and one connection are used.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

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

// 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.

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.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. The concurrency primitive is sound — the correctness reviewer traced createLimiter's slot accounting across success, rejection, synchronous throw, and abort-while-queued interleavings and confirmed active never exceeds max, never drifts negative, and the finally always releases or hands off a slot. Dedup via getOrFetch is preserved. The remaining findings are reliability/scalability trade-offs and test-coverage gaps, none blocking.

🟡 P2 — recommended

  • packages/common-utils/src/core/metadata.ts:186 — The textIndexReadLimiters map is module-global and keyed only by connectionId, so in a shared API/MCP process every user and session resolving to the same connection shares one 4-slot pool, causing cross-user head-of-line blocking, and the map is hidden process-lived state that also bleeds across test runs.
    • Fix: Hold the limiter map on the per-connection MetadataCache instance instead of module scope so its lifecycle and isolation track the owning cache.
    • adversarial, performance, kieran-typescript, maintainability, agent-native
  • packages/common-utils/src/core/metadata.ts:168 — A slot is held for the full read with no bound shorter than the client request_timeout (default 3600000ms), so up to four genuinely stuck reads block every subsequent text-index value read on that connection until that timeout fires.
    • Fix: Set max_execution_time on the two limited queries or wrap the limited task in a wall-clock timeout that releases the slot on the order of the expected tens-of-seconds read.
    • adversarial, reliability
  • packages/common-utils/src/__tests__/metadata.test.ts:1949 — The new limiter lacks a test for slot release when an in-flight read rejects (the reject→handoff path, distinct from the abort path both tests exercise) and for per-connection isolation where two connectionIds each get their own cap of four.
    • Fix: Add a test that rejects an in-flight read while others are queued and asserts the queued reads still start, plus a two-connection test asserting up to eight concurrent reads.
    • testing, correctness, reliability
🔵 P3 nitpicks (6)
  • packages/common-utils/src/core/metadata.ts:2022 — An AbortError from caller cancellation is caught and logged as getMapTextIndexKeyValues failed; skipping this strategy, conflating routine cancellation with real transient failures in logs.
    • Fix: Re-raise or return quietly when signal?.aborted before the console.warn, mirroring the existing handling in getMapKeys.
    • correctness, reliability
  • packages/common-utils/src/core/metadata.ts:104 — MAX_CONCURRENT_TEXT_INDEX_READS is a hardcoded, non-exported constant with no per-deployment override, so fast services cannot raise the cap above four.
    • Fix: Make the cap configurable via env var or connection setting.
    • adversarial, performance
  • packages/common-utils/src/core/metadata.ts:200 — A queued read whose signal has already aborted is not removed from the wait queue until it reaches the front, so abort latency is bounded by the slowest in-flight read rather than firing promptly.
    • Fix: Check the abort signal at enqueue time and settle the waiter immediately on abort.
    • adversarial, correctness, reliability
  • packages/common-utils/src/__tests__/metadata.test.ts:1907 — The assertions hardcode derived numbers (six reads, four in flight) tied to unexported TEXT_INDEX_KEYS_PER_QUERY and MAX_CONCURRENT_TEXT_INDEX_READS, so a tuning change breaks them with a cryptic off-by-N failure.
    • Fix: Export the constants and derive the expectations in-test, or comment the 60/6/4 derivation.
    • testing
  • packages/common-utils/src/core/metadata.ts:167 — The slot-handoff invariant comment sits on the else await wait branch but actually describes the hand-off performed in the finally, and the general-purpose limiter is embedded in a very large module.
    • Fix: Move the comment onto the finally and consider extracting the limiter to a standalone, directly unit-tested util.
    • kieran-typescript, maintainability
  • packages/common-utils/src/__tests__/metadata.test.ts:167 — The documented FIFO "start in call order" guarantee has no test; only the concurrency cap and read count are asserted.
    • Fix: Tag reads with a dispatch index and assert queued reads begin in ascending order.
    • testing

Reviewers (11): correctness, adversarial, performance, reliability, kieran-typescript, testing, maintainability, project-standards, agent-native, learnings-researcher, previous-comments.

Testing gaps:

  • No test exercises a text-index read rejecting mid-flight to prove the slot is handed off (only the resolve and abort-before-start paths are covered).
  • No test proves per-connection limiter independence; current tests use unique connectionIds only to avoid cross-test state bleed.
  • No direct unit test for createLimiter (FIFO order, handoff, degenerate max); it is covered only indirectly through getAllKeyValues.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 498 passed • 1 skipped • 1093s

Status Count
✅ Passed 498
❌ Failed 0
⚠️ Flaky 14
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@jordan-simonovski
jordan-simonovski merged commit 325ae63 into main Dec 4, 2026
36 of 38 checks passed

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 6fff982c Deployed Dec 4, 2026 by vercel[bot]
Preview – hyperdx-storybook — 6fff982c Deployed Dec 4, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-2 Low risk — AI review + quick human skim

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants