Repository navigation
feat: attribute ClickHouse queries to the surface that issued them #3155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
72004c5
feat: attribute ClickHouse queries to the surface that issued them
tommyzli e9edf8a
fix: cover the query paths attribution missed, and harden the payload
tommyzli 7f658d4
fix lint
tommyzli ec8fb79
Update packages/common-utils/src/clickhouse/__tests__/attribution.tes…
tommyzli eed1f77
review and fixes
tommyzli 938edd9
reviews
tommyzli a49d8c9
next round of reviews
tommyzli 4942c9a
trace
tommyzli bf4b141
more
tommyzli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| --- | ||
| '@hyperdx/common-utils': minor | ||
| '@hyperdx/api': minor | ||
| '@hyperdx/app': minor | ||
| --- | ||
|
|
||
| feat: attribute ClickHouse queries to the dashboard, tile, search or alert that | ||
| issued them | ||
|
|
||
| A row in `system.query_log` previously couldn't be attributed to the part of | ||
| HyperDX that produced it. Now every query HyperDX runs has a small JSON | ||
| `log_comment`, plus a `query_id` starting with `hdx-`. | ||
|
|
||
| Attribute load after the fact: | ||
|
|
||
| ```sql | ||
| SELECT | ||
| JSONExtractString(log_comment, 'surface') AS surface, | ||
| JSONExtractString(log_comment, 'dashboard') AS dashboard, | ||
| JSONExtractString(log_comment, 'tile') AS tile, | ||
| count(), | ||
| sum(read_rows) | ||
| FROM system.query_log | ||
| WHERE type = 'QueryFinish' AND log_comment != '' AND query_id like 'hdx-%' | ||
| GROUP BY ALL | ||
| ORDER BY sum(read_rows) DESC | ||
| ``` | ||
|
|
||
| Or spot a query while it is still running, in `system.processes`, where the | ||
| `query_id` names the surface with no JSON parsing needed. | ||
|
|
||
| The payload records which part of the product asked (a dashboard, a search, an | ||
| alert, an MCP tool, the chart explorer, session replay, field lookups, and so | ||
| on), the dashboard and tile or saved search id, the source id, and on the server | ||
| the trace id of the request. Field lookups and autocomplete are labelled too, so | ||
| they can be told apart from a user's chart queries. | ||
|
|
||
| The exception is queries that skip settings processing: the `system.settings`, | ||
| server version and Cloud-detection probes, and the onboarding connection check. | ||
| They get a `query_id` but an empty `log_comment`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
packages/api/src/middleware/__tests__/queryAttribution.int.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import * as config from '@/config'; | ||
| import { | ||
| DEFAULT_DATABASE, | ||
| dropTimeSeriesTable, | ||
| getLoggedInAgent, | ||
| getServer, | ||
| getTestFixtureClickHouseClient, | ||
| seedTimeSeriesTagsTable, | ||
| } from '@/fixtures'; | ||
| import Connection from '@/models/connection'; | ||
|
|
||
| // Covers the wiring the unit tests can't: auth middleware opens the | ||
| // AsyncLocalStorage scope, and a query issued deep inside the route handler | ||
| // still reads it. If that scope is lost, queries fall back to hdx-unknown-*. | ||
| describe('request query attribution', () => { | ||
| const server = getServer(); | ||
| // Unique per run so query_log rows from earlier runs can't match. | ||
| const TABLE = `query_attribution_${Date.now()}`; | ||
|
|
||
| beforeAll(async () => { | ||
| await server.start(); | ||
| await seedTimeSeriesTagsTable({ | ||
| table: TABLE, | ||
| series: [ | ||
| { | ||
| metricName: 'attribution_metric', | ||
| tags: { job: 'api' }, | ||
| startSec: 1700000000, | ||
| endSec: 1700003600, | ||
| }, | ||
| ], | ||
| }); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await server.clearDBs(); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await dropTimeSeriesTable({ table: TABLE }); | ||
| await server.stop(); | ||
| }); | ||
|
|
||
| // query_log is written asynchronously, so flush and poll. | ||
| async function findRouteQueries() { | ||
| const client = await getTestFixtureClickHouseClient(); | ||
| for (let attempt = 0; attempt < 10; attempt++) { | ||
| await client.command({ query: 'SYSTEM FLUSH LOGS' }); | ||
| const result = await client.query({ | ||
| query: ` | ||
| SELECT query_id, log_comment | ||
| FROM system.query_log | ||
| WHERE type = 'QueryFinish' | ||
| AND query_kind = 'Select' | ||
| AND position(query, {table:String}) > 0`, | ||
| // Match on the text: timeSeriesTags() reads an inner table, so | ||
| // `tables` lists `.inner_id.tags.<uuid>`, not TABLE. | ||
| query_params: { table: TABLE }, | ||
| format: 'JSON', | ||
| }); | ||
| const { data }: { data: { query_id: string; log_comment: string }[] } = | ||
| await result.json(); | ||
| if (data.length > 0) return data; | ||
| await new Promise(resolve => setTimeout(resolve, 250)); | ||
| } | ||
| return []; | ||
| } | ||
|
|
||
| it('tags queries from an authenticated route with the api surface', async () => { | ||
| const { agent, team } = await getLoggedInAgent(server); | ||
| const conn = await Connection.create({ | ||
| team: team._id, | ||
| name: 'CH', | ||
| host: config.CLICKHOUSE_HOST, | ||
| username: config.CLICKHOUSE_USER, | ||
| password: config.CLICKHOUSE_PASSWORD, | ||
| }); | ||
|
|
||
| await agent | ||
| .get('/v1/prometheus/labels') | ||
| .query({ | ||
| connectionId: conn._id.toString(), | ||
| database: DEFAULT_DATABASE, | ||
| table: TABLE, | ||
| }) | ||
| .expect(200); | ||
|
|
||
| const logged = await findRouteQueries(); | ||
| expect(logged.length).toBeGreaterThan(0); | ||
| for (const row of logged) { | ||
| expect(row.query_id).toMatch(/^hdx-api-/); | ||
| expect(JSON.parse(row.log_comment)).toMatchObject({ | ||
| surface: 'api', | ||
| label: '/v1/prometheus', | ||
| }); | ||
| } | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.