Skip to content

Commit 1e95681

Browse files
committed
feat: optimize queries, add missing indeces
1 parent d87876d commit 1e95681

20 files changed

+96
-73
lines changed

apps/web/src/app/(admin)/backoffice/usage-overview/_components/UsageCell/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ export function UsageCell({
66
}: {
77
usageOverview: GetUsageOverviewRow
88
}) {
9-
const lastMonth = usageOverview.lastMonthTraces ?? 0
10-
const prevMonth = usageOverview.lastTwoMonthsTraces ?? 0
9+
const lastMonth = usageOverview.lastMonthRuns ?? 0
10+
const prevMonth = usageOverview.lastTwoMonthsRuns ?? 0
1111

1212
return (
1313
<div className='flex flex-col gap-1'>

apps/web/src/app/(admin)/backoffice/usage-overview/buildUsageInformation.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ function getEmailsList(emails: string | null) {
5454
export function buildUsageInformation(usage: GetUsageOverviewRow) {
5555
const plan = getPlanFromSubscriptionSlug(usage.subscriptionPlan)
5656
const trend = getTrendIndicator({
57-
tracesTwoMonthsAgo: usage.lastTwoMonthsTraces,
58-
tracesLast30Days: usage.lastMonthTraces,
57+
tracesTwoMonthsAgo: usage.lastTwoMonthsRuns,
58+
tracesLast30Days: usage.lastMonthRuns,
5959
plan,
6060
})
6161

apps/web/src/app/(admin)/backoffice/usage-overview/page.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ export default async function AdminPage({
8888
</ServerSideTableCell>
8989
<ServerSideTableCell className='w-40'>
9090
<Text.H6 color='foregroundMuted'>
91-
{usage.latestTraceAt
92-
? formatDistanceToNow(usage.latestTraceAt, {
91+
{usage.latestRunAt
92+
? formatDistanceToNow(usage.latestRunAt, {
9393
addSuffix: true,
9494
})
9595
: '-'}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
ALTER TABLE spans ON CLUSTER default DROP INDEX IF EXISTS idx_test_deployment_id;
2+
ALTER TABLE spans ON CLUSTER default DROP INDEX IF EXISTS idx_parent_id;
3+
ALTER TABLE spans ON CLUSTER default DROP INDEX IF EXISTS idx_experiment_uuid;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
ALTER TABLE spans ON CLUSTER default
2+
ADD INDEX IF NOT EXISTS idx_experiment_uuid experiment_uuid TYPE bloom_filter(0.01) GRANULARITY 1,
3+
ADD INDEX IF NOT EXISTS idx_parent_id parent_id TYPE bloom_filter(0.01) GRANULARITY 1,
4+
ADD INDEX IF NOT EXISTS idx_test_deployment_id test_deployment_id TYPE bloom_filter(0.01) GRANULARITY 1;
5+
6+
ALTER TABLE spans ON CLUSTER default MATERIALIZE INDEX idx_experiment_uuid;
7+
ALTER TABLE spans ON CLUSTER default MATERIALIZE INDEX idx_parent_id;
8+
ALTER TABLE spans ON CLUSTER default MATERIALIZE INDEX idx_test_deployment_id;
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
ALTER TABLE spans DROP INDEX IF EXISTS idx_test_deployment_id;
2+
ALTER TABLE spans DROP INDEX IF EXISTS idx_parent_id;
3+
ALTER TABLE spans DROP INDEX IF EXISTS idx_experiment_uuid;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
ALTER TABLE spans
2+
ADD INDEX IF NOT EXISTS idx_experiment_uuid experiment_uuid TYPE bloom_filter(0.01) GRANULARITY 1,
3+
ADD INDEX IF NOT EXISTS idx_parent_id parent_id TYPE bloom_filter(0.01) GRANULARITY 1,
4+
ADD INDEX IF NOT EXISTS idx_test_deployment_id test_deployment_id TYPE bloom_filter(0.01) GRANULARITY 1;
5+
6+
ALTER TABLE spans MATERIALIZE INDEX idx_experiment_uuid;
7+
ALTER TABLE spans MATERIALIZE INDEX idx_parent_id;
8+
ALTER TABLE spans MATERIALIZE INDEX idx_test_deployment_id;

packages/core/src/queries/clickhouse/spans/computeDocumentTracesAggregations.ts

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,74 +14,73 @@ export async function computeDocumentTracesAggregations({
1414
const params: Record<string, unknown> = {
1515
workspaceId,
1616
documentUuid,
17+
completionType: 'completion',
1718
}
1819

19-
const countConditions = [
20+
const conditions = [
2021
`workspace_id = {workspaceId: UInt64}`,
21-
`document_uuid = {documentUuid: String}`,
22-
]
23-
24-
const aggregationConditions = [
25-
`workspace_id = {workspaceId: UInt64}`,
26-
`document_uuid = {documentUuid: String}`,
27-
`type = 'completion'`,
22+
`document_uuid = {documentUuid: UUID}`,
2823
]
2924

3025
if (commitUuid) {
3126
params.commitUuid = commitUuid
32-
countConditions.push(`commit_uuid = {commitUuid: String}`)
33-
aggregationConditions.push(`commit_uuid = {commitUuid: String}`)
27+
conditions.push(`commit_uuid = {commitUuid: UUID}`)
3428
}
3529

36-
// Query for total count of distinct traces
37-
const countResult = await clickhouseClient().query({
38-
query: `
39-
SELECT count(DISTINCT trace_id) AS total_count
40-
FROM ${SPANS_TABLE}
41-
WHERE ${countConditions.join(' AND ')}
42-
`,
43-
format: 'JSONEachRow',
44-
query_params: params,
45-
})
46-
47-
const countRows = await countResult.json<{ total_count: string }>()
48-
const totalCount = Number(countRows[0]?.total_count ?? 0)
49-
50-
// Query for aggregations with median calculations using quantile(0.5)
30+
// Query all metrics in a single pass
5131
const aggregationResult = await clickhouseClient().query({
5232
query: `
5333
SELECT
34+
countDistinct(trace_id) AS total_count,
5435
coalesce(
55-
sum(
36+
sumIf(
5637
coalesce(tokens_prompt, 0) +
5738
coalesce(tokens_cached, 0) +
5839
coalesce(tokens_reasoning, 0) +
59-
coalesce(tokens_completion, 0)
40+
coalesce(tokens_completion, 0),
41+
type = {completionType: String}
6042
),
6143
0
6244
) AS total_tokens,
63-
coalesce(sum(cost), 0) AS total_cost_in_millicents,
6445
coalesce(
65-
avg(
46+
sumIf(cost, type = {completionType: String}),
47+
0
48+
) AS total_cost_in_millicents,
49+
coalesce(
50+
avgIf(
6651
coalesce(tokens_prompt, 0) +
6752
coalesce(tokens_cached, 0) +
6853
coalesce(tokens_reasoning, 0) +
69-
coalesce(tokens_completion, 0)
54+
coalesce(tokens_completion, 0),
55+
type = {completionType: String}
7056
),
7157
0
7258
) AS average_tokens,
73-
coalesce(avg(cost), 0) AS average_cost_in_millicents,
74-
coalesce(quantile(0.5)(cost), 0) AS median_cost_in_millicents,
75-
coalesce(avg(duration_ms), 0) AS average_duration,
76-
coalesce(quantile(0.5)(duration_ms), 0) AS median_duration
59+
coalesce(
60+
avgIf(cost, type = {completionType: String}),
61+
0
62+
) AS average_cost_in_millicents,
63+
coalesce(
64+
quantileIf(0.5)(cost, type = {completionType: String}),
65+
0
66+
) AS median_cost_in_millicents,
67+
coalesce(
68+
avgIf(duration_ms, type = {completionType: String}),
69+
0
70+
) AS average_duration,
71+
coalesce(
72+
quantileIf(0.5)(duration_ms, type = {completionType: String}),
73+
0
74+
) AS median_duration
7775
FROM ${SPANS_TABLE}
78-
WHERE ${aggregationConditions.join(' AND ')}
76+
WHERE ${conditions.join(' AND ')}
7977
`,
8078
format: 'JSONEachRow',
8179
query_params: params,
8280
})
8381

8482
const aggRows = await aggregationResult.json<{
83+
total_count: string
8584
total_tokens: string
8685
total_cost_in_millicents: string
8786
average_tokens: string
@@ -92,6 +91,7 @@ export async function computeDocumentTracesAggregations({
9291
}>()
9392

9493
const row = aggRows[0] ?? {
94+
total_count: '0',
9595
total_tokens: '0',
9696
total_cost_in_millicents: '0',
9797
average_tokens: '0',
@@ -102,7 +102,7 @@ export async function computeDocumentTracesAggregations({
102102
}
103103

104104
return {
105-
totalCount,
105+
totalCount: Number(row.total_count),
106106
totalTokens: Number(row.total_tokens),
107107
totalCostInMillicents: Number(row.total_cost_in_millicents),
108108
averageTokens: Number(row.average_tokens),

packages/core/src/queries/clickhouse/spans/computeDocumentTracesDailyCount.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ export async function computeDocumentTracesDailyCount({
3030

3131
const conditions = [
3232
`workspace_id = {workspaceId: UInt64}`,
33-
`document_uuid = {documentUuid: String}`,
33+
`document_uuid = {documentUuid: UUID}`,
3434
`started_at >= {startDate: DateTime64(6, 'UTC')}`,
3535
]
3636

3737
if (commitUuid) {
3838
params.commitUuid = commitUuid
39-
conditions.push(`commit_uuid = {commitUuid: String}`)
39+
conditions.push(`commit_uuid = {commitUuid: UUID}`)
4040
}
4141

4242
const result = await clickhouseClient().query({

packages/core/src/queries/clickhouse/spans/countByDocument.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ export async function countDistinctTracesByDocument({
3535
SELECT count(DISTINCT trace_id) AS cnt
3636
FROM ${SPANS_TABLE}
3737
WHERE workspace_id = {workspaceId: UInt64}
38-
AND document_uuid = {documentUuid: String}
39-
AND commit_uuid IN ({commitUuids: Array(String)})
38+
AND document_uuid = {documentUuid: UUID}
39+
AND commit_uuid IN ({commitUuids: Array(UUID)})
4040
${sourceFilter}
4141
`,
4242
format: 'JSONEachRow',

0 commit comments

Comments
 (0)