@langwatch/server 3.4.0 → 3.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/langwatch/package.json +1 -1
- package/langwatch/src/server/api-router.ts +2 -0
- package/langwatch/src/server/app-layer/clients/__tests__/clickhouse/cold-scan-detector.unit.test.ts +135 -0
- package/langwatch/src/server/app-layer/clients/clickhouse/cold-scan-detector.ts +89 -0
- package/langwatch/src/server/app-layer/clients/clickhouse/resilient-client.ts +21 -2
- package/langwatch/src/server/app-layer/traces/repositories/__tests__/trace-list.clickhouse.repository.integration.test.ts +253 -0
- package/langwatch/src/server/app-layer/traces/repositories/trace-list.clickhouse.repository.ts +54 -26
- package/langwatch/src/server/ops/__tests__/explain-core.unit.test.ts +259 -0
- package/langwatch/src/server/ops/explain-core.ts +264 -0
- package/langwatch/src/server/routes/__tests__/ops-explain.integration.test.ts +193 -0
- package/langwatch/src/server/routes/ops.ts +162 -0
- package/langwatch/src/server/workflows/runWorkflow.ts +31 -0
- package/package.json +1 -1
- package/packages/server/dist/cli.cjs +1 -1
package/langwatch/package.json
CHANGED
|
@@ -55,6 +55,7 @@ import { app as cronApp } from "./routes/cron";
|
|
|
55
55
|
import { app as evaluationsLegacyApp } from "./routes/evaluations-legacy";
|
|
56
56
|
import { app as healthApp } from "./routes/health";
|
|
57
57
|
import { app as miscApp } from "./routes/misc";
|
|
58
|
+
import { app as opsApp } from "./routes/ops";
|
|
58
59
|
import { app as sseApp } from "./routes/sse";
|
|
59
60
|
import { app as tracesLegacyApp } from "./routes/traces-legacy";
|
|
60
61
|
import { app as trpcApp } from "./routes/trpc";
|
|
@@ -154,6 +155,7 @@ export function createApiRouter() {
|
|
|
154
155
|
api.route("/", evaluationsLegacyApp);
|
|
155
156
|
api.route("/", healthApp);
|
|
156
157
|
api.route("/", miscApp);
|
|
158
|
+
api.route("/", opsApp);
|
|
157
159
|
api.route("/", sseApp);
|
|
158
160
|
api.route("/", tracesLegacyApp);
|
|
159
161
|
api.route("/", trpcApp);
|
package/langwatch/src/server/app-layer/clients/__tests__/clickhouse/cold-scan-detector.unit.test.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
detectColdScan,
|
|
4
|
+
TIME_PARTITIONED_TABLES,
|
|
5
|
+
} from "../../clickhouse/cold-scan-detector";
|
|
6
|
+
|
|
7
|
+
describe("detectColdScan", () => {
|
|
8
|
+
it("flags a stored_spans query with no time predicate", () => {
|
|
9
|
+
const query = `
|
|
10
|
+
SELECT SpanId, TraceId FROM stored_spans
|
|
11
|
+
WHERE TenantId = {tenantId:String} AND TraceId = {traceId:String}
|
|
12
|
+
`;
|
|
13
|
+
expect(detectColdScan(query)).toBe("stored_spans");
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it("clears the flag when the time column is in a WHERE comparison", () => {
|
|
17
|
+
const query = `
|
|
18
|
+
SELECT SpanId FROM stored_spans
|
|
19
|
+
WHERE TenantId = {tenantId:String}
|
|
20
|
+
AND TraceId = {traceId:String}
|
|
21
|
+
AND StartTime >= fromUnixTimestamp64Milli({fromMs:Int64})
|
|
22
|
+
`;
|
|
23
|
+
expect(detectColdScan(query)).toBeNull();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("clears the flag for a reversed comparison ({from} <= StartTime)", () => {
|
|
27
|
+
const query = `
|
|
28
|
+
SELECT SpanId FROM stored_spans
|
|
29
|
+
WHERE TenantId = {tenantId:String}
|
|
30
|
+
AND fromUnixTimestamp64Milli({fromMs:Int64}) <= StartTime
|
|
31
|
+
`;
|
|
32
|
+
expect(detectColdScan(query)).toBeNull();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("clears the flag for BETWEEN and IN predicates", () => {
|
|
36
|
+
expect(
|
|
37
|
+
detectColdScan(
|
|
38
|
+
"SELECT 1 FROM stored_spans WHERE StartTime BETWEEN a AND b",
|
|
39
|
+
),
|
|
40
|
+
).toBeNull();
|
|
41
|
+
expect(
|
|
42
|
+
detectColdScan(
|
|
43
|
+
"SELECT 1 FROM stored_spans WHERE StartTime IN (1, 2, 3)",
|
|
44
|
+
),
|
|
45
|
+
).toBeNull();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("STILL flags when the time column is only in the projection / ORDER BY (the real prod case)", () => {
|
|
49
|
+
// Verified on prod: this shape scans 252/252 partitions because StartTime in
|
|
50
|
+
// SELECT/ORDER BY does not enable partition pruning - only a WHERE does.
|
|
51
|
+
const query = `
|
|
52
|
+
SELECT SpanId, toUnixTimestamp64Milli(StartTime) AS StartTimeMs
|
|
53
|
+
FROM stored_spans
|
|
54
|
+
WHERE TenantId = {tenantId:String} AND TraceId = {traceId:String}
|
|
55
|
+
ORDER BY StartTimeMs ASC
|
|
56
|
+
`;
|
|
57
|
+
expect(detectColdScan(query)).toBe("stored_spans");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("is case-insensitive on table and column names", () => {
|
|
61
|
+
expect(
|
|
62
|
+
detectColdScan("select spanid from STORED_SPANS where tenantid = 'x'"),
|
|
63
|
+
).toBe("stored_spans");
|
|
64
|
+
expect(
|
|
65
|
+
detectColdScan(
|
|
66
|
+
"select spanid from STORED_SPANS where starttime > now() - 1",
|
|
67
|
+
),
|
|
68
|
+
).toBeNull();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("does not match a table whose name is a superstring (word boundary)", () => {
|
|
72
|
+
const query =
|
|
73
|
+
"SELECT * FROM stored_spans_archive WHERE TenantId = {tenantId:String}";
|
|
74
|
+
expect(detectColdScan(query)).toBeNull();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("ignores non-SELECT statements", () => {
|
|
78
|
+
expect(
|
|
79
|
+
detectColdScan("INSERT INTO stored_spans (SpanId) VALUES ('x')"),
|
|
80
|
+
).toBeNull();
|
|
81
|
+
expect(
|
|
82
|
+
detectColdScan("ALTER TABLE stored_spans DELETE WHERE TraceId = 'x'"),
|
|
83
|
+
).toBeNull();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("handles WITH (CTE) queries", () => {
|
|
87
|
+
const query = `
|
|
88
|
+
WITH ids AS (SELECT TraceId FROM other_table)
|
|
89
|
+
SELECT SpanId FROM stored_spans WHERE TraceId IN (SELECT TraceId FROM ids)
|
|
90
|
+
`;
|
|
91
|
+
expect(detectColdScan(query)).toBe("stored_spans");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("does not let a commented-out time predicate clear the flag", () => {
|
|
95
|
+
const lineComment = `
|
|
96
|
+
SELECT SpanId FROM stored_spans
|
|
97
|
+
WHERE TenantId = {tenantId:String}
|
|
98
|
+
-- AND StartTime >= something
|
|
99
|
+
`;
|
|
100
|
+
expect(detectColdScan(lineComment)).toBe("stored_spans");
|
|
101
|
+
|
|
102
|
+
const blockComment = `
|
|
103
|
+
SELECT SpanId FROM stored_spans /* StartTime >= x */
|
|
104
|
+
WHERE TenantId = {tenantId:String}
|
|
105
|
+
`;
|
|
106
|
+
expect(detectColdScan(blockComment)).toBe("stored_spans");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("returns null for tables that are not time-partitioned", () => {
|
|
110
|
+
expect(
|
|
111
|
+
detectColdScan("SELECT * FROM trace_checks WHERE project_id = 'x'"),
|
|
112
|
+
).toBeNull();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("returns null for empty or non-string input", () => {
|
|
116
|
+
expect(detectColdScan("")).toBeNull();
|
|
117
|
+
expect(detectColdScan(undefined as unknown as string)).toBeNull();
|
|
118
|
+
expect(detectColdScan(null as unknown as string)).toBeNull();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("flags every tracked table when its time predicate is missing", () => {
|
|
122
|
+
for (const [table, timeColumns] of Object.entries(TIME_PARTITIONED_TABLES)) {
|
|
123
|
+
const cold = `SELECT 1 FROM ${table} WHERE TenantId = 'x'`;
|
|
124
|
+
expect(detectColdScan(cold)).toBe(table);
|
|
125
|
+
|
|
126
|
+
const warm = `SELECT 1 FROM ${table} WHERE ${timeColumns[0]} > 0`;
|
|
127
|
+
expect(detectColdScan(warm)).toBeNull();
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("flags the exact query captured live from prod (tree columns, no time predicate)", () => {
|
|
132
|
+
const prodQuery = `SELECT SpanId, TraceId, TenantId, ParentSpanId, ParentTraceId, ParentIsRemote, Sampled, toUnixTimestamp64Milli(StartTime) AS StartTimeMs, DurationMs, SpanName FROM stored_spans WHERE (TenantId = 'project_x') AND (TraceId = 'abc') AND ((TenantId, TraceId, SpanId, UpdatedAt) IN (SELECT TenantId, TraceId, SpanId, max(UpdatedAt) FROM stored_spans WHERE (TenantId = 'project_x') AND (TraceId = 'abc') GROUP BY TenantId, TraceId, SpanId)) ORDER BY StartTimeMs ASC LIMIT 512`;
|
|
133
|
+
expect(detectColdScan(prodQuery)).toBe("stored_spans");
|
|
134
|
+
});
|
|
135
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cold-scan detection for ClickHouse SELECTs.
|
|
3
|
+
*
|
|
4
|
+
* Several of our largest tables are partitioned by a time expression and tier
|
|
5
|
+
* old partitions to S3 (see clickhouse-serverless storage policy). A SELECT
|
|
6
|
+
* that filters one of these tables WITHOUT a predicate on its partition time
|
|
7
|
+
* column cannot prune partitions, so ClickHouse walks every weekly/monthly
|
|
8
|
+
* partition including the cold ones on S3. Each such scan turns into a burst of
|
|
9
|
+
* S3 GET requests, which is the dominant driver of our S3 request bill.
|
|
10
|
+
*
|
|
11
|
+
* This module flags those queries so the resilient client can warn on them.
|
|
12
|
+
* It is detection-only: it never changes the query or its behaviour.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Tables partitioned by a time expression, mapped to the column names that, when
|
|
17
|
+
* used in a WHERE/PREWHERE comparison, let ClickHouse prune partitions.
|
|
18
|
+
*
|
|
19
|
+
* Keep in sync with the ClickHouse migrations (PARTITION BY clauses). A table
|
|
20
|
+
* absent from this map is treated as not time-partitioned and never flagged.
|
|
21
|
+
*/
|
|
22
|
+
export const TIME_PARTITIONED_TABLES = {
|
|
23
|
+
stored_spans: ["StartTime"],
|
|
24
|
+
stored_log_records: ["TimeUnixMs"],
|
|
25
|
+
stored_metric_records: ["TimeUnixMs"],
|
|
26
|
+
event_log: ["EventOccurredAt"],
|
|
27
|
+
billable_events: ["EventTimestamp"],
|
|
28
|
+
governance_ocsf_events: ["EventTime"],
|
|
29
|
+
} as const satisfies Record<string, readonly string[]>;
|
|
30
|
+
|
|
31
|
+
/** Strip line and block comments so they can't hide or fake a predicate. */
|
|
32
|
+
function stripComments(sql: string): string {
|
|
33
|
+
return sql
|
|
34
|
+
.replace(/--[^\n]*/g, " ")
|
|
35
|
+
.replace(/\/\*[\s\S]*?\*\//g, " ");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Does the SQL use `column` in a filter comparison (not merely a projection or
|
|
40
|
+
* ORDER BY)? Only a comparison lets ClickHouse derive a partition bound.
|
|
41
|
+
*
|
|
42
|
+
* This is the crux: a query like `SELECT toUnixTimestamp64Milli(StartTime) ...
|
|
43
|
+
* ORDER BY StartTimeMs` references StartTime but still scans every partition
|
|
44
|
+
* (verified on prod: 252/252 parts). A query with `WHERE StartTime >= {from}`
|
|
45
|
+
* prunes (41/255). So we look for the column adjacent to a comparison operator
|
|
46
|
+
* or BETWEEN/IN on either side.
|
|
47
|
+
*/
|
|
48
|
+
function hasTimePredicate(sql: string, column: string): boolean {
|
|
49
|
+
const col = column.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
50
|
+
// column <op> ... (e.g. StartTime >= {from})
|
|
51
|
+
const colThenOp = new RegExp(
|
|
52
|
+
`\\b${col}\\b\\s*(?:>=|<=|<>|!=|=|>|<|\\bBETWEEN\\b|\\bIN\\b)`,
|
|
53
|
+
"i",
|
|
54
|
+
);
|
|
55
|
+
// ... <op> column (e.g. {from} <= StartTime)
|
|
56
|
+
const opThenCol = new RegExp(
|
|
57
|
+
`(?:>=|<=|<>|!=|=|>|<)\\s*\\b${col}\\b`,
|
|
58
|
+
"i",
|
|
59
|
+
);
|
|
60
|
+
return colThenOp.test(sql) || opThenCol.test(sql);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Returns the name of a time-partitioned table that the query reads without any
|
|
65
|
+
* filter predicate on its partition time column, or null if the query is fine
|
|
66
|
+
* (or not a SELECT against a tracked table).
|
|
67
|
+
*
|
|
68
|
+
* Errs toward flagging: a projection or ORDER BY mention of the time column does
|
|
69
|
+
* NOT clear the flag, because those do not enable partition pruning. A false
|
|
70
|
+
* positive is a cheap advisory log line; a false negative misses real S3 cost.
|
|
71
|
+
*/
|
|
72
|
+
export function detectColdScan(query: string): string | null {
|
|
73
|
+
if (typeof query !== "string" || query.length === 0) return null;
|
|
74
|
+
|
|
75
|
+
const sql = stripComments(query);
|
|
76
|
+
const trimmed = sql.trimStart().toUpperCase();
|
|
77
|
+
if (!trimmed.startsWith("SELECT") && !trimmed.startsWith("WITH")) return null;
|
|
78
|
+
|
|
79
|
+
for (const [table, timeColumns] of Object.entries(TIME_PARTITIONED_TABLES)) {
|
|
80
|
+
// Word-boundary match so `stored_spans` doesn't match `stored_spans_v2`.
|
|
81
|
+
const tableRef = new RegExp(`\\b${table}\\b`, "i");
|
|
82
|
+
if (!tableRef.test(sql)) continue;
|
|
83
|
+
|
|
84
|
+
const hasPredicate = timeColumns.some((col) => hasTimePredicate(sql, col));
|
|
85
|
+
if (!hasPredicate) return table;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
incrementClickHouseQueryCount,
|
|
6
6
|
} from "~/server/clickhouse/metrics";
|
|
7
7
|
import { CLICKHOUSE_TRANSIENT_MESSAGE_FRAGMENTS } from "~/server/event-sourcing/services/errorHandling";
|
|
8
|
+
import { detectColdScan } from "./cold-scan-detector";
|
|
8
9
|
|
|
9
10
|
const logger = createLogger("langwatch:clickhouse:resilient");
|
|
10
11
|
const queryLogger = createLogger("langwatch:clickhouse:query");
|
|
@@ -253,6 +254,12 @@ function extractQueryPreview(params: unknown): string | undefined {
|
|
|
253
254
|
return p.query.length > 200 ? p.query.slice(0, 200) + "..." : p.query;
|
|
254
255
|
}
|
|
255
256
|
|
|
257
|
+
function extractRawQuery(params: unknown): string {
|
|
258
|
+
if (!params || typeof params !== "object") return "";
|
|
259
|
+
const p = params as Record<string, unknown>;
|
|
260
|
+
return typeof p.query === "string" ? p.query : "";
|
|
261
|
+
}
|
|
262
|
+
|
|
256
263
|
function logFailure({
|
|
257
264
|
operation,
|
|
258
265
|
error,
|
|
@@ -305,10 +312,20 @@ function logSuccess({
|
|
|
305
312
|
&& readBytes !== undefined
|
|
306
313
|
&& readBytes > expectations.maxReadBytes;
|
|
307
314
|
|
|
308
|
-
|
|
315
|
+
// A SELECT against a time-partitioned table with no predicate on its time
|
|
316
|
+
// column cannot prune partitions, so it walks the whole history including
|
|
317
|
+
// the cold tier on S3 - a burst of S3 GET requests per call. Worth warning
|
|
318
|
+
// even when fast, because the cost is request count, not latency.
|
|
319
|
+
const coldScanTable = operation === "query"
|
|
320
|
+
? detectColdScan(extractRawQuery(params))
|
|
321
|
+
: null;
|
|
322
|
+
const isColdScan = coldScanTable !== null;
|
|
323
|
+
|
|
324
|
+
if (isSlow || isTooHeavy || isColdScan) {
|
|
309
325
|
const reasons: string[] = [];
|
|
310
326
|
if (isSlow) reasons.push(`${roundedMs}ms > ${expectations.maxDurationMs}ms`);
|
|
311
327
|
if (isTooHeavy) reasons.push(`${formatBytes(readBytes!)} > ${formatBytes(expectations.maxReadBytes!)} expected`);
|
|
328
|
+
if (isColdScan) reasons.push(`cold scan of ${coldScanTable} (no time filter, walks S3 partitions)`);
|
|
312
329
|
|
|
313
330
|
queryLogger.warn(
|
|
314
331
|
{
|
|
@@ -322,8 +339,10 @@ function logSuccess({
|
|
|
322
339
|
table: meta.table,
|
|
323
340
|
paramKeys: meta.paramKeys,
|
|
324
341
|
query: extractQueryPreview(params),
|
|
342
|
+
coldScan: isColdScan,
|
|
343
|
+
...(coldScanTable ? { coldScanTable } : {}),
|
|
325
344
|
},
|
|
326
|
-
`ClickHouse slow ${operation}: ${reasons.join(", ")}`
|
|
345
|
+
`ClickHouse ${isColdScan && !isSlow && !isTooHeavy ? "cold-scan" : "slow"} ${operation}: ${reasons.join(", ")}`
|
|
327
346
|
);
|
|
328
347
|
} else {
|
|
329
348
|
queryLogger.debug(
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Integration tests for `TraceListClickHouseRepository.findAll`, exercised
|
|
3
|
+
* against a real ClickHouse testcontainer on the production `trace_summaries`
|
|
4
|
+
* schema.
|
|
5
|
+
*
|
|
6
|
+
* Focus: the trace list must read the heavy `ComputedInput`/`ComputedOutput`
|
|
7
|
+
* payload for at most one page of traces, not for every deduped trace in the
|
|
8
|
+
* window. The window scan over those payloads (plus the `count() OVER ()`
|
|
9
|
+
* buffer) is the dominant read-bytes cost on this list in prod, so the test
|
|
10
|
+
* seeds far more traces than one page and asserts both correctness and a real
|
|
11
|
+
* peak-memory reduction versus the naive single-scan form.
|
|
12
|
+
*/
|
|
13
|
+
import { nanoid } from "nanoid";
|
|
14
|
+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
15
|
+
import type { ClickHouseClient } from "@clickhouse/client";
|
|
16
|
+
import {
|
|
17
|
+
startTestContainers,
|
|
18
|
+
stopTestContainers,
|
|
19
|
+
} from "../../../../event-sourcing/__tests__/integration/testContainers";
|
|
20
|
+
import { TraceListClickHouseRepository } from "../trace-list.clickhouse.repository";
|
|
21
|
+
import type { TraceListQuery } from "../trace-list.repository";
|
|
22
|
+
|
|
23
|
+
const tenantId = `test-trace-list-${nanoid()}`;
|
|
24
|
+
const base = Date.now() - 60 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
const TOTAL_TRACES = 800;
|
|
27
|
+
const PAGE_LIMIT = 200;
|
|
28
|
+
const HEAVY_INPUT = "i".repeat(8000);
|
|
29
|
+
const HEAVY_OUTPUT = "o".repeat(8000); // ~16KB of payload per trace
|
|
30
|
+
|
|
31
|
+
let ch: ClickHouseClient;
|
|
32
|
+
let repo: TraceListClickHouseRepository;
|
|
33
|
+
|
|
34
|
+
function traceIdFor(i: number): string {
|
|
35
|
+
return `tr-${String(i).padStart(4, "0")}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function makeTraceSummaryRow(i: number, overrides: Record<string, unknown> = {}) {
|
|
39
|
+
return {
|
|
40
|
+
ProjectionId: `proj-${nanoid()}`,
|
|
41
|
+
TenantId: tenantId,
|
|
42
|
+
TraceId: traceIdFor(i),
|
|
43
|
+
Version: "v1",
|
|
44
|
+
Attributes: {},
|
|
45
|
+
OccurredAt: new Date(base + i),
|
|
46
|
+
CreatedAt: new Date(base + i),
|
|
47
|
+
UpdatedAt: new Date(base + i),
|
|
48
|
+
ComputedIOSchemaVersion: "v1",
|
|
49
|
+
ComputedInput: `input-${i}-${HEAVY_INPUT}`,
|
|
50
|
+
ComputedOutput: `output-${i}-${HEAVY_OUTPUT}`,
|
|
51
|
+
TimeToFirstTokenMs: null,
|
|
52
|
+
TimeToLastTokenMs: null,
|
|
53
|
+
TotalDurationMs: 100,
|
|
54
|
+
TokensPerSecond: null,
|
|
55
|
+
SpanCount: 1,
|
|
56
|
+
ContainsErrorStatus: false,
|
|
57
|
+
ContainsOKStatus: true,
|
|
58
|
+
ErrorMessage: null,
|
|
59
|
+
Models: [],
|
|
60
|
+
TotalCost: null,
|
|
61
|
+
TokensEstimated: false,
|
|
62
|
+
TotalPromptTokenCount: null,
|
|
63
|
+
TotalCompletionTokenCount: null,
|
|
64
|
+
OutputFromRootSpan: false,
|
|
65
|
+
OutputSpanEndTimeMs: 0,
|
|
66
|
+
BlockedByGuardrail: false,
|
|
67
|
+
TraceName: `trace-${i}`,
|
|
68
|
+
RootSpanType: "",
|
|
69
|
+
ContainsAi: false,
|
|
70
|
+
ContainsPrompt: false,
|
|
71
|
+
AnnotationIds: [],
|
|
72
|
+
LastEventOccurredAt: new Date(base + i),
|
|
73
|
+
TopicId: null,
|
|
74
|
+
SubTopicId: null,
|
|
75
|
+
...overrides,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function insertRows(rows: ReturnType<typeof makeTraceSummaryRow>[]) {
|
|
80
|
+
const chunk = 200;
|
|
81
|
+
for (let i = 0; i < rows.length; i += chunk) {
|
|
82
|
+
await ch.insert({
|
|
83
|
+
table: "trace_summaries",
|
|
84
|
+
values: rows.slice(i, i + chunk),
|
|
85
|
+
format: "JSONEachRow",
|
|
86
|
+
clickhouse_settings: { async_insert: 0, wait_for_async_insert: 0 },
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function baseQuery(): TraceListQuery {
|
|
92
|
+
return {
|
|
93
|
+
tenantId,
|
|
94
|
+
timeRange: { from: base - 60_000, to: base + TOTAL_TRACES + 60_000 },
|
|
95
|
+
sort: { column: "OccurredAt", direction: "desc" },
|
|
96
|
+
limit: PAGE_LIMIT,
|
|
97
|
+
offset: 0,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
beforeAll(async () => {
|
|
102
|
+
const containers = await startTestContainers();
|
|
103
|
+
ch = containers.clickHouseClient;
|
|
104
|
+
repo = new TraceListClickHouseRepository(async () => ch);
|
|
105
|
+
|
|
106
|
+
const rows = Array.from({ length: TOTAL_TRACES }, (_, i) =>
|
|
107
|
+
makeTraceSummaryRow(i),
|
|
108
|
+
);
|
|
109
|
+
await insertRows(rows);
|
|
110
|
+
|
|
111
|
+
// A stale earlier version of the newest trace (same OccurredAt, older
|
|
112
|
+
// UpdatedAt): dedup must return the latest payload, and the count must not
|
|
113
|
+
// double-count it.
|
|
114
|
+
await insertRows([
|
|
115
|
+
makeTraceSummaryRow(TOTAL_TRACES - 1, {
|
|
116
|
+
ComputedInput: "stale-input",
|
|
117
|
+
ComputedOutput: "stale-output",
|
|
118
|
+
UpdatedAt: new Date(base - 10_000),
|
|
119
|
+
CreatedAt: new Date(base - 10_000),
|
|
120
|
+
}),
|
|
121
|
+
]);
|
|
122
|
+
}, 120_000);
|
|
123
|
+
|
|
124
|
+
afterAll(async () => {
|
|
125
|
+
if (ch) {
|
|
126
|
+
await ch.exec({
|
|
127
|
+
query:
|
|
128
|
+
"ALTER TABLE trace_summaries DELETE WHERE TenantId = {tenantId:String}",
|
|
129
|
+
query_params: { tenantId },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
await stopTestContainers();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
describe("TraceListClickHouseRepository.findAll (integration)", () => {
|
|
136
|
+
describe("when the window holds far more traces than one page", () => {
|
|
137
|
+
it("returns one page ordered by the sort column", async () => {
|
|
138
|
+
const page = await repo.findAll(baseQuery());
|
|
139
|
+
|
|
140
|
+
expect(page.rows).toHaveLength(PAGE_LIMIT);
|
|
141
|
+
// OccurredAt DESC → the newest PAGE_LIMIT traces, newest first.
|
|
142
|
+
const expected = Array.from({ length: PAGE_LIMIT }, (_, i) =>
|
|
143
|
+
traceIdFor(TOTAL_TRACES - 1 - i),
|
|
144
|
+
);
|
|
145
|
+
expect(page.rows.map((r) => r.traceId)).toEqual(expected);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("reports the full deduped total, not just the page size", async () => {
|
|
149
|
+
const page = await repo.findAll(baseQuery());
|
|
150
|
+
expect(page.totalHits).toBe(TOTAL_TRACES);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("returns the latest version of a duplicated trace, not the stale one", async () => {
|
|
154
|
+
const page = await repo.findAll(baseQuery());
|
|
155
|
+
const newest = page.rows.find(
|
|
156
|
+
(r) => r.traceId === traceIdFor(TOTAL_TRACES - 1),
|
|
157
|
+
);
|
|
158
|
+
expect(newest).toBeDefined();
|
|
159
|
+
expect(newest?.computedInput).toContain(`input-${TOTAL_TRACES - 1}-`);
|
|
160
|
+
expect(newest?.computedInput).not.toContain("stale");
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("honours offset paging without overlap", async () => {
|
|
164
|
+
const page2 = await repo.findAll({ ...baseQuery(), offset: PAGE_LIMIT });
|
|
165
|
+
const expected = Array.from({ length: PAGE_LIMIT }, (_, i) =>
|
|
166
|
+
traceIdFor(TOTAL_TRACES - 1 - PAGE_LIMIT - i),
|
|
167
|
+
);
|
|
168
|
+
expect(page2.rows.map((r) => r.traceId)).toEqual(expected);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("reads heavy columns for fewer traces than the naive single-scan form", async () => {
|
|
172
|
+
const dedup = `(TenantId, TraceId, UpdatedAt) IN (
|
|
173
|
+
SELECT TenantId, TraceId, max(UpdatedAt)
|
|
174
|
+
FROM trace_summaries
|
|
175
|
+
WHERE TenantId = {tenantId:String}
|
|
176
|
+
AND OccurredAt >= fromUnixTimestamp64Milli({from:Int64})
|
|
177
|
+
GROUP BY TenantId, TraceId
|
|
178
|
+
)`;
|
|
179
|
+
const where = `TenantId = {tenantId:String}
|
|
180
|
+
AND OccurredAt >= fromUnixTimestamp64Milli({from:Int64})`;
|
|
181
|
+
const params = { tenantId, from: base - 60_000, limit: PAGE_LIMIT };
|
|
182
|
+
|
|
183
|
+
const naiveId = `naive-${nanoid()}`;
|
|
184
|
+
const pagedId = `paged-${nanoid()}`;
|
|
185
|
+
|
|
186
|
+
// Naive: heavy payload for every deduped trace + count() OVER () buffer.
|
|
187
|
+
await ch
|
|
188
|
+
.query({
|
|
189
|
+
query: `
|
|
190
|
+
SELECT TraceId, ComputedInput, ComputedOutput,
|
|
191
|
+
count() OVER () AS TotalCount
|
|
192
|
+
FROM trace_summaries
|
|
193
|
+
WHERE ${where} AND ${dedup}
|
|
194
|
+
ORDER BY OccurredAt DESC
|
|
195
|
+
LIMIT {limit:UInt32}
|
|
196
|
+
`,
|
|
197
|
+
query_params: params,
|
|
198
|
+
query_id: naiveId,
|
|
199
|
+
format: "JSONEachRow",
|
|
200
|
+
})
|
|
201
|
+
.then((r) => r.json());
|
|
202
|
+
|
|
203
|
+
// Paged: pick the TraceId page first, read heavy payload for those only.
|
|
204
|
+
await ch
|
|
205
|
+
.query({
|
|
206
|
+
query: `
|
|
207
|
+
SELECT TraceId, ComputedInput, ComputedOutput
|
|
208
|
+
FROM trace_summaries
|
|
209
|
+
WHERE ${where}
|
|
210
|
+
AND TraceId IN (
|
|
211
|
+
SELECT TraceId
|
|
212
|
+
FROM trace_summaries
|
|
213
|
+
WHERE ${where} AND ${dedup}
|
|
214
|
+
ORDER BY OccurredAt DESC
|
|
215
|
+
LIMIT {limit:UInt32}
|
|
216
|
+
)
|
|
217
|
+
AND ${dedup}
|
|
218
|
+
ORDER BY OccurredAt DESC
|
|
219
|
+
LIMIT {limit:UInt32}
|
|
220
|
+
`,
|
|
221
|
+
query_params: params,
|
|
222
|
+
query_id: pagedId,
|
|
223
|
+
format: "JSONEachRow",
|
|
224
|
+
})
|
|
225
|
+
.then((r) => r.json());
|
|
226
|
+
|
|
227
|
+
await ch.exec({ query: "SYSTEM FLUSH LOGS" });
|
|
228
|
+
|
|
229
|
+
const memRows = (await (
|
|
230
|
+
await ch.query({
|
|
231
|
+
query: `
|
|
232
|
+
SELECT query_id, max(memory_usage) AS mem
|
|
233
|
+
FROM system.query_log
|
|
234
|
+
WHERE query_id IN ({naiveId:String}, {pagedId:String})
|
|
235
|
+
AND type = 'QueryFinish'
|
|
236
|
+
GROUP BY query_id
|
|
237
|
+
`,
|
|
238
|
+
query_params: { naiveId, pagedId },
|
|
239
|
+
format: "JSONEachRow",
|
|
240
|
+
})
|
|
241
|
+
).json()) as Array<{ query_id: string; mem: string }>;
|
|
242
|
+
|
|
243
|
+
const memOf = (id: string) =>
|
|
244
|
+
Number(memRows.find((r) => r.query_id === id)?.mem ?? 0);
|
|
245
|
+
const naiveMem = memOf(naiveId);
|
|
246
|
+
const pagedMem = memOf(pagedId);
|
|
247
|
+
|
|
248
|
+
expect(naiveMem).toBeGreaterThan(0);
|
|
249
|
+
expect(pagedMem).toBeGreaterThan(0);
|
|
250
|
+
expect(pagedMem).toBeLessThan(naiveMem);
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
});
|
package/langwatch/src/server/app-layer/traces/repositories/trace-list.clickhouse.repository.ts
CHANGED
|
@@ -25,7 +25,6 @@ interface ClickHouseSummaryRow extends TraceSummaryFieldsBase {
|
|
|
25
25
|
AttrUserId: string;
|
|
26
26
|
AttrOrigin: string;
|
|
27
27
|
LastEventOccurredAt: number;
|
|
28
|
-
TotalCount: number;
|
|
29
28
|
}
|
|
30
29
|
|
|
31
30
|
/**
|
|
@@ -109,15 +108,30 @@ export class TraceListClickHouseRepository implements TraceListRepository {
|
|
|
109
108
|
|
|
110
109
|
const client = await this.resolveClient(query.tenantId);
|
|
111
110
|
|
|
112
|
-
//
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
111
|
+
// Latest-version dedup, shared by the page, the heavy read, and the count.
|
|
112
|
+
const dedupFilter = `(TenantId, TraceId, UpdatedAt) IN (
|
|
113
|
+
SELECT TenantId, TraceId, max(UpdatedAt)
|
|
114
|
+
FROM ${TABLE_NAME}
|
|
115
|
+
WHERE ${whereClause}
|
|
116
|
+
GROUP BY TenantId, TraceId
|
|
117
|
+
)`;
|
|
118
|
+
|
|
119
|
+
// Page the matching TraceIds first (key + sort columns only), then read
|
|
120
|
+
// the heavy columns (ComputedInput/ComputedOutput and the rest) for that
|
|
121
|
+
// bounded page alone. The previous single query materialized those
|
|
122
|
+
// payloads for every deduped trace in the window before ORDER BY ... LIMIT
|
|
123
|
+
// trimmed it, and `count() OVER ()` forced the whole deduped set to buffer
|
|
124
|
+
// — together the dominant read-bytes cost on this list. The total is now a
|
|
125
|
+
// separate light count that never touches the payload columns.
|
|
126
|
+
//
|
|
127
|
+
// The inner subquery keeps WHERE/ORDER BY on raw DateTime columns —
|
|
128
|
+
// aliasing DateTime to millis in the same scope shadows the column and
|
|
129
|
+
// breaks the comparison. It also lists explicit columns (no `SELECT *`) so
|
|
130
|
+
// ClickHouse skips reading the full `Attributes` Map; only five keys flow
|
|
131
|
+
// through to the list mapper (see `mapToTraceListItem`).
|
|
132
|
+
const [result, countResult] = await Promise.all([
|
|
133
|
+
client.query({
|
|
134
|
+
query: `
|
|
121
135
|
SELECT
|
|
122
136
|
TraceId,
|
|
123
137
|
TenantId,
|
|
@@ -161,8 +175,7 @@ export class TraceListClickHouseRepository implements TraceListRepository {
|
|
|
161
175
|
TopicId,
|
|
162
176
|
SubTopicId,
|
|
163
177
|
AnnotationIds,
|
|
164
|
-
toUnixTimestamp64Milli(LastEventOccurredAt) AS LastEventOccurredAt
|
|
165
|
-
TotalCount
|
|
178
|
+
toUnixTimestamp64Milli(LastEventOccurredAt) AS LastEventOccurredAt
|
|
166
179
|
FROM (
|
|
167
180
|
SELECT
|
|
168
181
|
TraceId,
|
|
@@ -207,31 +220,46 @@ export class TraceListClickHouseRepository implements TraceListRepository {
|
|
|
207
220
|
TopicId,
|
|
208
221
|
SubTopicId,
|
|
209
222
|
AnnotationIds,
|
|
210
|
-
LastEventOccurredAt
|
|
211
|
-
count() OVER () AS TotalCount
|
|
223
|
+
LastEventOccurredAt
|
|
212
224
|
FROM ${TABLE_NAME}
|
|
213
225
|
WHERE ${whereClause}
|
|
214
|
-
AND
|
|
215
|
-
SELECT
|
|
226
|
+
AND TraceId IN (
|
|
227
|
+
SELECT TraceId
|
|
216
228
|
FROM ${TABLE_NAME}
|
|
217
229
|
WHERE ${whereClause}
|
|
218
|
-
|
|
230
|
+
AND ${dedupFilter}
|
|
231
|
+
ORDER BY ${sortExpression} ${sortDir}
|
|
232
|
+
LIMIT {limit:UInt32}
|
|
233
|
+
OFFSET {offset:UInt32}
|
|
219
234
|
)
|
|
235
|
+
AND ${dedupFilter}
|
|
220
236
|
ORDER BY ${sortExpression} ${sortDir}
|
|
221
237
|
LIMIT {limit:UInt32}
|
|
222
|
-
OFFSET {offset:UInt32}
|
|
223
238
|
)
|
|
224
239
|
`,
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
240
|
+
query_params: {
|
|
241
|
+
...params,
|
|
242
|
+
limit: query.limit,
|
|
243
|
+
offset: query.offset,
|
|
244
|
+
},
|
|
245
|
+
format: "JSONEachRow",
|
|
246
|
+
}),
|
|
247
|
+
client.query({
|
|
248
|
+
query: `
|
|
249
|
+
SELECT count() AS totalHits
|
|
250
|
+
FROM ${TABLE_NAME}
|
|
251
|
+
WHERE ${whereClause}
|
|
252
|
+
AND ${dedupFilter}
|
|
253
|
+
`,
|
|
254
|
+
query_params: { ...params },
|
|
255
|
+
format: "JSONEachRow",
|
|
256
|
+
}),
|
|
257
|
+
]);
|
|
232
258
|
|
|
233
259
|
const rows = await result.json<ClickHouseSummaryRow>();
|
|
234
|
-
const
|
|
260
|
+
const countRows = await countResult.json<{ totalHits: number | string }>();
|
|
261
|
+
const totalHits =
|
|
262
|
+
countRows.length > 0 ? Number(countRows[0]!.totalHits) : 0;
|
|
235
263
|
|
|
236
264
|
return {
|
|
237
265
|
rows: rows.map((row) => this.toTraceSummaryData(row)),
|