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
7 changes: 7 additions & 0 deletions .changeset/clickhouse-version-on-proxy-spans.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/api': patch
---

feat: record the ClickHouse server version on ClickHouse proxy spans, as
`hyperdx.clickhouse_proxy.clickhouse.version`, so query errors and latency can
be compared across ClickHouse upgrades.
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,18 @@ describe('clickhouse-proxy forwarding', () => {
const chunks: Buffer[] = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
const body = Buffer.concat(chunks);
// The proxy's own version lookup, not a forwarded request.
if (body.includes('SELECT version()')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ data: [{ version: '26.10.3.7' }] }));
return;
}
captured.push({
method: req.method,
url: req.url,
headers: req.headers,
body: Buffer.concat(chunks),
body,
});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ data: [] }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import http from 'http';

import { getLoggedInAgent, getServer } from '@/fixtures';
import Connection from '@/models/connection';
import { cachedClickHouseVersion } from '@/utils/clickhouseVersion';
import * as instrumentation from '@/utils/instrumentation';

jest.unmock('http-proxy-middleware');

const UPSTREAM_VERSION = '26.10.3.7';

const TIMEOUT_TRAILER =
'Code: 159. DB::Exception: Timeout exceeded: elapsed 15.0 seconds, maximum: 15. (TIMEOUT_EXCEEDED) (version 25.3.1.1)\n';

Expand Down Expand Up @@ -69,8 +72,15 @@ describe('clickhouse-proxy outcome', () => {
beforeAll(async () => {
await server.start();
upstream = http.createServer((req, res) => {
req.resume();
let body = '';
req.on('data', (chunk: Buffer) => (body += chunk));
req.on('end', () => {
// The proxy's own version lookup, not a scripted query.
if (body.includes('SELECT version()')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ data: [{ version: UPSTREAM_VERSION }] }));
return;
}
const id = new URL(req.url ?? '', 'http://x').searchParams.get(
'query_id',
);
Expand Down Expand Up @@ -137,6 +147,30 @@ describe('clickhouse-proxy outcome', () => {
});
});

it('records the ClickHouse version once it has been read', async () => {
const send = await connect();
await send('ok').expect(200);
const connection = await Connection.findOne({ host: upstreamUrl });
const key = {
id: connection!._id.toString(),
host: upstreamUrl,
username: 'default',
};
for (let i = 0; i < 50 && !cachedClickHouseVersion(key); i++) {
await new Promise(resolve => setTimeout(resolve, 20));
}
recordSpy.mockClear();
setAttributes.mockClear();

await send('ok').expect(200);
await proxyOutcome();
expect(setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
'hyperdx.clickhouse_proxy.clickhouse.version': UPSTREAM_VERSION,
}),
);
});

it('categorises an exception written after a 200', async () => {
const send = await connect();
const res = await send('mid-stream')
Expand Down Expand Up @@ -222,6 +256,11 @@ describe('clickhouse-proxy outcome', () => {
outcome: 'error',
attributes: { error_category: 'upstream_unavailable' },
});
expect(setAttributes).toHaveBeenCalledWith(
expect.objectContaining({
'hyperdx.clickhouse_proxy.clickhouse.version': undefined,
}),
);
});

it('categorises a request the client abandoned', async () => {
Expand Down
58 changes: 58 additions & 0 deletions packages/api/src/utils/clickhouseVersion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {
Metadata,
MetadataCache,
} from '@hyperdx/common-utils/dist/core/metadata';
import type { Connection } from '@hyperdx/common-utils/dist/types';

import { ClickhouseClient } from '@/clickhouse';

// Short, because the point is to see a server change version after an upgrade.
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


type VersionedConnection = Pick<
Connection,
'id' | 'host' | 'username' | 'password'
>;

// '' marks a failed read, so an unreachable server is not asked on every request.
async function readVersion(connection: VersionedConnection): Promise<string> {
let client: ClickhouseClient | undefined;
try {
client = new ClickhouseClient({
host: connection.host,
username: connection.username,
password: connection.password,
requestTimeout: VERSION_TIMEOUT_MS,
});
const version = await new Metadata(
client,
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

return '';
} finally {
void client?.close();
}
}

/**
* The connection's ClickHouse version if it is cached, starting a lookup
* otherwise so a later call has it. Never waits on ClickHouse.
*/
export function cachedClickHouseVersion(
connection: VersionedConnection,
): string | undefined {
// Keyed on the host as well, so editing a connection's host drops the answer.
const key = `${connection.id}|${connection.host}`;
const version = versionCache.get<string>(key);
if (version === undefined) {
void versionCache.getOrFetch(key, () => readVersion(connection), {
ttlMs: VERSION_TTL_MS,
});
}
return version || undefined;
}
11 changes: 10 additions & 1 deletion packages/api/src/utils/proxyOutcome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { ClientRequest, IncomingMessage, ServerResponse } from 'http';
import { performance } from 'perf_hooks';

import { isClickHouseError } from '@/utils/clickhouseErrors';
import { cachedClickHouseVersion } from '@/utils/clickhouseVersion';
import {
getServerSpan,
recordOperationOutcome,
Expand Down Expand Up @@ -131,6 +132,7 @@ type ProxyState = {
startedAt: number;
headersAt?: number;
span?: Span;
connection?: Parameters<typeof cachedClickHouseVersion>[0];
timedOut: boolean;
upstreamCut: boolean;
transportError?: { code?: string; message: string };
Expand All @@ -150,10 +152,15 @@ const states = new WeakMap<ServerResponse, ProxyState>();
* response closes, from listeners prepended so they run before the HTTP
* instrumentation ends the server span.
*/
export const trackProxyOutcome: RequestHandler = (_req, res, next) => {
export const trackProxyOutcome: RequestHandler = (req, res, next) => {
const connection = req._hdx_connection;
// Starts the version lookup now so it is usually cached by the time the
// response closes.
if (connection) cachedClickHouseVersion(connection);
const state: ProxyState = {
startedAt: performance.now(),
span: getServerSpan(),
connection,
timedOut: false,
upstreamCut: false,
done: false,
Expand Down Expand Up @@ -252,6 +259,8 @@ function finishProxyOutcome(res: ServerResponse, state: ProxyState) {
state.span?.setAttributes({
'hyperdx.clickhouse_proxy.error.category': category,
'hyperdx.clickhouse_proxy.upstream.status_code': state.upstreamStatus,
'hyperdx.clickhouse_proxy.clickhouse.version':
state.connection && cachedClickHouseVersion(state.connection),
'hyperdx.clickhouse_proxy.clickhouse.error_code': clickhouseErrorCode,
'hyperdx.clickhouse_proxy.clickhouse.error_type': exception?.type,
'hyperdx.clickhouse_proxy.error.message': category
Expand Down
Loading