forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.ts
More file actions
456 lines (396 loc) · 12.2 KB
/
Copy pathrunner.ts
File metadata and controls
456 lines (396 loc) · 12.2 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
/**
* Eval parallel test runner with tier support.
*
* Unlike the existing CLI runner (which runs probe drivers in-process), this
* runner spawns EXTERNAL processes (`showcase test <slug> --d5`) because each
* integration's Playwright suite is separate. Results are collected from the
* Playwright JSON reporter output on stdout.
*
* Tiers allow prioritized execution: Gold Standard integrations run first
* with fail-fast semantics, then Key Partners, then the Full Matrix.
*/
import { execFile } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { SlugResult, TestResult } from "./matrix.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export type { SlugResult } from "./matrix.js";
export interface TierConfig {
name: string;
slugs: string[] | "*";
fail_fast: boolean;
}
export interface TiersFile {
tiers: TierConfig[];
}
export interface RunOptions {
level: string;
maxParallel: number;
timeout: number;
showcaseDir: string;
maxTier?: number;
noFailFast?: boolean;
onSlugStart?: (slug: string, tier: string) => void;
onSlugComplete?: (result: SlugResult, tier: string) => void;
}
export interface TieredRunResult {
results: SlugResult[];
abortedAtTier?: number;
tierSummaries: Array<{
name: string;
total: number;
passed: number;
failed: number;
duration_ms: number;
}>;
}
// ---------------------------------------------------------------------------
// Resolved tier (slugs always string[] after resolution)
// ---------------------------------------------------------------------------
interface ResolvedTier {
name: string;
slugs: string[];
fail_fast: boolean;
}
// ---------------------------------------------------------------------------
// loadTiers
// ---------------------------------------------------------------------------
/**
* Load tier configuration from a JSON file. Resolves the "*" wildcard by
* filtering out slugs already named in previous tiers.
*
* If the file doesn't exist, returns a single "all" tier containing every slug.
*/
export function loadTiers(
tiersPath: string,
allSlugs: string[],
): ResolvedTier[] {
let tiersFile: TiersFile;
try {
const raw = fs.readFileSync(tiersPath, "utf-8");
tiersFile = JSON.parse(raw) as TiersFile;
} catch (err: unknown) {
if (
err instanceof Error &&
"code" in err &&
(err as NodeJS.ErrnoException).code === "ENOENT"
) {
return [{ name: "all", slugs: [...allSlugs], fail_fast: false }];
}
throw err;
}
const claimedSlugs = new Set<string>();
const resolved: ResolvedTier[] = [];
for (const tier of tiersFile.tiers) {
let slugs: string[];
if (tier.slugs === "*") {
// Wildcard: all slugs not already claimed by previous tiers
slugs = allSlugs.filter((s) => !claimedSlugs.has(s));
} else {
slugs = tier.slugs.filter((s) => allSlugs.includes(s));
}
for (const s of slugs) {
claimedSlugs.add(s);
}
resolved.push({
name: tier.name,
slugs,
fail_fast: tier.fail_fast,
});
}
return resolved;
}
// ---------------------------------------------------------------------------
// runSlug
// ---------------------------------------------------------------------------
/**
* Spawn `npx tsx harness/src/cli.ts test <slug> --level <level>` with
* Playwright JSON reporter injected via `--reporter=list,json` and
* `PLAYWRIGHT_JSON_OUTPUT_NAME`. Reads the JSON file after exit for
* per-test granularity; falls back to stdout, then to exit-code.
*/
export async function runSlug(
slug: string,
level: string,
timeout: number,
showcaseDir: string,
): Promise<SlugResult> {
const startMs = Date.now();
const jsonOutputPath = path.join(
os.tmpdir(),
`eval-${slug}-${Date.now()}.json`,
);
return new Promise<SlugResult>((resolve) => {
const args = [
"tsx",
"harness/src/cli.ts",
"test",
slug,
"--level",
level,
"--",
"--reporter=list,json",
];
execFile(
"npx",
args,
{
cwd: showcaseDir,
timeout,
maxBuffer: 10 * 1024 * 1024,
encoding: "utf-8",
env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_NAME: jsonOutputPath },
},
(err: Error | null, stdout: string, _stderr: string) => {
const durationMs = Date.now() - startMs;
let fileJson: string | null = null;
try {
fileJson = fs.readFileSync(jsonOutputPath, "utf-8");
fs.unlinkSync(jsonOutputPath);
} catch {
// File doesn't exist — Playwright didn't write it
}
const exitedWithError = !!err;
const parsed =
tryParsePlaywrightJson(fileJson) ?? tryParsePlaywrightJson(stdout);
if (parsed) {
resolve({
slug,
status: parsed.hasFailures ? "fail" : "pass",
tests: parsed.tests,
duration_ms: durationMs,
});
return;
}
resolve({
slug,
status: exitedWithError ? "fail" : "pass",
tests: {},
duration_ms: durationMs,
});
},
);
});
}
// ---------------------------------------------------------------------------
// Playwright JSON parsing
// ---------------------------------------------------------------------------
interface ParsedPlaywright {
tests: Record<string, TestResult>;
hasFailures: boolean;
}
/**
* Normalize Playwright test statuses to the vocabulary expected by the
* matrix module ("pass", "fail", "error", "skip").
*/
function normalizeStatus(pwStatus: string): TestResult["status"] {
if (pwStatus === "passed") return "pass";
if (pwStatus === "failed") return "fail";
if (pwStatus === "timedOut") return "error";
if (pwStatus === "skipped") return "skip";
if (pwStatus === "interrupted") return "error";
return "error";
}
/**
* Try to parse Playwright JSON reporter output from stdout. Returns null
* if parsing fails. Handles the nested suites/specs/tests structure.
*/
function tryParsePlaywrightJson(
stdout: string | null,
): ParsedPlaywright | null {
if (!stdout) return null;
try {
const data = JSON.parse(stdout) as {
suites?: Array<{
title: string;
specs?: Array<{
title: string;
tests?: Array<{
results?: Array<{
status: string;
duration: number;
error?: { message?: string };
}>;
}>;
}>;
suites?: Array<unknown>;
}>;
};
if (!data.suites) return null;
const tests: Record<string, TestResult> = {};
let hasFailures = false;
function walkSuites(
suites: Array<{
title: string;
specs?: Array<{
title: string;
tests?: Array<{
results?: Array<{
status: string;
duration: number;
error?: { message?: string };
}>;
}>;
}>;
suites?: Array<unknown>;
}>,
parentTitle?: string,
): void {
for (const suite of suites) {
const suiteTitle = parentTitle
? `${parentTitle} > ${suite.title}`
: suite.title;
if (suite.specs) {
for (const spec of suite.specs) {
if (spec.tests) {
for (const test of spec.tests) {
if (test.results && test.results.length > 0) {
const lastResult = test.results[test.results.length - 1];
const normalized = normalizeStatus(lastResult.status);
const entry: TestResult = {
status: normalized,
duration_ms: lastResult.duration,
};
if (lastResult.error?.message) {
entry.error = lastResult.error.message;
}
if (normalized === "fail" || normalized === "error") {
hasFailures = true;
}
tests[`${suiteTitle} > ${spec.title}`] = entry;
}
}
}
}
}
// Recurse into nested suites
if (suite.suites) {
walkSuites(
suite.suites as Array<{
title: string;
specs?: Array<{
title: string;
tests?: Array<{
results?: Array<{
status: string;
duration: number;
error?: { message?: string };
}>;
}>;
}>;
suites?: Array<unknown>;
}>,
suiteTitle,
);
}
}
}
walkSuites(data.suites);
return { tests, hasFailures };
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// runParallel
// ---------------------------------------------------------------------------
/**
* Run slugs in parallel with bounded concurrency using a Promise-based
* semaphore pattern.
*/
export async function runParallel(
slugs: string[],
opts: RunOptions,
): Promise<SlugResult[]> {
const results: SlugResult[] = [];
const executing = new Set<Promise<void>>();
for (const slug of slugs) {
opts.onSlugStart?.(slug, "");
const p = runSlug(slug, opts.level, opts.timeout, opts.showcaseDir)
.then((r) => {
results.push(r);
opts.onSlugComplete?.(r, "");
})
.finally(() => executing.delete(p));
executing.add(p);
if (executing.size >= opts.maxParallel) {
await Promise.race(executing);
}
}
await Promise.all(executing);
return results;
}
// ---------------------------------------------------------------------------
// runTiered
// ---------------------------------------------------------------------------
/**
* Execute tiers in sequence. Tier 1 runs with maxParallel=1 for fast feedback.
* After each tier, checks fail_fast + failure count; if fail_fast and any
* failures, stops the run.
*
* `healthySlugs` filters the tier slugs — only healthy slugs are run, the
* rest are marked "unhealthy".
*/
export async function runTiered(
allSlugs: string[],
healthySlugs: string[],
opts: RunOptions,
): Promise<TieredRunResult> {
const tiersPath = `${opts.showcaseDir}/eval-tiers.json`;
const tiers = loadTiers(tiersPath, allSlugs);
const healthySet = new Set(healthySlugs);
const allResults: SlugResult[] = [];
const tierSummaries: TieredRunResult["tierSummaries"] = [];
let abortedAtTier: number | undefined;
const maxTier = opts.maxTier ?? tiers.length;
for (let i = 0; i < Math.min(tiers.length, maxTier); i++) {
const tier = tiers[i];
const tierStart = Date.now();
// Filter to only healthy slugs for this tier
const runnableSlugs = tier.slugs.filter((s) => healthySet.has(s));
const unhealthySlugs = tier.slugs.filter((s) => !healthySet.has(s));
// Mark unhealthy slugs as such
for (const slug of unhealthySlugs) {
allResults.push({
slug,
status: "unhealthy",
tests: {},
duration_ms: 0,
});
}
// Tier 1 runs with maxParallel=1 for fast feedback
const tierParallel = i === 0 ? 1 : opts.maxParallel;
const tierOpts: RunOptions = {
...opts,
maxParallel: tierParallel,
onSlugStart: (slug) => opts.onSlugStart?.(slug, tier.name),
onSlugComplete: (result) => opts.onSlugComplete?.(result, tier.name),
};
const tierResults = await runParallel(runnableSlugs, tierOpts);
allResults.push(...tierResults);
const passed = tierResults.filter((r) => r.status === "pass").length;
const failed = tierResults.filter(
(r) => r.status === "fail" || r.status === "error",
).length;
tierSummaries.push({
name: tier.name,
total: tier.slugs.length,
passed,
failed,
duration_ms: Date.now() - tierStart,
});
// Check fail-fast: if this tier has fail_fast and there are failures, abort
if (tier.fail_fast && !opts.noFailFast && failed > 0) {
abortedAtTier = i;
break;
}
}
return {
results: allResults,
abortedAtTier,
tierSummaries,
};
}