dsh-flakefinder 0.4.22 → 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/runner.js CHANGED
@@ -1,20 +1,39 @@
1
1
  /**
2
- * 进程执行层:复用 dsh-docker 同款 subprocess 包装,并按计划读取 JSON 报告。
2
+ * 进程执行层:复用 dsh-docker 同款 subprocess 包装,并按计划读取 JSON / JUnit / TAP 报告。
3
+ * 支持单轮超时错误区分、4MB 截断检测、以及受控并发与早停批次调度。
3
4
  *
4
5
  * @module dsh-flakefinder/runner
5
6
  */
6
7
  import fs from 'node:fs/promises';
7
8
  import { parseJsonReport, parseJunitReport, parseTapReport } from './parse.js';
9
+ /** 单轮测试运行超时错误,与宿主 AbortSignal 取消严格区分。 */
10
+ export class FlakeTimeoutError extends Error {
11
+ timeoutMs;
12
+ constructor(timeoutMs, message) {
13
+ super(message ?? '单轮测试超时(' + String(timeoutMs) + 'ms)');
14
+ this.name = 'FlakeTimeoutError';
15
+ this.timeoutMs = timeoutMs;
16
+ }
17
+ }
18
+ /** 判断错误是否为单轮测试超时错误。 */
19
+ export function isTimeoutError(error) {
20
+ return error instanceof FlakeTimeoutError || (error instanceof Error && error.name === 'FlakeTimeoutError');
21
+ }
8
22
  const COLLECT_BYTES = 4 * 1024 * 1024;
9
23
  /** 用 DSH subprocess 服务构造 ProcessRunner。 */
10
24
  export function createSubprocessRunner(spawn, graceMs, defaultTimeoutMs) {
11
25
  return {
12
26
  async run(argv, options) {
13
27
  const timeoutMs = options?.timeoutMs ?? defaultTimeoutMs;
28
+ const hostSignal = options?.signal;
29
+ hostSignal?.throwIfAborted();
14
30
  const controller = new AbortController();
15
- const signal = options?.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
16
- signal.throwIfAborted();
17
- const timer = setTimeout(() => controller.abort(new Error('flakefinder test run timed out')), timeoutMs);
31
+ const signal = hostSignal ? AbortSignal.any([hostSignal, controller.signal]) : controller.signal;
32
+ let timedOut = false;
33
+ const timer = setTimeout(() => {
34
+ timedOut = true;
35
+ controller.abort(new FlakeTimeoutError(timeoutMs));
36
+ }, timeoutMs);
18
37
  let handle;
19
38
  try {
20
39
  handle = spawn({
@@ -29,10 +48,38 @@ export function createSubprocessRunner(spawn, graceMs, defaultTimeoutMs) {
29
48
  signal,
30
49
  });
31
50
  const outcome = await handle.done;
32
- signal.throwIfAborted();
33
- const stdout = handle.collected.stdout?.readFrom(0).text ?? '';
34
- const stderr = handle.collected.stderr?.readFrom(0).text ?? '';
35
- return { exitCode: outcome.exitCode, signal: outcome.signal, stdout, stderr };
51
+ if (hostSignal?.aborted) {
52
+ throw hostSignal.reason;
53
+ }
54
+ if (timedOut || controller.signal.aborted) {
55
+ throw isTimeoutError(controller.signal.reason)
56
+ ? controller.signal.reason
57
+ : new FlakeTimeoutError(timeoutMs);
58
+ }
59
+ const stdoutChunk = handle.collected.stdout?.readFrom(0);
60
+ const stderrChunk = handle.collected.stderr?.readFrom(0);
61
+ const stdout = stdoutChunk?.text ?? '';
62
+ const stderr = stderrChunk?.text ?? '';
63
+ const truncated = stdoutChunk?.lossy === true || stderrChunk?.lossy === true;
64
+ return {
65
+ exitCode: outcome.exitCode,
66
+ signal: outcome.signal,
67
+ stdout,
68
+ stderr,
69
+ ...(truncated ? { truncated: true } : {}),
70
+ };
71
+ }
72
+ catch (error) {
73
+ if (hostSignal?.aborted) {
74
+ throw hostSignal.reason ?? error;
75
+ }
76
+ if (timedOut || controller.signal.aborted) {
77
+ if (isTimeoutError(error))
78
+ throw error;
79
+ const detail = error instanceof Error && error.message !== '' ? ':' + error.message : '';
80
+ throw new FlakeTimeoutError(timeoutMs, '单轮测试超时(' + String(timeoutMs) + 'ms)' + detail);
81
+ }
82
+ throw error;
36
83
  }
37
84
  finally {
38
85
  clearTimeout(timer);
@@ -44,25 +91,71 @@ function stderrTail(stderr) {
44
91
  const tail = stderr.trim().split(/\r?\n/).slice(-5).join(' | ');
45
92
  return tail || '无错误输出';
46
93
  }
47
- /** 执行一个测试计划并读取报告;进程失败但报告存在时仍返回报告。 */
94
+ async function cleanupReportFile(reportPath) {
95
+ if (reportPath !== '') {
96
+ await fs.rm(reportPath, { force: true }).catch(() => { });
97
+ }
98
+ }
99
+ /** 执行一个测试计划并读取报告;进程失败但报告存在时仍返回报告,单轮超时返回结构化超时记录。 */
48
100
  export async function executePlan(runner, plan, index, timeoutMs, cwd, signal) {
49
101
  const started = Date.now();
50
102
  signal?.throwIfAborted();
51
- const result = await runner.run(plan.argv, { timeoutMs, cwd, signal });
52
- signal?.throwIfAborted();
103
+ const seedField = plan.seed !== undefined ? { seed: plan.seed } : {};
104
+ let result;
105
+ try {
106
+ result = await runner.run(plan.argv, { timeoutMs, cwd, signal });
107
+ }
108
+ catch (error) {
109
+ await cleanupReportFile(plan.reportPath);
110
+ if (signal?.aborted) {
111
+ throw signal.reason ?? error;
112
+ }
113
+ if (isTimeoutError(error)) {
114
+ return {
115
+ index,
116
+ report: null,
117
+ durationMs: Date.now() - started,
118
+ exitCode: null,
119
+ stderr: '',
120
+ timedOut: true,
121
+ ...seedField,
122
+ error: '单轮测试超时(' + String(timeoutMs) + 'ms)',
123
+ };
124
+ }
125
+ throw error;
126
+ }
127
+ if (signal?.aborted) {
128
+ await cleanupReportFile(plan.reportPath);
129
+ throw signal.reason;
130
+ }
53
131
  const durationMs = Date.now() - started;
54
- const completed = (report) => {
132
+ const truncatedField = result.truncated === true ? { truncated: true } : {};
133
+ const completed = (report, forceTruncatedFailure = false) => {
55
134
  // A reporter can finish before teardown crashes or the process is killed.
56
135
  // Keep its assertions, but never turn that process outcome into a pass.
57
136
  const unexpectedExit = report.failed === 0 && (result.exitCode !== 0 || result.signal !== null);
137
+ const errors = [];
138
+ if (forceTruncatedFailure) {
139
+ errors.push('TAP 测试输出超过 4MB 采集上限被截断,结果不完整,不能判定为稳定通过。');
140
+ }
141
+ if (unexpectedExit) {
142
+ errors.push('测试进程异常结束(退出码 ' + String(result.exitCode ?? 'null') + (result.signal ? ',信号 ' + result.signal : '') + ');stderr:' + stderrTail(result.stderr));
143
+ }
144
+ const failedOutcome = forceTruncatedFailure || unexpectedExit;
58
145
  return {
59
- index, report: unexpectedExit ? { ...report, success: false } : report,
60
- durationMs, exitCode: result.exitCode, stderr: result.stderr,
61
- ...(unexpectedExit ? { error: '测试进程异常结束(退出码 ' + String(result.exitCode ?? 'null') + (result.signal ? ',信号 ' + result.signal : '') + ');stderr:' + stderrTail(result.stderr) } : {}),
146
+ index,
147
+ report: failedOutcome ? { ...report, success: false } : report,
148
+ durationMs,
149
+ exitCode: result.exitCode,
150
+ stderr: result.stderr,
151
+ ...(forceTruncatedFailure ? { truncated: true } : {}),
152
+ ...seedField,
153
+ ...(errors.length > 0 ? { error: errors.join(';') } : {}),
62
154
  };
63
155
  };
64
156
  if (plan.reportKind === 'tap') {
65
- return completed(parseTapReport(result.stdout));
157
+ const parsed = parseTapReport(result.stdout, { cwd, target: plan.target });
158
+ return completed(parsed, result.truncated === true);
66
159
  }
67
160
  let fileText = '';
68
161
  let fileError = '';
@@ -73,20 +166,26 @@ export async function executePlan(runner, plan, index, timeoutMs, cwd, signal) {
73
166
  fileError = error instanceof Error ? error.message : String(error);
74
167
  }
75
168
  finally {
76
- await fs.rm(plan.reportPath, { force: true }).catch(() => { });
169
+ await cleanupReportFile(plan.reportPath);
77
170
  }
78
171
  if (fileText.trim() === '') {
172
+ const truncNote = result.truncated === true ? '(测试输出超过 4MB 被截断)' : '';
79
173
  return {
80
174
  index,
81
175
  report: null,
82
176
  durationMs,
83
177
  exitCode: result.exitCode,
84
178
  stderr: result.stderr,
85
- error: plan.framework + ' 没有写出报告文件(' + fileError + ')。进程退出码:' + String(result.exitCode ?? 'null') + ';stderr:' + stderrTail(result.stderr),
179
+ ...truncatedField,
180
+ ...seedField,
181
+ error: plan.framework + ' 没有写出报告文件' + truncNote + '(' + fileError + ')。进程退出码:' + String(result.exitCode ?? 'null') + ';stderr:' + stderrTail(result.stderr),
86
182
  };
87
183
  }
88
184
  try {
89
- return completed(plan.reportKind === 'junit' ? parseJunitReport(fileText) : parseJsonReport(fileText, plan.framework));
185
+ const parsed = plan.reportKind === 'junit'
186
+ ? parseJunitReport(fileText, cwd)
187
+ : parseJsonReport(fileText, plan.framework, cwd);
188
+ return completed(parsed, false);
90
189
  }
91
190
  catch (error) {
92
191
  return {
@@ -95,7 +194,110 @@ export async function executePlan(runner, plan, index, timeoutMs, cwd, signal) {
95
194
  durationMs,
96
195
  exitCode: result.exitCode,
97
196
  stderr: result.stderr,
197
+ ...truncatedField,
198
+ ...seedField,
98
199
  error: error instanceof Error ? error.message : String(error),
99
200
  };
100
201
  }
101
202
  }
203
+ function isRunFailure(run) {
204
+ return run.timedOut === true || run.error !== undefined || run.report === null || run.report.success !== true;
205
+ }
206
+ const EARLY_STOP_SENTINEL = new Error('flakefinder early stop');
207
+ /**
208
+ * 批量执行多个测试计划:支持 1-4 路并发 worker 池,以及 verify-fix / until-flaky 早停模式。
209
+ * 返回结果始终按 1-based `index` 升序排列;宿主 signal 取消时立刻中止并抛出取消原因。
210
+ */
211
+ export async function executePlansBatch(runner, plans, options) {
212
+ const hostSignal = options.signal;
213
+ hostSignal?.throwIfAborted();
214
+ if (plans.length === 0)
215
+ return [];
216
+ const concurrency = Math.min(4, Math.max(1, Math.round(options.concurrency ?? 1)));
217
+ const mode = options.mode ?? 'full';
218
+ const workerCount = Math.min(concurrency, plans.length);
219
+ const needsInternalAbort = workerCount > 1 || mode !== 'full';
220
+ const internalController = needsInternalAbort ? new AbortController() : undefined;
221
+ const batchSignal = internalController !== undefined
222
+ ? (hostSignal ? AbortSignal.any([hostSignal, internalController.signal]) : internalController.signal)
223
+ : hostSignal;
224
+ let nextCursor = 0;
225
+ let earlyStopped = false;
226
+ let fatalError = undefined;
227
+ let hasFatalError = false;
228
+ let sawPassRun = false;
229
+ let sawFailRun = false;
230
+ let sawFlakyTest = false;
231
+ const testOutcomes = new Map();
232
+ const results = [];
233
+ function recordOutcomeAndCheckStop(run) {
234
+ if (isRunFailure(run))
235
+ sawFailRun = true;
236
+ else
237
+ sawPassRun = true;
238
+ if (run.report !== null) {
239
+ for (const test of run.report.tests) {
240
+ if (test.status !== 'passed' && test.status !== 'failed')
241
+ continue;
242
+ let state = testOutcomes.get(test.id);
243
+ if (state === undefined) {
244
+ state = { passed: false, failed: false };
245
+ testOutcomes.set(test.id, state);
246
+ }
247
+ if (test.status === 'passed')
248
+ state.passed = true;
249
+ else
250
+ state.failed = true;
251
+ if (state.passed && state.failed)
252
+ sawFlakyTest = true;
253
+ }
254
+ }
255
+ if (mode === 'verify-fix' && sawFailRun) {
256
+ earlyStopped = true;
257
+ internalController?.abort(EARLY_STOP_SENTINEL);
258
+ }
259
+ else if (mode === 'until-flaky' && ((sawPassRun && sawFailRun) || sawFlakyTest)) {
260
+ earlyStopped = true;
261
+ internalController?.abort(EARLY_STOP_SENTINEL);
262
+ }
263
+ }
264
+ async function worker() {
265
+ while (true) {
266
+ if (hostSignal?.aborted || earlyStopped || hasFatalError)
267
+ return;
268
+ const pos = nextCursor;
269
+ if (pos >= plans.length)
270
+ return;
271
+ nextCursor += 1;
272
+ const plan = plans[pos];
273
+ try {
274
+ const run = await executePlan(runner, plan, pos + 1, options.timeoutMs, options.cwd, batchSignal);
275
+ if (hostSignal?.aborted)
276
+ return;
277
+ results.push(run);
278
+ recordOutcomeAndCheckStop(run);
279
+ }
280
+ catch (error) {
281
+ if (hostSignal?.aborted)
282
+ return;
283
+ if (earlyStopped && (internalController?.signal.aborted ?? false))
284
+ return;
285
+ if (!hasFatalError) {
286
+ hasFatalError = true;
287
+ fatalError = error;
288
+ internalController?.abort(error);
289
+ }
290
+ return;
291
+ }
292
+ }
293
+ }
294
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
295
+ if (hostSignal?.aborted) {
296
+ throw hostSignal.reason;
297
+ }
298
+ if (hasFatalError) {
299
+ throw fatalError;
300
+ }
301
+ results.sort((a, b) => a.index - b.index);
302
+ return results;
303
+ }
package/lib/store.d.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  /**
2
- * 历史与隔离清单存储:JSON 文件、原子写入、零运行时依赖。
2
+ * 历史与隔离清单存储:按工作区隔离历史、兼容旧版全局历史与 v1 隔离清单、原子写入与文件锁。
3
3
  *
4
4
  * @module dsh-flakefinder/store
5
5
  */
6
+ export interface HistoryFlakyTest {
7
+ file: string;
8
+ name: string;
9
+ failureRate: number;
10
+ patterns?: string[];
11
+ topError?: string;
12
+ }
6
13
  export interface HistoryEntry {
7
14
  timestamp: string;
8
15
  target: string;
@@ -14,10 +21,16 @@ export interface HistoryEntry {
14
21
  stableFailCount: number;
15
22
  flakyCount: number;
16
23
  skippedCount: number;
17
- flakyTests: Array<{
18
- file: string;
19
- name: string;
20
- failureRate: number;
24
+ flakyTests: HistoryFlakyTest[];
25
+ workspace?: string;
26
+ testName?: string;
27
+ mode?: string;
28
+ concurrency?: number;
29
+ shuffle?: boolean;
30
+ failedSeeds?: number[];
31
+ errorSummary?: Array<{
32
+ message: string;
33
+ count: number;
21
34
  }>;
22
35
  }
23
36
  export interface QuarantineEntry {
@@ -25,17 +38,31 @@ export interface QuarantineEntry {
25
38
  name: string | null;
26
39
  reason: string;
27
40
  since: string;
41
+ updatedAt?: string;
42
+ lastVerifiedAt?: string;
43
+ lastFailureRate?: number;
44
+ issue?: string;
28
45
  }
29
46
  export interface QuarantineDocument {
30
47
  version: 1;
31
48
  quarantined: QuarantineEntry[];
32
49
  }
50
+ export interface QuarantineAddOptions {
51
+ issue?: string;
52
+ lastFailureRate?: number;
53
+ lastVerifiedAt?: string;
54
+ }
55
+ export interface StoreOptions {
56
+ workspace?: string;
57
+ }
58
+ export type HistoryScope = 'workspace' | 'all';
33
59
  export interface Store {
34
60
  appendHistory(entry: HistoryEntry): Promise<void>;
35
- listHistory(target: string | undefined, limit: number): Promise<HistoryEntry[]>;
61
+ listHistory(target: string | undefined, limit: number, scope?: HistoryScope): Promise<HistoryEntry[]>;
36
62
  loadQuarantine(): Promise<QuarantineDocument>;
37
- addQuarantine(refs: ParsedRef[], reason: string): Promise<{
63
+ addQuarantine(refs: ParsedRef[], reason: string, options?: QuarantineAddOptions): Promise<{
38
64
  added: QuarantineEntry[];
65
+ updated: QuarantineEntry[];
39
66
  file: string;
40
67
  }>;
41
68
  removeQuarantine(refs: ParsedRef[]): Promise<{
@@ -43,12 +70,64 @@ export interface Store {
43
70
  file: string;
44
71
  }>;
45
72
  quarantinePath: string;
73
+ historyPath?: string;
74
+ workspace?: string;
46
75
  }
47
76
  export interface ParsedRef {
48
77
  file: string;
49
78
  name: string | null;
50
79
  }
51
- export declare function createStore(dataDir: string, quarantineFile: string): Store;
80
+ export interface AnnotatableTest {
81
+ file: string;
82
+ name: string;
83
+ verdict: string;
84
+ failureRate?: number;
85
+ }
86
+ export interface QuarantineAnnotation<T extends AnnotatableTest = AnnotatableTest> {
87
+ newFlaky: T[];
88
+ alreadyQuarantinedFlaky: T[];
89
+ clearCandidates: QuarantineEntry[];
90
+ }
91
+ export interface TopFlakyTest {
92
+ file: string;
93
+ name: string;
94
+ occurrences: number;
95
+ avgFailureRate: number;
96
+ maxFailureRate: number;
97
+ lastSeen: string;
98
+ quarantined: boolean;
99
+ }
100
+ export interface StaleQuarantineEntry extends QuarantineEntry {
101
+ ageDays: number;
102
+ }
103
+ export interface StabilitySummary {
104
+ topFlakyTests: TopFlakyTest[];
105
+ staleQuarantined: StaleQuarantineEntry[];
106
+ }
107
+ export interface SummarizeStabilityOptions {
108
+ staleDays?: number;
109
+ topN?: number;
110
+ now?: Date;
111
+ }
112
+ /** 计算工作区稳定哈希,用于按工作区分文件存储历史。 */
113
+ export declare function workspaceHash(workspace: string): string;
114
+ /**
115
+ * 规范化隔离清单中的文件路径为 POSIX 相对路径;
116
+ * 拒绝工作区外的绝对路径与越界相对路径,避免把本机路径污染进 .flakefinder.json。
117
+ */
118
+ export declare function normalizeQuarantinePath(rawFile: string, workspace?: string): string;
119
+ export declare function createStore(dataDir: string, quarantineFile: string, options?: StoreOptions): Store;
120
+ /**
121
+ * 将本次检测结果中的用例与隔离清单交叉对照:
122
+ * - newFlaky: 本次新发现(尚未隔离)的 flaky 用例
123
+ * - alreadyQuarantinedFlaky: 已在隔离清单中且本次仍为 flaky 的用例
124
+ * - clearCandidates: 隔离清单中在本次运行全部稳定通过(stable-pass)的候选清理条目
125
+ */
126
+ export declare function annotateTestsWithQuarantine<T extends AnnotatableTest>(tests: readonly T[], quarantineDoc: QuarantineDocument): QuarantineAnnotation<T>;
127
+ /**
128
+ * 汇总历史与隔离清单的稳定性概览:高频 flaky 榜单 + 超期未复查的陈旧隔离条目。
129
+ */
130
+ export declare function summarizeStability(history: readonly HistoryEntry[], quarantineDoc: QuarantineDocument, options?: SummarizeStabilityOptions): StabilitySummary;
52
131
  /** 解析 "file.test.mjs" 或 "file.test.mjs > 用例名" 形式的引用。 */
53
132
  export declare function parseRef(raw: string): ParsedRef;
54
133
  /** 隔离清单条目的可读格式。 */