-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathrunsReplicationBenchmark.test.ts
More file actions
571 lines (504 loc) · 17.7 KB
/
Copy pathrunsReplicationBenchmark.test.ts
File metadata and controls
571 lines (504 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import { ClickHouse } from "@internal/clickhouse";
import { replicationContainerTest } from "@internal/testcontainers";
import { fork, type ChildProcess } from "node:child_process";
import { performance, PerformanceObserver } from "node:perf_hooks";
import { setTimeout } from "node:timers/promises";
import path from "node:path";
import { z } from "zod";
import { RunsReplicationService } from "~/services/runsReplicationService.server";
import { createInMemoryTracing, createInMemoryMetrics } from "./utils/tracing";
import { TestReplicationClickhouseFactory } from "./utils/testReplicationClickhouseFactory";
// Extend test timeout for benchmarks
vi.setConfig({ testTimeout: 300_000 }); // 5 minutes
/**
* Benchmark configuration
*/
const BENCHMARK_CONFIG = {
// Number of runs to create - adjust this to test different volumes
// Start with smaller numbers (1000) for quick tests, increase to 10000+ for realistic benchmarks
NUM_RUNS: parseInt(process.env.BENCHMARK_NUM_RUNS || "5000", 10),
// Error rate (7% = realistic production load with some failures)
ERROR_RATE: 0.07,
// Batch size for producer
PRODUCER_BATCH_SIZE: 100,
// Replication service settings
FLUSH_BATCH_SIZE: 50,
FLUSH_INTERVAL_MS: 100,
MAX_FLUSH_CONCURRENCY: 4,
// How long to wait for replication to complete (in ms)
REPLICATION_TIMEOUT_MS: 120_000, // 2 minutes
};
interface BenchmarkResult {
name: string;
fingerprintingEnabled: boolean;
producerStats: {
created: number;
withErrors: number;
duration: number;
throughput: number;
};
replicationStats: {
duration: number;
throughput: number;
replicatedRuns: number;
};
eluStats: {
mean: number;
p50: number;
p95: number;
p99: number;
samples: number[];
};
metricsStats: {
batchesFlushed: number;
taskRunsInserted: number;
payloadsInserted: number;
eventsProcessed: number;
};
}
/**
* Measure Event Loop Utilization during benchmark
*/
class ELUMonitor {
private samples: number[] = [];
private interval: NodeJS.Timeout | null = null;
private startELU: { idle: number; active: number } | null = null;
start(intervalMs: number = 100) {
this.samples = [];
this.startELU = performance.eventLoopUtilization();
this.interval = setInterval(() => {
const elu = performance.eventLoopUtilization();
const utilization = elu.utilization * 100; // Convert to percentage
this.samples.push(utilization);
}, intervalMs);
}
stop(): { mean: number; p50: number; p95: number; p99: number; samples: number[] } {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
if (this.samples.length === 0) {
return { mean: 0, p50: 0, p95: 0, p99: 0, samples: [] };
}
const sorted = [...this.samples].sort((a, b) => a - b);
const mean = sorted.reduce((sum, val) => sum + val, 0) / sorted.length;
const p50 = sorted[Math.floor(sorted.length * 0.5)];
const p95 = sorted[Math.floor(sorted.length * 0.95)];
const p99 = sorted[Math.floor(sorted.length * 0.99)];
return { mean, p50, p95, p99, samples: sorted };
}
}
/**
* Run the producer script in a separate process
*/
async function runProducer(config: {
postgresUrl: string;
organizationId: string;
projectId: string;
environmentId: string;
numRuns: number;
errorRate: number;
batchSize: number;
}): Promise<{ created: number; withErrors: number; duration: number; throughput: number }> {
return new Promise((resolve, reject) => {
const producerPath = path.join(__dirname, "runsReplicationBenchmark.producer.ts");
// Use tsx to run the TypeScript file directly
const child = fork(producerPath, [JSON.stringify(config)], {
stdio: ["ignore", "pipe", "pipe", "ipc"],
execArgv: ["-r", "tsx/cjs"],
});
let output = "";
child.stdout?.on("data", (data) => {
const text = data.toString();
output += text;
console.log(text.trim());
});
child.stderr?.on("data", (data) => {
console.error(data.toString().trim());
});
child.on("message", (message: any) => {
if (message.type === "complete") {
resolve(message.stats);
} else if (message.type === "error") {
reject(new Error(message.error));
}
});
child.on("error", (error) => {
reject(error);
});
child.on("exit", (code) => {
if (code !== 0) {
reject(new Error(`Producer exited with code ${code}`));
}
});
});
}
/**
* Wait for all runs to be replicated to ClickHouse
*/
async function waitForReplication(
clickhouse: ClickHouse,
organizationId: string,
expectedCount: number,
timeoutMs: number
): Promise<{ duration: number; replicatedRuns: number }> {
const startTime = performance.now();
const deadline = startTime + timeoutMs;
const queryRuns = clickhouse.reader.query({
name: "benchmark-count",
query:
"SELECT count(*) as count FROM trigger_dev.task_runs_v2 WHERE organization_id = {org_id:String}",
schema: z.object({ count: z.number() }),
params: z.object({ org_id: z.string() }),
});
while (performance.now() < deadline) {
const [error, result] = await queryRuns({ org_id: organizationId });
if (error) {
throw new Error(`Failed to query ClickHouse: ${error.message}`);
}
const count = result?.[0]?.count || 0;
if (count >= expectedCount) {
const duration = performance.now() - startTime;
return { duration, replicatedRuns: count };
}
// Wait a bit before checking again
await setTimeout(500);
}
throw new Error(
`Replication timeout: expected ${expectedCount} runs, but only found ${await getRunCount(
clickhouse
)} after ${timeoutMs}ms`
);
}
async function getRunCount(clickhouse: ClickHouse): Promise<number> {
const queryRuns = clickhouse.reader.query({
name: "benchmark-count",
query: "SELECT count(*) as count FROM trigger_dev.task_runs_v2",
schema: z.object({ count: z.number() }),
});
const [error, result] = await queryRuns({});
if (error) return 0;
return result?.[0]?.count || 0;
}
/**
* Extract metrics from OpenTelemetry metrics
*/
function extractMetrics(metrics: any[]): {
batchesFlushed: number;
taskRunsInserted: number;
payloadsInserted: number;
eventsProcessed: number;
} {
function getMetricData(name: string) {
for (const resourceMetrics of metrics) {
for (const scopeMetrics of resourceMetrics.scopeMetrics) {
for (const metric of scopeMetrics.metrics) {
if (metric.descriptor.name === name) {
return metric;
}
}
}
}
return null;
}
function sumCounterValues(metric: any): number {
if (!metric?.dataPoints) return 0;
return metric.dataPoints.reduce((sum: number, dp: any) => sum + (dp.value || 0), 0);
}
return {
batchesFlushed: sumCounterValues(getMetricData("runs_replication.batches_flushed")),
taskRunsInserted: sumCounterValues(getMetricData("runs_replication.task_runs_inserted")),
payloadsInserted: sumCounterValues(getMetricData("runs_replication.payloads_inserted")),
eventsProcessed: sumCounterValues(getMetricData("runs_replication.events_processed")),
};
}
/**
* Run a single benchmark test
*/
async function runBenchmark(
name: string,
fingerprintingEnabled: boolean,
{
clickhouseContainer,
redisOptions,
postgresContainer,
prisma,
}: {
clickhouseContainer: any;
redisOptions: any;
postgresContainer: any;
prisma: any;
}
): Promise<BenchmarkResult> {
console.log(`\n${"=".repeat(80)}`);
console.log(`BENCHMARK: ${name}`);
console.log(`Error Fingerprinting: ${fingerprintingEnabled ? "ENABLED" : "DISABLED"}`);
console.log(
`Runs: ${BENCHMARK_CONFIG.NUM_RUNS}, Error Rate: ${(BENCHMARK_CONFIG.ERROR_RATE * 100).toFixed(
1
)}%`
);
console.log(`${"=".repeat(80)}\n`);
// Setup
const organization = await prisma.organization.create({
data: {
title: `benchmark-${name}`,
slug: `benchmark-${name}`,
},
});
const project = await prisma.project.create({
data: {
name: `benchmark-${name}`,
slug: `benchmark-${name}`,
organizationId: organization.id,
externalRef: `benchmark-${name}`,
},
});
const runtimeEnvironment = await prisma.runtimeEnvironment.create({
data: {
slug: `benchmark-${name}`,
type: "DEVELOPMENT",
projectId: project.id,
organizationId: organization.id,
apiKey: `benchmark-${name}`,
pkApiKey: `benchmark-${name}`,
shortcode: `benchmark-${name}`,
},
});
// Setup ClickHouse
const clickhouse = new ClickHouse({
url: clickhouseContainer.getConnectionUrl(),
name: `benchmark-${name}`,
compression: {
request: true,
},
logLevel: "warn",
});
// Setup tracing and metrics
const { tracer } = createInMemoryTracing();
const metricsHelper = createInMemoryMetrics();
// Create and start replication service
const runsReplicationService = new RunsReplicationService({
clickhouseFactory: new TestReplicationClickhouseFactory(clickhouse),
pgConnectionUrl: postgresContainer.getConnectionUri(),
serviceName: `benchmark-${name}`,
slotName: `benchmark_${name.replace(/-/g, "_")}`,
publicationName: `benchmark_${name.replace(/-/g, "_")}_pub`,
redisOptions,
maxFlushConcurrency: BENCHMARK_CONFIG.MAX_FLUSH_CONCURRENCY,
flushIntervalMs: BENCHMARK_CONFIG.FLUSH_INTERVAL_MS,
flushBatchSize: BENCHMARK_CONFIG.FLUSH_BATCH_SIZE,
leaderLockTimeoutMs: 10000,
leaderLockExtendIntervalMs: 2000,
ackIntervalSeconds: 10,
tracer,
meter: metricsHelper.meter,
logLevel: "warn",
disableErrorFingerprinting: !fingerprintingEnabled,
});
await runsReplicationService.start();
// Start ELU monitoring
const eluMonitor = new ELUMonitor();
eluMonitor.start(100);
let producerStats!: BenchmarkResult["producerStats"];
let replicationResult!: { duration: number; replicatedRuns: number };
let metricsStats!: BenchmarkResult["metricsStats"];
let eluStats!: BenchmarkResult["eluStats"];
try {
// Run producer in separate process
console.log("\n[Benchmark] Starting producer...");
producerStats = await runProducer({
postgresUrl: postgresContainer.getConnectionUri(),
organizationId: organization.id,
projectId: project.id,
environmentId: runtimeEnvironment.id,
numRuns: BENCHMARK_CONFIG.NUM_RUNS,
errorRate: BENCHMARK_CONFIG.ERROR_RATE,
batchSize: BENCHMARK_CONFIG.PRODUCER_BATCH_SIZE,
});
console.log("\n[Benchmark] Waiting for replication to complete...");
replicationResult = await waitForReplication(
clickhouse,
organization.id,
producerStats.created,
BENCHMARK_CONFIG.REPLICATION_TIMEOUT_MS
);
const metrics = await metricsHelper.getMetrics();
metricsStats = extractMetrics(metrics);
} finally {
eluStats = eluMonitor.stop();
await runsReplicationService.stop();
await metricsHelper.shutdown();
}
const throughput = (replicationResult.replicatedRuns / replicationResult.duration) * 1000;
const result: BenchmarkResult = {
name,
fingerprintingEnabled,
producerStats,
replicationStats: {
duration: replicationResult.duration,
throughput,
replicatedRuns: replicationResult.replicatedRuns,
},
eluStats,
metricsStats,
};
// Print results
console.log(`\n${"=".repeat(80)}`);
console.log(`RESULTS: ${name}`);
console.log(`${"=".repeat(80)}`);
console.log("\nProducer:");
console.log(` Created: ${producerStats.created} runs`);
console.log(
` With errors: ${producerStats.withErrors} (${(
(producerStats.withErrors / producerStats.created) *
100
).toFixed(1)}%)`
);
console.log(` Duration: ${producerStats.duration.toFixed(0)}ms`);
console.log(` Throughput: ${producerStats.throughput.toFixed(0)} runs/sec`);
console.log("\nReplication:");
console.log(` Replicated: ${replicationResult.replicatedRuns} runs`);
console.log(` Duration: ${replicationResult.duration.toFixed(0)}ms`);
console.log(` Throughput: ${throughput.toFixed(0)} runs/sec`);
console.log("\nEvent Loop Utilization:");
console.log(` Mean: ${eluStats.mean.toFixed(2)}%`);
console.log(` P50: ${eluStats.p50.toFixed(2)}%`);
console.log(` P95: ${eluStats.p95.toFixed(2)}%`);
console.log(` P99: ${eluStats.p99.toFixed(2)}%`);
console.log(` Samples: ${eluStats.samples.length}`);
console.log("\nMetrics:");
console.log(` Batches flushed: ${metricsStats.batchesFlushed}`);
console.log(` Task runs inserted: ${metricsStats.taskRunsInserted}`);
console.log(` Payloads inserted: ${metricsStats.payloadsInserted}`);
console.log(` Events processed: ${metricsStats.eventsProcessed}`);
console.log(`${"=".repeat(80)}\n`);
return result;
}
/**
* Compare two benchmark results and print delta
*/
function compareBenchmarks(baseline: BenchmarkResult, comparison: BenchmarkResult) {
console.log(`\n${"=".repeat(80)}`);
console.log("COMPARISON");
console.log(
`Baseline: ${baseline.name} (fingerprinting ${baseline.fingerprintingEnabled ? "ON" : "OFF"})`
);
console.log(
`Comparison: ${comparison.name} (fingerprinting ${
comparison.fingerprintingEnabled ? "ON" : "OFF"
})`
);
console.log(`${"=".repeat(80)}`);
const replicationDurationDelta =
((comparison.replicationStats.duration - baseline.replicationStats.duration) /
baseline.replicationStats.duration) *
100;
const throughputDelta =
((comparison.replicationStats.throughput - baseline.replicationStats.throughput) /
baseline.replicationStats.throughput) *
100;
const eluMeanDelta =
((comparison.eluStats.mean - baseline.eluStats.mean) / baseline.eluStats.mean) * 100;
const eluP99Delta =
((comparison.eluStats.p99 - baseline.eluStats.p99) / baseline.eluStats.p99) * 100;
console.log("\nReplication Duration:");
console.log(
` ${baseline.replicationStats.duration.toFixed(
0
)}ms → ${comparison.replicationStats.duration.toFixed(0)}ms (${
replicationDurationDelta > 0 ? "+" : ""
}${replicationDurationDelta.toFixed(2)}%)`
);
console.log("\nThroughput:");
console.log(
` ${baseline.replicationStats.throughput.toFixed(
0
)} → ${comparison.replicationStats.throughput.toFixed(0)} runs/sec (${
throughputDelta > 0 ? "+" : ""
}${throughputDelta.toFixed(2)}%)`
);
console.log("\nEvent Loop Utilization (Mean):");
console.log(
` ${baseline.eluStats.mean.toFixed(2)}% → ${comparison.eluStats.mean.toFixed(2)}% (${
eluMeanDelta > 0 ? "+" : ""
}${eluMeanDelta.toFixed(2)}%)`
);
console.log("\nEvent Loop Utilization (P99):");
console.log(
` ${baseline.eluStats.p99.toFixed(2)}% → ${comparison.eluStats.p99.toFixed(2)}% (${
eluP99Delta > 0 ? "+" : ""
}${eluP99Delta.toFixed(2)}%)`
);
console.log(`\n${"=".repeat(80)}\n`);
// Return deltas for assertions if needed
return {
replicationDurationDelta,
throughputDelta,
eluMeanDelta,
eluP99Delta,
};
}
describe("RunsReplicationService Benchmark", () => {
replicationContainerTest.skipIf(process.env.BENCHMARKS_ENABLED !== "1")(
"should benchmark error fingerprinting performance impact",
async ({ clickhouseContainer, redisOptions, postgresContainer, prisma }) => {
// Enable replica identity for TaskRun table
await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`);
console.log("\n" + "=".repeat(80));
console.log("RUNS REPLICATION SERVICE - ERROR FINGERPRINTING BENCHMARK");
console.log("=".repeat(80));
console.log(`Configuration:`);
console.log(` Total runs: ${BENCHMARK_CONFIG.NUM_RUNS}`);
console.log(` Error rate: ${(BENCHMARK_CONFIG.ERROR_RATE * 100).toFixed(1)}%`);
console.log(
` Expected errors: ~${Math.floor(BENCHMARK_CONFIG.NUM_RUNS * BENCHMARK_CONFIG.ERROR_RATE)}`
);
console.log(` Producer batch size: ${BENCHMARK_CONFIG.PRODUCER_BATCH_SIZE}`);
console.log(` Replication batch size: ${BENCHMARK_CONFIG.FLUSH_BATCH_SIZE}`);
console.log(` Max flush concurrency: ${BENCHMARK_CONFIG.MAX_FLUSH_CONCURRENCY}`);
console.log("=".repeat(80) + "\n");
// Run benchmark WITHOUT error fingerprinting (baseline)
const baselineResult = await runBenchmark("baseline-no-fingerprinting", false, {
clickhouseContainer,
redisOptions,
postgresContainer,
prisma,
});
// Run benchmark WITH error fingerprinting
const fingerprintingResult = await runBenchmark("with-fingerprinting", true, {
clickhouseContainer,
redisOptions,
postgresContainer,
prisma,
});
// Compare results
const deltas = compareBenchmarks(baselineResult, fingerprintingResult);
// Basic assertions - just to ensure benchmarks completed successfully
expect(baselineResult.replicationStats.replicatedRuns).toBe(BENCHMARK_CONFIG.NUM_RUNS);
expect(fingerprintingResult.replicationStats.replicatedRuns).toBe(BENCHMARK_CONFIG.NUM_RUNS);
// Log final summary
console.log("BENCHMARK COMPLETE");
console.log(
`Fingerprinting impact on replication duration: ${
deltas.replicationDurationDelta > 0 ? "+" : ""
}${deltas.replicationDurationDelta.toFixed(2)}%`
);
console.log(
`Fingerprinting impact on throughput: ${
deltas.throughputDelta > 0 ? "+" : ""
}${deltas.throughputDelta.toFixed(2)}%`
);
console.log(
`Fingerprinting impact on ELU (mean): ${
deltas.eluMeanDelta > 0 ? "+" : ""
}${deltas.eluMeanDelta.toFixed(2)}%`
);
console.log(
`Fingerprinting impact on ELU (P99): ${
deltas.eluP99Delta > 0 ? "+" : ""
}${deltas.eluP99Delta.toFixed(2)}%`
);
}
);
});