dsh-flakefinder 0.4.23 → 0.5.0

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/lib/classify.js CHANGED
@@ -1,37 +1,406 @@
1
1
  /**
2
- * 多轮结果聚合与 flaky 判定:纯函数,便于单测边界。
2
+ * 多轮结果聚合、flaky 判定与根因诊断:纯函数,零运行时依赖,便于单测边界。
3
3
  *
4
4
  * @module dsh-flakefinder/classify
5
5
  */
6
+ import { createHash } from 'node:crypto';
7
+ const ANSI_ESCAPE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
8
+ const VERDICT_RANK = {
9
+ 'flaky': 0,
10
+ 'stable-fail': 1,
11
+ 'skipped': 2,
12
+ 'stable-pass': 3,
13
+ };
14
+ const INTERNAL_FRAME = /(?:node:internal\/|node:async_hooks|node:timers|node:net|node:events|internal\/modules\/|node_modules[\\/](?:vitest|@vitest|jest|@jest|jest-circus|jest-runner|tinypool|pirates|expect)[\\/]|site-packages[\\/](?:_pytest|pluggy|pytest)[\\/])/i;
15
+ function round1(value) {
16
+ return Math.round(value * 10) / 10;
17
+ }
18
+ function stripAnsi(text) {
19
+ return text.replace(ANSI_ESCAPE, '');
20
+ }
21
+ /** 脱敏常见密钥/令牌,避免写入诊断报告或堆栈采样。 */
22
+ export function redactSecrets(text) {
23
+ let out = text;
24
+ out = out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 <REDACTED>');
25
+ out = out.replace(/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, '<REDACTED_JWT>');
26
+ out = out.replace(/\bsk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{12,}/g, '<REDACTED_KEY>');
27
+ out = out.replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g, '<REDACTED_KEY>');
28
+ out = out.replace(/\bAKIA[0-9A-Z]{16}\b/g, '<REDACTED_KEY>');
29
+ out = out.replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, '<REDACTED_KEY>');
30
+ out = out.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^:\s/@]+:)([^@\s/]+)(@)/gi, '$1<REDACTED>$3');
31
+ out = out.replace(/\b(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|private[_-]?key|client[_-]?secret)(["']?\s*[:=]\s*)(["']?)([^\s"',;)}\]]+)\3/gi, '$1$2$3<REDACTED>$3');
32
+ out = out.replace(/\b(token)(["']?\s*[:=]\s*)(["']?)([A-Za-z0-9._~+/=-]{16,})\3/gi, '$1$2$3<REDACTED>$3');
33
+ return out;
34
+ }
35
+ /** 归一化错误文本中的动态噪声(时间戳、UUID、地址、端口、临时路径、数字差异),用于聚类指纹。 */
36
+ export function normalizeErrorForFingerprint(text) {
37
+ let out = stripAnsi(redactSecrets(text));
38
+ // ISO 时间戳与日期时间
39
+ out = out.replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g, '<ISO_TIME>');
40
+ out = out.replace(/\b\d{4}[-/]\d{2}[-/]\d{2}\b/g, '<DATE>');
41
+ out = out.replace(/\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/g, '<TIME>');
42
+ // UUID
43
+ out = out.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<UUID>');
44
+ // 临时目录路径(Windows & POSIX)
45
+ out = out.replace(/[A-Za-z]:[\\/](?:Users|Documents and Settings)[\\/][^\\/:\s"'`]+[\\/]AppData[\\/]Local[\\/]Temp[\\/][^\s"'`)\]]+/gi, '<TMP_PATH>');
46
+ out = out.replace(/[A-Za-z]:[\\/]Windows[\\/]Temp[\\/][^\s"'`)\]]+/gi, '<TMP_PATH>');
47
+ out = out.replace(/(?:\/private)?\/(?:tmp|var\/tmp|var\/folders)\/[^\s"'`)\]]+/g, '<TMP_PATH>');
48
+ // 随机端口
49
+ out = out.replace(/\b(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]):(\d{2,5})\b/gi, '$1:<PORT>');
50
+ out = out.replace(/\bport\s+\d{2,5}\b/gi, 'port <PORT>');
51
+ out = out.replace(/(?<!\.[a-z]{1,4}):\d{4,5}\b/gi, ':<PORT>');
52
+ // 十六进制地址与长哈希
53
+ out = out.replace(/\b0x[0-9a-f]+\b/gi, '<HEX>');
54
+ out = out.replace(/\b[0-9a-f]{16,}\b/gi, '<HEX>');
55
+ // 耗时与数字差异
56
+ out = out.replace(/\b\d+(?:\.\d+)?\s*(?:ms|s|us|ns|µs)\b/gi, '<DURATION>');
57
+ out = out.replace(/\b\d+(?:\.\d+)?\b/g, '<NUM>');
58
+ return out.replace(/\s+/g, ' ').trim().toLowerCase();
59
+ }
60
+ /** 计算结构化错误指纹,用于把同一根因的多次失败归为一簇。 */
61
+ export function errorFingerprint(error) {
62
+ const rawMessage = error.message.trim() || firstNonEmptyLine(error.stack ?? '') || '(unknown error)';
63
+ const firstLine = firstNonEmptyLine(rawMessage);
64
+ const typeKey = (error.type ?? '').trim().toLowerCase();
65
+ const normalized = normalizeErrorForFingerprint(firstLine).slice(0, 300);
66
+ return createHash('sha256').update(typeKey + '|' + normalized).digest('hex').slice(0, 12);
67
+ }
68
+ function firstNonEmptyLine(text) {
69
+ for (const line of text.split(/\r?\n/)) {
70
+ const trimmed = line.trim();
71
+ if (trimmed !== '')
72
+ return trimmed;
73
+ }
74
+ return '';
75
+ }
76
+ function cleanMessage(raw, maxChars = 400) {
77
+ const cleaned = stripAnsi(redactSecrets(raw)).replace(/\r\n/g, '\n').trim();
78
+ if (cleaned.length <= maxChars)
79
+ return cleaned;
80
+ return cleaned.slice(0, Math.max(1, maxChars - 1)) + '…';
81
+ }
82
+ function isStackFrameLine(line) {
83
+ const trimmed = line.trim();
84
+ if (trimmed.startsWith('at ') || /^\s*File\s+"/.test(line) || /^[\w$.<>-]+@/.test(trimmed))
85
+ return true;
86
+ // Node 24 node:test TAP YAML 堆栈帧省略前导 "at ",例如:
87
+ // TestContext.<anonymous> (file:///.../a.test.mjs:5:40)
88
+ // Test.runInAsyncScope (node:async_hooks:227:14)
89
+ return /\([^()]+:\d+(?::\d+)?\)$/.test(trimmed) || /^(?:file:\/\/|node:|[A-Za-z]:[\\/]|\/)[^\s]+:\d+(?::\d+)?$/.test(trimmed);
90
+ }
91
+ /** 压缩代表堆栈:脱敏、保留头部与关键业务帧,限制行数(默认 12 行)与字符数(默认 1200)。 */
92
+ export function compactStack(stack, maxLines = 12, maxChars = 1200) {
93
+ const sanitized = stripAnsi(redactSecrets(stack)).replace(/\r\n/g, '\n');
94
+ const rawLines = sanitized.split('\n');
95
+ let start = 0;
96
+ while (start < rawLines.length && rawLines[start].trim() === '')
97
+ start += 1;
98
+ let end = rawLines.length;
99
+ while (end > start && rawLines[end - 1].trim() === '')
100
+ end -= 1;
101
+ const lines = rawLines.slice(start, end);
102
+ if (lines.length === 0)
103
+ return '';
104
+ let selected;
105
+ if (lines.length <= maxLines) {
106
+ selected = lines;
107
+ }
108
+ else {
109
+ const firstFrameIdx = lines.findIndex(isStackFrameLine);
110
+ const headEnd = firstFrameIdx === -1 ? Math.min(3, lines.length) : Math.min(Math.max(1, firstFrameIdx), 3);
111
+ const chosen = new Set();
112
+ for (let i = 0; i < headEnd; i += 1)
113
+ chosen.add(i);
114
+ const budget = Math.max(1, maxLines - 1);
115
+ const topFrameIdx = firstFrameIdx >= headEnd ? firstFrameIdx : -1;
116
+ if (topFrameIdx !== -1 && chosen.size < budget)
117
+ chosen.add(topFrameIdx);
118
+ const userFrameIndices = [];
119
+ const otherIndices = [];
120
+ for (let i = headEnd; i < lines.length; i += 1) {
121
+ if (chosen.has(i))
122
+ continue;
123
+ const line = lines[i];
124
+ if (isStackFrameLine(line) && !INTERNAL_FRAME.test(line)) {
125
+ userFrameIndices.push(i);
126
+ }
127
+ else {
128
+ otherIndices.push(i);
129
+ }
130
+ }
131
+ for (const idx of userFrameIndices) {
132
+ if (chosen.size >= budget)
133
+ break;
134
+ chosen.add(idx);
135
+ }
136
+ for (const idx of otherIndices) {
137
+ if (chosen.size >= budget)
138
+ break;
139
+ chosen.add(idx);
140
+ }
141
+ const sortedIdx = [...chosen].sort((a, b) => a - b);
142
+ const omitted = lines.length - sortedIdx.length;
143
+ selected = sortedIdx.map(i => lines[i]);
144
+ if (omitted > 0) {
145
+ selected.push(' ... (' + String(omitted) + ' lines omitted)');
146
+ }
147
+ }
148
+ const out = [];
149
+ let used = 0;
150
+ for (let i = 0; i < selected.length && out.length < maxLines; i += 1) {
151
+ const line = selected[i];
152
+ const sep = out.length === 0 ? 0 : 1;
153
+ if (used + sep + line.length <= maxChars) {
154
+ out.push(line);
155
+ used += sep + line.length;
156
+ }
157
+ else {
158
+ const remain = maxChars - used - sep;
159
+ if (remain > 1) {
160
+ out.push(line.slice(0, remain - 1) + '…');
161
+ }
162
+ else if (out.length === 0) {
163
+ out.push(line.slice(0, Math.max(1, maxChars - 1)) + '…');
164
+ }
165
+ break;
166
+ }
167
+ }
168
+ return out.join('\n');
169
+ }
170
+ function percentile95(values) {
171
+ if (values.length === 0)
172
+ return 0;
173
+ const sorted = [...values].sort((a, b) => a - b);
174
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * 0.95) - 1));
175
+ return round1(sorted[idx]);
176
+ }
177
+ function averageOrNull(values) {
178
+ if (values.length === 0)
179
+ return null;
180
+ const sum = values.reduce((acc, v) => acc + v, 0);
181
+ return round1(sum / values.length);
182
+ }
183
+ function addErrorToClusters(clusters, error, runIndex) {
184
+ const fp = errorFingerprint(error);
185
+ const message = cleanMessage(error.message || firstNonEmptyLine(error.stack ?? '') || '(unknown error)');
186
+ const stack = error.stack !== undefined && error.stack.trim() !== '' ? compactStack(error.stack) : undefined;
187
+ const existing = clusters.get(fp);
188
+ if (existing !== undefined) {
189
+ existing.count += 1;
190
+ if (!existing.runIndices.includes(runIndex))
191
+ existing.runIndices.push(runIndex);
192
+ if (existing.type === undefined && error.type !== undefined && error.type.trim() !== '') {
193
+ existing.type = error.type.trim();
194
+ }
195
+ if (existing.sampleStack === undefined && stack !== undefined && stack !== '') {
196
+ existing.sampleStack = stack;
197
+ }
198
+ return;
199
+ }
200
+ const created = {
201
+ fingerprint: fp,
202
+ count: 1,
203
+ message,
204
+ runIndices: [runIndex],
205
+ };
206
+ if (error.type !== undefined && error.type.trim() !== '')
207
+ created.type = error.type.trim();
208
+ if (stack !== undefined && stack !== '')
209
+ created.sampleStack = stack;
210
+ clusters.set(fp, created);
211
+ }
212
+ function finalizeClusters(clusters) {
213
+ return [...clusters.values()]
214
+ .map(c => ({
215
+ fingerprint: c.fingerprint,
216
+ count: c.count,
217
+ ...(c.type !== undefined ? { type: c.type } : {}),
218
+ message: c.message,
219
+ ...(c.sampleStack !== undefined ? { sampleStack: c.sampleStack } : {}),
220
+ runIndices: [...c.runIndices].sort((a, b) => a - b),
221
+ }))
222
+ .sort((a, b) => b.count - a.count || (a.runIndices[0] ?? 0) - (b.runIndices[0] ?? 0));
223
+ }
224
+ function isFailSymbol(symbol) {
225
+ return symbol === 'F' || symbol === 'T';
226
+ }
227
+ function detectPatterns(input) {
228
+ if (input.verdict !== 'flaky') {
229
+ return input.teardownCrash ? ['teardown-crash'] : [];
230
+ }
231
+ const patterns = [];
232
+ // 1. cold-start: 仅第 1 轮失败,后续全部通过,且总轮次 >= 3
233
+ if (input.timeline.length >= 3
234
+ && isFailSymbol(input.timeline[0])
235
+ && input.timeline.slice(1).every(symbol => symbol === 'P')) {
236
+ patterns.push('cold-start');
237
+ }
238
+ // 2. state-leak: 先通过 (>= 1 轮),一旦失败后剩余轮次持续失败 (>= 2 轮连续尾部失败)
239
+ const effective = input.timeline.filter(symbol => symbol === 'P' || symbol === 'F' || symbol === 'T');
240
+ const firstFail = effective.findIndex(isFailSymbol);
241
+ if (firstFail >= 1
242
+ && effective.length - firstFail >= 2
243
+ && effective.slice(firstFail).every(isFailSymbol)) {
244
+ patterns.push('state-leak');
245
+ }
246
+ // 3. timeout-race: 超时标志 / 失败耗时显著拉长 (>=1.8x 且差值 >=100ms) / 错误信息含超时关键词
247
+ const durationRatioRace = input.passDurationAvgMs !== null
248
+ && input.failDurationAvgMs !== null
249
+ && input.failDurationAvgMs - input.passDurationAvgMs >= 100
250
+ && input.failDurationAvgMs >= input.passDurationAvgMs * 1.8;
251
+ const timeoutErrorMatch = input.errorClusters.some(cluster => /timeout|timed out|exceeded/i.test(cluster.message)
252
+ || (cluster.type !== undefined && /timeout/i.test(cluster.type)));
253
+ if (input.failedRunTimedOut || input.timeline.includes('T') || durationRatioRace || timeoutErrorMatch) {
254
+ patterns.push('timeout-race');
255
+ }
256
+ // 4. order-dependent: 存在互不相交的通过种子与失败种子
257
+ if (input.failedSeeds.size > 0
258
+ && input.passedSeeds.size > 0
259
+ && [...input.failedSeeds].every(seed => !input.passedSeeds.has(seed))) {
260
+ patterns.push('order-dependent');
261
+ }
262
+ // 5. teardown-crash: 断言通过但进程异常退出
263
+ if (input.teardownCrash) {
264
+ patterns.push('teardown-crash');
265
+ }
266
+ // 6. intermittent: 无更窄特征时的默认兜底
267
+ if (patterns.length === 0) {
268
+ patterns.push('intermittent');
269
+ }
270
+ return patterns;
271
+ }
272
+ /** 根因模式的简明中文说明。 */
273
+ export function patternLabel(pattern) {
274
+ switch (pattern) {
275
+ case 'cold-start': return '冷启动偶发(仅首轮失败,后续均通过,可能存在预热/缓存初始化竞争)';
276
+ case 'state-leak': return '状态泄漏(先通过后持续失败,可能存在未清理的全局状态、文件或端口)';
277
+ case 'timeout-race': return '超时/竞态(出现超时或失败耗时显著拉长)';
278
+ case 'order-dependent': return '顺序依赖(不同随机种子下稳定区分通过与失败)';
279
+ case 'teardown-crash': return '清理阶段崩溃(用例断言已通过,但测试进程在退出阶段异常中止)';
280
+ case 'intermittent': return '间歇性偶发(无单一固定规律,建议结合错误聚合与并发环境排查)';
281
+ }
282
+ }
283
+ /**
284
+ * 连续全通过 runs 轮后,在指定置信度下的最大潜在偶发失败率上界(百分比,保留 1 位小数)。
285
+ * 公式:1 - (1 - confidence)^(1 / runs)
286
+ */
287
+ export function confidenceUpperBound(runs, confidence = 0.95) {
288
+ if (!Number.isFinite(runs) || runs <= 0)
289
+ return 100;
290
+ if (!Number.isFinite(confidence) || confidence <= 0)
291
+ return 0;
292
+ if (confidence >= 1)
293
+ return 100;
294
+ return Math.round((1 - Math.pow(1 - confidence, 1 / runs)) * 1000) / 10;
295
+ }
296
+ /**
297
+ * 在指定置信度下,要将潜在偶发失败率压到 maxFlakeRate 以下所需的最少全通过轮数。
298
+ * maxFlakeRate 同时支持百分比(如 5 表示 5%、10 表示 10%)与比例(如 0.05、0.1)。
299
+ */
300
+ export function runsNeededForThreshold(maxFlakeRate, confidence = 0.95) {
301
+ if (!Number.isFinite(maxFlakeRate) || maxFlakeRate <= 0) {
302
+ throw new Error('maxFlakeRate 必须大于 0。');
303
+ }
304
+ if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) {
305
+ throw new Error('confidence 必须在 (0, 1) 之间。');
306
+ }
307
+ if (maxFlakeRate >= 100)
308
+ return 1;
309
+ const p = maxFlakeRate < 1 ? maxFlakeRate : maxFlakeRate / 100;
310
+ if (p >= 1)
311
+ return 1;
312
+ return Math.max(1, Math.ceil(Math.log(1 - confidence) / Math.log(1 - p)));
313
+ }
314
+ function truncateSingleLine(text, maxChars) {
315
+ const line = firstNonEmptyLine(text);
316
+ if (line.length <= maxChars)
317
+ return line;
318
+ return line.slice(0, Math.max(1, maxChars - 1)) + '…';
319
+ }
6
320
  export function aggregate(runs) {
7
- const records = runs.map(run => ({
8
- runIndex: run.index,
9
- success: run.report?.success === true,
10
- passed: run.report?.passed ?? 0,
11
- failed: run.report?.failed ?? 0,
12
- skipped: run.report?.skipped ?? 0,
13
- durationMs: run.durationMs,
14
- }));
15
- const active = runs.filter(run => run.report !== null);
321
+ const orderedRuns = [...runs].sort((a, b) => a.index - b.index);
322
+ const records = orderedRuns.map(run => {
323
+ const success = run.report?.success === true
324
+ && run.timedOut !== true
325
+ && run.truncated !== true
326
+ && run.error === undefined;
327
+ const rec = {
328
+ runIndex: run.index,
329
+ success,
330
+ passed: run.report?.passed ?? 0,
331
+ failed: run.report?.failed ?? 0,
332
+ skipped: run.report?.skipped ?? 0,
333
+ durationMs: run.durationMs,
334
+ };
335
+ if (run.timedOut !== undefined)
336
+ rec.timedOut = run.timedOut;
337
+ if (run.truncated !== undefined)
338
+ rec.truncated = run.truncated;
339
+ if (run.seed !== undefined)
340
+ rec.seed = run.seed;
341
+ if (run.error !== undefined)
342
+ rec.error = redactSecrets(run.error);
343
+ return rec;
344
+ });
345
+ const active = orderedRuns.filter(run => run.report !== null);
16
346
  if (active.length === 0) {
17
- const detail = runs.find(run => run.error !== undefined);
18
- throw new Error('没有一次运行产出可解析的测试报告。' + (detail?.error !== undefined ? ' 首个错误:' + detail.error : ''));
347
+ const detail = orderedRuns.find(run => run.error !== undefined);
348
+ throw new Error('没有一次运行产出可解析的测试报告。' + (detail?.error !== undefined ? ' 首个错误:' + redactSecrets(detail.error) : ''));
19
349
  }
20
350
  const byId = new Map();
21
- for (const run of active) {
22
- const tests = run.report?.tests ?? [];
23
- for (const test of tests) {
351
+ for (let pos = 0; pos < orderedRuns.length; pos += 1) {
352
+ const run = orderedRuns[pos];
353
+ if (run.report === null)
354
+ continue;
355
+ const runTests = run.report.tests ?? [];
356
+ for (const test of runTests) {
24
357
  let entry = byId.get(test.id);
25
358
  if (entry === undefined) {
26
- entry = { file: test.file, name: test.name, passes: 0, failures: 0, skips: 0 };
359
+ entry = {
360
+ file: test.file,
361
+ name: test.name,
362
+ passes: 0,
363
+ failures: 0,
364
+ skips: 0,
365
+ passDurations: [],
366
+ failDurations: [],
367
+ allDurations: [],
368
+ statusByRunPos: new Map(),
369
+ errorClusters: new Map(),
370
+ failedRunTimedOut: false,
371
+ passedSeeds: new Set(),
372
+ failedSeeds: new Set(),
373
+ };
27
374
  byId.set(test.id, entry);
28
375
  }
29
- if (test.status === 'passed')
376
+ const dur = Math.max(0, Number.isFinite(test.durationMs) ? test.durationMs : 0);
377
+ entry.allDurations.push(dur);
378
+ const prevSym = entry.statusByRunPos.get(pos);
379
+ if (test.status === 'passed') {
30
380
  entry.passes += 1;
31
- else if (test.status === 'failed')
381
+ entry.passDurations.push(dur);
382
+ if (prevSym !== 'F')
383
+ entry.statusByRunPos.set(pos, 'P');
384
+ if (run.seed !== undefined)
385
+ entry.passedSeeds.add(run.seed);
386
+ }
387
+ else if (test.status === 'failed') {
32
388
  entry.failures += 1;
33
- else
389
+ entry.failDurations.push(dur);
390
+ entry.statusByRunPos.set(pos, 'F');
391
+ if (run.timedOut === true)
392
+ entry.failedRunTimedOut = true;
393
+ if (run.seed !== undefined)
394
+ entry.failedSeeds.add(run.seed);
395
+ if (test.error !== undefined) {
396
+ addErrorToClusters(entry.errorClusters, test.error, run.index);
397
+ }
398
+ }
399
+ else {
34
400
  entry.skips += 1;
401
+ if (prevSym === undefined)
402
+ entry.statusByRunPos.set(pos, 'S');
403
+ }
35
404
  }
36
405
  }
37
406
  const tests = [];
@@ -58,7 +427,33 @@ export function aggregate(runs) {
58
427
  verdict = 'flaky';
59
428
  flakyCount += 1;
60
429
  }
61
- tests.push({
430
+ const timeline = orderedRuns.map((run, pos) => {
431
+ const sym = entry.statusByRunPos.get(pos);
432
+ if (sym !== undefined)
433
+ return sym;
434
+ if (run.report === null && run.timedOut === true)
435
+ return 'T';
436
+ return '-';
437
+ });
438
+ const executedDurations = [...entry.passDurations, ...entry.failDurations];
439
+ const durPool = executedDurations.length > 0 ? executedDurations : entry.allDurations;
440
+ const passDurationAvgMs = averageOrNull(entry.passDurations);
441
+ const failDurationAvgMs = averageOrNull(entry.failDurations);
442
+ const maxDurationMs = durPool.length === 0 ? 0 : round1(Math.max(...durPool));
443
+ const p95DurationMs = percentile95(durPool);
444
+ const errorClusters = finalizeClusters(entry.errorClusters);
445
+ const patterns = detectPatterns({
446
+ verdict,
447
+ timeline,
448
+ passDurationAvgMs,
449
+ failDurationAvgMs,
450
+ errorClusters,
451
+ failedRunTimedOut: entry.failedRunTimedOut,
452
+ passedSeeds: entry.passedSeeds,
453
+ failedSeeds: entry.failedSeeds,
454
+ });
455
+ const failedSeedsArr = [...entry.failedSeeds];
456
+ const record = {
62
457
  id,
63
458
  file: entry.file,
64
459
  name: entry.name,
@@ -67,18 +462,138 @@ export function aggregate(runs) {
67
462
  skips: entry.skips,
68
463
  failureRate: seen === 0 ? 0 : Math.round((entry.failures / seen) * 1000) / 10,
69
464
  verdict,
465
+ timeline,
466
+ passDurationAvgMs,
467
+ failDurationAvgMs,
468
+ maxDurationMs,
469
+ p95DurationMs,
470
+ errorClusters,
471
+ patterns,
472
+ };
473
+ if (failedSeedsArr.length > 0)
474
+ record.failedSeeds = failedSeedsArr;
475
+ tests.push(record);
476
+ }
477
+ // 检查运行级异常(缺失报告、超时、输出截断或断言全过后的进程异常退出),生成合成 (timeout)/(crash) 记录。
478
+ const abnormalPositions = [];
479
+ let timedOutCount = 0;
480
+ let teardownCrashCount = 0;
481
+ for (let pos = 0; pos < orderedRuns.length; pos += 1) {
482
+ const run = orderedRuns[pos];
483
+ const rec = records[pos];
484
+ const isMissingReport = run.report === null;
485
+ const isTeardownOrExecAnomaly = run.report !== null && (run.timedOut === true
486
+ || run.truncated === true
487
+ || run.error !== undefined
488
+ || (run.report.passed > 0 && run.report.failed === 0 && !rec.success));
489
+ if (isMissingReport || isTeardownOrExecAnomaly) {
490
+ abnormalPositions.push(pos);
491
+ if (run.timedOut === true)
492
+ timedOutCount += 1;
493
+ if (run.report !== null
494
+ && run.report.passed > 0
495
+ && run.report.failed === 0
496
+ && !rec.success
497
+ && run.truncated !== true
498
+ && run.timedOut !== true) {
499
+ teardownCrashCount += 1;
500
+ }
501
+ }
502
+ }
503
+ if (abnormalPositions.length > 0) {
504
+ const abnormalSet = new Set(abnormalPositions);
505
+ const crashRuns = abnormalPositions.length;
506
+ const completedRuns = records.length - crashRuns;
507
+ const allTimedOut = timedOutCount === crashRuns && timedOutCount > 0;
508
+ const synId = allTimedOut ? '(timeout)' : '(crash)';
509
+ const synName = allTimedOut
510
+ ? '运行超时(单轮未在超时前完成)'
511
+ : '运行异常(进程失败或未产出报告)';
512
+ const synVerdict = completedRuns > 0 ? 'flaky' : 'stable-fail';
513
+ const synTimeline = orderedRuns.map((run, pos) => {
514
+ if (!abnormalSet.has(pos))
515
+ return 'P';
516
+ return run.timedOut === true ? 'T' : 'F';
517
+ });
518
+ const synPassDurations = [];
519
+ const synFailDurations = [];
520
+ const synPassedSeeds = new Set();
521
+ const synFailedSeeds = new Set();
522
+ const synClusters = new Map();
523
+ for (let pos = 0; pos < orderedRuns.length; pos += 1) {
524
+ const run = orderedRuns[pos];
525
+ const dur = Math.max(0, Number.isFinite(run.durationMs) ? run.durationMs : 0);
526
+ if (abnormalSet.has(pos)) {
527
+ synFailDurations.push(dur);
528
+ if (run.seed !== undefined)
529
+ synFailedSeeds.add(run.seed);
530
+ if (run.error !== undefined && run.error.trim() !== '') {
531
+ addErrorToClusters(synClusters, {
532
+ type: run.timedOut === true ? 'TimeoutError' : 'ProcessError',
533
+ message: run.error,
534
+ }, run.index);
535
+ }
536
+ }
537
+ else {
538
+ synPassDurations.push(dur);
539
+ if (run.seed !== undefined)
540
+ synPassedSeeds.add(run.seed);
541
+ }
542
+ }
543
+ const synPassAvg = averageOrNull(synPassDurations);
544
+ const synFailAvg = averageOrNull(synFailDurations);
545
+ const synAllDurations = [...synPassDurations, ...synFailDurations];
546
+ const synErrorClusters = finalizeClusters(synClusters);
547
+ const synPatterns = detectPatterns({
548
+ verdict: synVerdict,
549
+ timeline: synTimeline,
550
+ passDurationAvgMs: synPassAvg,
551
+ failDurationAvgMs: synFailAvg,
552
+ errorClusters: synErrorClusters,
553
+ failedRunTimedOut: timedOutCount > 0,
554
+ passedSeeds: synPassedSeeds,
555
+ failedSeeds: synFailedSeeds,
556
+ teardownCrash: teardownCrashCount > 0,
70
557
  });
558
+ const synFailedSeedsArr = [...synFailedSeeds];
559
+ const synRecord = {
560
+ id: synId,
561
+ file: synId,
562
+ name: synName,
563
+ passes: completedRuns,
564
+ failures: crashRuns,
565
+ skips: 0,
566
+ failureRate: Math.round((crashRuns / records.length) * 1000) / 10,
567
+ verdict: synVerdict,
568
+ timeline: synTimeline,
569
+ passDurationAvgMs: synPassAvg,
570
+ failDurationAvgMs: synFailAvg,
571
+ maxDurationMs: synAllDurations.length === 0 ? 0 : round1(Math.max(...synAllDurations)),
572
+ p95DurationMs: percentile95(synAllDurations),
573
+ errorClusters: synErrorClusters,
574
+ patterns: synPatterns,
575
+ };
576
+ if (synFailedSeedsArr.length > 0)
577
+ synRecord.failedSeeds = synFailedSeedsArr;
578
+ tests.push(synRecord);
579
+ if (synVerdict === 'flaky')
580
+ flakyCount += 1;
581
+ else
582
+ stableFailCount += 1;
71
583
  }
72
584
  let verdict;
73
585
  const passRuns = records.filter(run => run.success).length;
74
- const executionFailed = runs.some(run => run.error !== undefined);
586
+ const executionFailed = abnormalPositions.length > 0;
75
587
  if (tests.length === 0 && !executionFailed) {
76
588
  verdict = 'empty';
77
589
  }
78
590
  else if (tests.every(test => test.verdict === 'skipped') && !executionFailed) {
79
591
  verdict = 'skipped';
80
592
  }
81
- else if (passRuns === records.length) {
593
+ else if (flakyCount > 0) {
594
+ verdict = 'flaky';
595
+ }
596
+ else if (passRuns === records.length && stableFailCount === 0) {
82
597
  verdict = 'stable-pass';
83
598
  }
84
599
  else if (passRuns === 0) {
@@ -87,26 +602,10 @@ export function aggregate(runs) {
87
602
  else {
88
603
  verdict = 'flaky';
89
604
  }
90
- // 运行级 flaky 但无具体 flaky 用例:可能是无报告或报告完成后进程异常退出。
91
- // 补一条合成记录,避免 flaky 信号丢失(历史写入 verdict=flaky 但 flakyCount=0)。
92
- if (verdict === 'flaky' && flakyCount === 0) {
93
- const crashRuns = runs.filter(run => run.report === null || run.error !== undefined).length;
94
- if (crashRuns > 0) {
95
- tests.push({
96
- id: '(crash)',
97
- file: '(crash)',
98
- name: '运行异常(进程失败或未产出报告)',
99
- passes: 0,
100
- failures: crashRuns,
101
- skips: 0,
102
- failureRate: 100,
103
- verdict: 'flaky',
104
- });
105
- flakyCount += 1;
106
- }
107
- }
108
- tests.sort((a, b) => a.id.localeCompare(b.id));
109
- return {
605
+ tests.sort((a, b) => VERDICT_RANK[a.verdict] - VERDICT_RANK[b.verdict]
606
+ || b.failureRate - a.failureRate
607
+ || a.id.localeCompare(b.id));
608
+ const result = {
110
609
  runs: records,
111
610
  verdict,
112
611
  stablePassCount,
@@ -116,10 +615,28 @@ export function aggregate(runs) {
116
615
  tests,
117
616
  durationMs: records.reduce((sum, item) => sum + item.durationMs, 0),
118
617
  };
618
+ if (verdict === 'stable-pass') {
619
+ result.confidence95MaxFlakeRate = confidenceUpperBound(records.length, 0.95);
620
+ }
621
+ return result;
119
622
  }
120
- /** 结果里需要写入历史的 flaky 用例。 */
623
+ /** 结果里需要写入历史的 flaky 用例(保持精简,不携带大堆栈)。 */
121
624
  export function flakyTests(result) {
122
625
  return result.tests
123
626
  .filter(test => test.verdict === 'flaky')
124
- .map(test => ({ file: test.file, name: test.name, failureRate: test.failureRate }));
627
+ .map(test => {
628
+ const item = {
629
+ file: test.file,
630
+ name: test.name,
631
+ failureRate: test.failureRate,
632
+ };
633
+ if (test.patterns.length > 0)
634
+ item.patterns = test.patterns;
635
+ const top = test.errorClusters[0];
636
+ if (top !== undefined) {
637
+ const prefix = top.type ? top.type + ': ' : '';
638
+ item.topError = truncateSingleLine(prefix + top.message, 200);
639
+ }
640
+ return item;
641
+ });
125
642
  }