Skip to content

feat(api): record ClickHouse version on proxy spans - #3843

Merged
jordan-simonovski merged 2 commits into
mainfrom
jordansimonovski/clickhouse-version-on-proxy-spans
Nov 27, 2026
Merged

jordan-simonovski merged 2 commits into
mainfrom
jordansimonovski/clickhouse-version-on-proxy-spans

Conversation

@jordan-simonovski

@jordan-simonovski jordan-simonovski commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

/clickhouse-proxy server spans now carry the ClickHouse server version as hyperdx.clickhouse_proxy.clickhouse.version, so query errors and latency can be grouped by version before and after a ClickHouse upgrade in Cloud. Until now no API or app span recorded the ClickHouse version.

Key decisions

  • The version comes from Metadata.getServerVersion, cached per connection (and host) for 60 seconds. The lookup starts when a proxied request arrives and the cached value is read when the response closes, so a query never waits on it. A failed lookup leaves the attribute off for a minute instead of being retried on every request.
  • It is a span attribute only, not an attribute on the clickhouse_proxy.query SLI metric, following agent_docs/observability.md: versions vary across customers, which suits spans better than metric series.
  • Only the proxy path is covered. Alert and MCP queries go through other clients and can follow if this proves useful.

Breaking changes

None. This adds a span attribute and changes no responses.

Other impact

  • Each API pod runs one SELECT version() per active connection per minute, and only while that connection is receiving proxied requests. It shows up in the customer's system.query_log under an hdx-api- query id.
  • That lookup has no log_comment, because shouldSkipApplySettings skips the settings step that adds query attribution. This already affects every getServerVersion and getSettings call and needs its own fix.
  • On a service with several replicas, the attribute is the version of the replica that answered the lookup. During a rolling upgrade that may differ from the replica that served the query, and the value can be up to a minute old.

How to reproduce

Starting point: yarn dev (needs the API).

On this branch:

  1. Run a search so the app queries ClickHouse through /clickhouse-proxy.
  2. Run a second search.
  3. Find the API's POST /clickhouse-proxy/* server span for the second search and confirm hyperdx.clickhouse_proxy.clickhouse.version matches SELECT version().
Implementation detail
  • utils/clickhouseVersion.ts keeps the cache. Client construction sits inside the try, so a bad host returns no version instead of an unhandled rejection.
  • trackProxyOutcome starts the lookup and finishProxyOutcome reads it, next to the other hyperdx.clickhouse_proxy.* attributes.
  • The fake upstreams in both proxy integration tests answer SELECT version(), and the forwarding test leaves the lookup out of what it captured. New assertions: the version appears once it has been read, and is absent when the upstream refuses the connection. make dev-int FILE=clickhouseProxy passes (25 tests).

Note

Low Risk
Observability-only span attribute with async, non-blocking version lookup; no API response or auth changes.

Overview
Adds hyperdx.clickhouse_proxy.clickhouse.version to /clickhouse-proxy server spans so query outcomes and latency can be segmented by ClickHouse release (e.g. around upgrades).

A new cachedClickHouseVersion helper runs SELECT version() via Metadata.getServerVersion, caches it per connection and host for 60 seconds, and never blocks the proxied query: lookup starts when trackProxyOutcome sees req._hdx_connection, and the cached value is applied when the response closes in finishProxyOutcome. Failed lookups are cached as empty for the TTL so unreachable servers are not hammered.

Integration tests stub upstream SELECT version() responses, exclude that traffic from forwarding captures, and assert the version attribute is set after cache warm-up and omitted when the upstream cannot be reached.

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

Adds hyperdx.clickhouse_proxy.clickhouse.version to /clickhouse-proxy
server spans, so query errors and latency can be compared across
ClickHouse upgrades. The version comes from a per-connection
SELECT version() cached for a minute, started when a request arrives
and read when it closes, so it never delays a query.
@jordan-simonovski
jordan-simonovski requested a review from a team as a code owner November 27, 2026 01:23
@vercel

vercel Bot commented Nov 27, 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 Nov 27, 2026 2:54pm UTC
hyperdx-storybook Ready Ready Preview Nov 27, 2026 2:54pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c752d96

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

This PR includes changesets to release 3 packages
Name Type
@hyperdx/api Patch
@hyperdx/app 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

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

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: 2
  • Production lines changed: 69 (+ 50 in test files, excluded from tier calculation)
  • Branch: jordansimonovski/clickhouse-version-on-proxy-spans
  • 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

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 108 in total (1.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

const VERSION_TTL_MS = 60_000;
const VERSION_TIMEOUT_MS = 5_000;

const versionCache = new MetadataCache();

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 — Module-level version cache never evicts entries for connections that stop being used

MetadataCache (packages/common-utils/src/core/metadata.ts:331) only deletes an expired entry when get() is called again with the same key. Every ${id}|${host} pair ever proxied therefore stays in versionCache for the life of the pod, including deleted connections and every old host left behind by an edit (the key includes the host on purpose). On a long-lived multi-tenant API pod this grows without bound. Fix: use a bounded LRU/TTL map, or sweep expired entries when a new one is written.

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

new MetadataCache(),
).getServerVersion({ connectionId: connection.id });
return version?.join('.') ?? '';
} catch {

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 — Recorded version is the parsed and padded tuple, not what SELECT version() returns

getServerVersion returns parseClickHouseVersion(...) (packages/common-utils/src/core/clickhouseVersion.ts:13), and that function keeps only four numeric parts and pads missing ones with 0. So 24.8.14.10459.altinitystable gets recorded as 24.8.14.10459, and 26.4 as 26.4.0.0. That contradicts the PR's own check that the attribute matches SELECT version(), and it merges vendor builds together. Fix: run SELECT version() directly in readVersion and store the raw string.

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

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 · 🟡 2 P2 · 🔵 0 P3

2 posted as inline comment(s) on the changed lines.


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.

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 477 passed • 1 skipped • 1112s

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

Tests ran across 4 shards in parallel.

View full report →

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. The feature is correctly non-blocking: cachedClickHouseVersion reads the cache synchronously and floats the fetch, readVersion and getServerVersion both swallow their own errors, and the process-global unhandledRejection handler only logs — so a slow or unreachable ClickHouse can never delay, fail, or crash a proxied request. Cross-tenant cache isolation holds (connection.id is a globally-unique Mongo _id), and the version string is bounded by parseClickHouseVersion before it becomes a span attribute. The findings below are a missing test for the headline behavior plus minor polish.

🟡 P2 — recommended

  • packages/api/src/utils/clickhouseVersion.ts:52 — the central design guarantee — a failed read caches '' so an unreachable server is not re-queried on every request within the TTL — has no test; the new integration tests only cover cached-success and not-yet-read-undefined.
    • Fix: Add a test that issues two requests against an unreachable host and asserts SELECT version() reaches the upstream at most once within the TTL window, then retries after expiry.
    • testing, correctness, reliability, performance, adversarial, project-standards
🔵 P3 nitpicks (7)
  • packages/api/src/utils/clickhouseVersion.ts:38 — void client?.close() floats a promise outside the surrounding try/catch, so a rejecting socket teardown would surface as an unhandled rejection (no constructible reject path in the current client, so latent).
    • Fix: Use void client?.close().catch(() => {}).
    • correctness, reliability, kieran-typescript
  • packages/api/src/utils/clickhouseVersion.ts:53 — if readVersion never settles (a hung socket that defeats the request timeout), the pendingQueries entry for the key is never cleared, permanently suppressing re-fetch for that connection and leaking the client; the request path stays safe.
    • Fix: Race readVersion against an internal deadline so the fetch always settles and close() always runs, letting the key retry after TTL.
    • reliability, adversarial
  • packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts:261 — expect.objectContaining({ '...version': undefined }) also matches when the key is absent, so the assertion passes even if the attribute were never set.
    • Fix: Assert against the actual setAttributes call args to prove the key is present with value undefined.
    • testing
  • packages/api/src/routers/api/__tests__/clickhouseProxyOutcome.int.test.ts:159 — the 50×20ms poll loop exits silently if the lookup exceeds 1s, making a slow fetch fail later as a confusing missing-attribute error.
    • Fix: Assert cachedClickHouseVersion(key) resolved to the expected version before clearing the spies.
    • testing
  • packages/api/src/utils/proxyOutcome.ts:135 — ProxyState.connection is typed via Parameters<typeof cachedClickHouseVersion>[0], forcing a reader to resolve the function signature to learn the shape.
    • Fix: Export VersionedConnection from clickhouseVersion.ts and reference it directly.
    • maintainability, kieran-typescript
  • packages/api/src/utils/clickhouseVersion.ts:32 — new Metadata(client, new MetadataCache()) passes a throwaway cache that is populated then discarded, reading as dead code since the module-level versionCache is the real cache.
    • Fix: Add a one-line comment that the inner cache is intentionally discarded.
  • packages/api/src/utils/clickhouseVersion.ts:57 — the tri-state value (undefined = not fetched, '' = failed, 'x.y.z' = real) is distinguished by === undefined and || undefined on one variable, which is subtle to follow and fragile to edit.
    • Fix: Name the sentinel (e.g. const FAILED_READ = '') and comment why || is used rather than ??.

Reviewers (10): correctness, testing, maintainability, project-standards, reliability, performance, security, adversarial, kieran-typescript, previous-comments.

Testing gaps:

  • Failed/unreachable read caches '' and is not re-queried within the TTL (the headline guarantee) — untested.
  • Host-keyed invalidation ("editing a connection's host drops the answer") — untested.
  • state.connection falsy branch (request with no _hdx_connection) resolving the attribute to undefined — untested.
  • No direct unit test of clickhouseVersion.ts; the version?.join('.') ?? '' empty-version fallback is never exercised.

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

@jordan-simonovski
jordan-simonovski merged commit f874e34 into main Nov 27, 2026
29 of 30 checks passed

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — c752d961 Deployed Nov 27, 2026 by vercel[bot]
Preview – hyperdx-storybook — c752d961 Deployed Nov 27, 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