forgedock 1.60.1 → 1.61.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/bin/config-schema.mjs +44 -1
- package/bin/engine/runlog.mjs +52 -0
- package/bin/engine-cli.mjs +9 -4
- package/bin/env/bench.mjs +38 -0
- package/bin/env/cli.mjs +134 -0
- package/bin/env/env.mjs +339 -0
- package/bin/forgedock.mjs +32 -3
- package/bin/help-text.mjs +2 -0
- package/bin/lean/ci-budget.mjs +3 -1
- package/bin/lean/ci-classify.mjs +74 -0
- package/bin/lean/ci-classify.test.mjs +147 -0
- package/bin/lean/ci-emit.mjs +175 -0
- package/bin/lean/ci-emit.test.mjs +177 -0
- package/bin/lean/ci-preflight.mjs +183 -0
- package/bin/lean/ci-preflight.test.mjs +122 -0
- package/bin/lean/ci-runner-health.mjs +213 -0
- package/bin/lean/ci-runner-health.test.mjs +113 -0
- package/bin/lean/ci-watch.mjs +79 -0
- package/bin/lean/ci-watch.test.mjs +80 -0
- package/bin/lean/depcache.mjs +38 -8
- package/bin/lean/deploy-stages.mjs +514 -0
- package/bin/lean/deploy-stages.test.mjs +580 -0
- package/bin/lean/effects.mjs +50 -0
- package/bin/lean/execution.mjs +8 -1
- package/bin/lean/lean.mjs +38 -6
- package/bin/lean/lean.test.mjs +61 -0
- package/bin/lean/release-deploy.mjs +12 -6
- package/bin/lean/release-flakes.mjs +16 -0
- package/bin/lean/release-flakes.test.mjs +15 -0
- package/bin/lean/release-gates.mjs +24 -1
- package/bin/lean/release-ledger.mjs +21 -0
- package/bin/lean/release-minutes-timing.test.mjs +57 -0
- package/bin/lean/release-minutes.mjs +98 -0
- package/bin/lean/release-promote.mjs +444 -0
- package/bin/lean/release-promote.test.mjs +470 -0
- package/bin/lean/release-rollback.mjs +14 -6
- package/bin/lean/release.mjs +31 -2
- package/bin/lean/sandbox-remote.mjs +11 -3
- package/bin/lean/testengine-recall.mjs +82 -0
- package/bin/lean/testengine-recall.test.mjs +103 -0
- package/bin/lean/testengine-shard.mjs +150 -0
- package/bin/lean/testengine-shard.test.mjs +111 -0
- package/bin/lean/testengine.mjs +486 -0
- package/bin/lean/testengine.test.mjs +303 -0
- package/bin/lean/verify-settle.test.mjs +156 -0
- package/bin/lean/verify.mjs +98 -3
- package/bin/pool/agent.mjs +57 -6
- package/bin/pool/ci-events.mjs +183 -0
- package/bin/pool/ci-events.test.mjs +143 -0
- package/bin/pool/docker.mjs +7 -0
- package/bin/pool/lane-tools.mjs +1 -0
- package/bin/pool/router.mjs +18 -0
- package/bin/pool/warm.mjs +1 -1
- package/bin/stats/ci-awareness.mjs +66 -0
- package/bin/stats/index.mjs +44 -3
- package/bin/stats/release-ledger.test.mjs +226 -0
- package/bin/stats/release.mjs +365 -1
- package/bin/stats/stats.test.mjs +36 -0
- package/docs/CI.md +31 -0
- package/docs/CONFIG.md +235 -2
- package/docs/ENV-LIBRARY.md +172 -0
- package/docs/STATS.md +43 -0
- package/docs/ci-events.md +88 -0
- package/docs/test-engine.md +98 -0
- package/package.json +1 -1
- package/pool/README.md +1 -0
- package/pool/image/entrypoint.sh +15 -3
- package/pool/services/docker-compose.yml +53 -0
- package/pool/services/git-mirror.sh +22 -0
- package/templates/github-actions/forge-env/action.yml +65 -0
|
@@ -17,9 +17,12 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { execFileSync } from "node:child_process";
|
|
19
19
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
20
|
-
import {
|
|
20
|
+
import { homedir } from "node:os";
|
|
21
|
+
import { dirname, join } from "node:path";
|
|
22
|
+
import { mergeRemoteLog } from "../engine/runlog.mjs";
|
|
21
23
|
import { safeSegment } from "./ledger.mjs";
|
|
22
24
|
import { scopedEnv } from "./execution.mjs";
|
|
25
|
+
import { laneEnvFor, readEnvSnapshots } from "../env/env.mjs";
|
|
23
26
|
import { resolveCredential } from "./credentials.mjs";
|
|
24
27
|
import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
|
|
25
28
|
|
|
@@ -222,14 +225,16 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
222
225
|
const resultFile = `/result/${issue}.json`;
|
|
223
226
|
const relayEnv = relays.length ? { CS_RELAY_COMMANDS: relayCommandNames(relay).join(","), CS_RELAY_CAPS: relays.join(","), ...(await prefetchEnv(issue)) } : {};
|
|
224
227
|
const warm = Number.isInteger(settings.warmSandboxes) && settings.warmSandboxes > 0 ? settings.warmSandboxes : 0;
|
|
228
|
+
const envSnap = settings.forgeYaml ? readEnvSnapshots(settings.forgeYaml) : null; // env.snapshots: off unless enabled
|
|
225
229
|
const spec = {
|
|
226
230
|
id, issue, batch: batch.id, image: settings.image ?? null,
|
|
227
231
|
repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
|
|
228
232
|
...(settings.laneTools?.length ? { lane_tools: settings.laneTools } : {}), // #5650: per-repo lane image
|
|
233
|
+
...(envSnap?.enabled ? { env_snapshots: { enabled: true, ready: envSnap.ready, keep: envSnap.keep, max_age_days: envSnap.maxAgeDays } } : {}), // the agent builds and stages snapshots outside the lane
|
|
229
234
|
...(warm ? { warm } : {}), // #4912: the pool agent keeps this many warm sandboxes for the repo
|
|
230
235
|
cache: settings.cacheStore ? { store: settings.cacheStore, key: safeSegment(String(repo ?? "repo")) } : null,
|
|
231
236
|
// The host's git identity: without it the lane image falls back to a placeholder author that fails DCO.
|
|
232
|
-
env: { ...gitIdentityEnv(gitIdentity(), laneEnv ?? {}), ...scopedEnv({ env: resolved, secrets, batchId: batch.id, repo }), ...(settings.forgeYaml ? { CS_FORGE_YAML_B64: Buffer.from(settings.forgeYaml).toString("base64") } : {}), ...relayEnv }, // #4546: the dispatcher's forge.yaml (gitignored in the repo)
|
|
237
|
+
env: { ...gitIdentityEnv(gitIdentity(), laneEnv ?? {}), ...scopedEnv({ env: resolved, secrets, batchId: batch.id, repo }), ...(settings.forgeYaml ? { CS_FORGE_YAML_B64: Buffer.from(settings.forgeYaml).toString("base64") } : {}), ...relayEnv, ...laneEnvFor(envSnap, settings.laneTools ?? []) }, // #4546: the dispatcher's forge.yaml (gitignored in the repo)
|
|
233
238
|
command: ["forgedock", "run-issue", String(issue), ...args, "--result-file", resultFile], result_file: resultFile,
|
|
234
239
|
};
|
|
235
240
|
const startedAt = now();
|
|
@@ -250,7 +255,10 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
250
255
|
async fetchResult(h) {
|
|
251
256
|
const r = await transport.result(h.id);
|
|
252
257
|
if (r) { await pullLogs(h); await minutesOf(h); }
|
|
253
|
-
|
|
258
|
+
if (!r) return null;
|
|
259
|
+
const { runLog, ...rest } = r; // #5697: the lane's run log goes to the host run log, not into the result
|
|
260
|
+
if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
|
|
261
|
+
return rest;
|
|
254
262
|
},
|
|
255
263
|
async capacity() {
|
|
256
264
|
// #5048: no capacity() is unknown (null); a transport error propagates, so the caller can report the pool down
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Test engine, shadow recall ledger and graduation (#5710, Forge CI W3).
|
|
5
|
+
* One JSONL record per CI run: what the selection would have run and which failing tests fell outside it. Only a run of
|
|
6
|
+
* the full suite (`ran: "all"`: shadow, nightly, release) can measure recall; an enforced run is neutral. Selection may
|
|
7
|
+
* skip tests only after `after` consecutive measured runs with 100% failure recall under the current selection config,
|
|
8
|
+
* at least `minFailing` of them a subset selection that caught a real failure (a streak of green runs proves nothing).
|
|
9
|
+
* A miss, an unattributable failure or a selection-config change restarts the count, also after graduation.
|
|
10
|
+
* The ledger is a cache-shaped local file (default outside the checkout); flaky tests are read from it through
|
|
11
|
+
* `release-flakes.mjs` (same-sha fail -> pass flips).
|
|
12
|
+
*/
|
|
13
|
+
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
14
|
+
import { dirname } from "node:path";
|
|
15
|
+
import { detectSameShaFlip, flakeEntry, quarantineReport } from "./release-flakes.mjs";
|
|
16
|
+
|
|
17
|
+
const arr = (v) => (Array.isArray(v) ? v.map(String) : []);
|
|
18
|
+
|
|
19
|
+
/** Ledger records of `file`, oldest first ([] when absent; a torn or foreign line is skipped). */
|
|
20
|
+
export function readLedger(file) {
|
|
21
|
+
let text = "";
|
|
22
|
+
try { text = readFileSync(file, "utf8"); } catch { return []; }
|
|
23
|
+
return text.split("\n").flatMap((l) => { try { const e = JSON.parse(l); return e && typeof e === "object" && e.v === 1 ? [e] : []; } catch { return []; } });
|
|
24
|
+
}
|
|
25
|
+
export function appendLedger(file, entry) {
|
|
26
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
27
|
+
appendFileSync(file, `${JSON.stringify(entry)}\n`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The record of one run. `failed` = failing test files (or `@suite` names); `unattributed` = failures no test file could be
|
|
32
|
+
* named for, which count as a miss unless everything was selected.
|
|
33
|
+
*/
|
|
34
|
+
export function recallEntry({ selection, ran = "all", config, failed = [], unattributed = [], sha = "", runId = null, event = null, now = Date.now() }) {
|
|
35
|
+
const inside = new Set([...arr(selection.tests), ...arr(selection.suites)]);
|
|
36
|
+
const fails = [...new Set(arr(failed))].sort(), loose = [...new Set(arr(unattributed))];
|
|
37
|
+
const everything = selection.mode === "all";
|
|
38
|
+
const missed = everything ? [] : fails.filter((f) => !inside.has(f));
|
|
39
|
+
return {
|
|
40
|
+
v: 1, at: new Date(now).toISOString(), sha, run_id: runId === null ? null : String(runId), event, ran, config,
|
|
41
|
+
mode: selection.mode, selected: arr(selection.tests).length, total: Number(selection.total) || 0,
|
|
42
|
+
failed: fails, missed, unattributed: everything ? [] : loose, ok: missed.length === 0 && (everything || loose.length === 0),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Graduation state of the ledger under the current selection config.
|
|
48
|
+
* @returns {{graduated: boolean, streak: number, needed: number, caught: number, min_failing: number, last_miss: object|null, why: string}}
|
|
49
|
+
*/
|
|
50
|
+
export function graduation(entries, { after = 50, minFailing = 1, config }) {
|
|
51
|
+
let streak = 0, caught = 0, lastMiss = null, stale = false;
|
|
52
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
53
|
+
const e = entries[i];
|
|
54
|
+
if (e.ran !== "all") continue;
|
|
55
|
+
if (e.config !== config) { stale = true; break; }
|
|
56
|
+
if (!e.ok) { lastMiss = e; break; }
|
|
57
|
+
streak++;
|
|
58
|
+
if (e.mode === "subset" && e.failed.length) caught++;
|
|
59
|
+
}
|
|
60
|
+
const graduated = streak >= after && caught >= minFailing;
|
|
61
|
+
const why = graduated ? `graduated: ${streak} consecutive full runs with 100% failure recall (${caught} caught a failure inside a subset selection)`
|
|
62
|
+
: streak < after ? `${streak} of ${after} consecutive full runs with 100% failure recall${lastMiss ? " since the last miss" : stale ? " since the selection config changed" : ""}`
|
|
63
|
+
: `${streak} consecutive runs recalled, but only ${caught} of the ${minFailing} required caught a failure inside a subset selection`;
|
|
64
|
+
return { graduated, streak, needed: after, caught, min_failing: minFailing, last_miss: lastMiss, why };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Flake entries (`release-flakes.mjs` shape) from the ledger: a test file that failed and later passed on one sha, full runs only. */
|
|
68
|
+
export function flakesFromLedger(entries) {
|
|
69
|
+
const full = entries.filter((e) => e.ran === "all" && e.sha);
|
|
70
|
+
const failedOn = new Map(), lastAt = new Map();
|
|
71
|
+
for (const e of full) {
|
|
72
|
+
const s = failedOn.get(e.sha) ?? failedOn.set(e.sha, new Set()).get(e.sha);
|
|
73
|
+
for (const f of e.failed) s.add(f);
|
|
74
|
+
lastAt.set(e.sha, e.at);
|
|
75
|
+
}
|
|
76
|
+
const runs = full.flatMap((e, i) => [...failedOn.get(e.sha)].map((test) => ({ sha: e.sha, check: "tests", test, conclusion: e.failed.includes(test) ? "failure" : "success", id: e.run_id ?? `#${i}`, at: e.at })));
|
|
77
|
+
return detectSameShaFlip(runs).map((f) => flakeEntry({ check: f.check, test: f.test, kind: "flip", sha: f.sha, runIds: f.run_ids, at: lastAt.get(f.sha) }));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Quarantine report for `ci.tests.quarantine` (off | report | non-blocking) from the ledger's flips. */
|
|
81
|
+
export const quarantineFromLedger = (entries, cfg, now = Date.now()) =>
|
|
82
|
+
quarantineReport(flakesFromLedger(entries), { mode: cfg.quarantine, quarantineAfter: cfg.quarantineAfter, windowDays: cfg.quarantineWindowDays }, now);
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { writeFileSync, appendFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { readLedger, appendLedger, recallEntry, graduation, flakesFromLedger, quarantineFromLedger } from "./testengine-recall.mjs";
|
|
9
|
+
|
|
10
|
+
const NOW = Date.parse("2026-11-15T00:00:00Z"), DAY = 86_400_000;
|
|
11
|
+
const subset = { mode: "subset", tests: ["t/a.test.js", "t/b.test.js"], suites: ["@e2e"], total: 5 };
|
|
12
|
+
const everything = { mode: "all", tests: ["t/a.test.js", "t/b.test.js", "t/c.test.js"], suites: [], total: 3 };
|
|
13
|
+
const entry = (o = {}) => recallEntry({ selection: subset, config: "c1", sha: "s", now: NOW, ...o });
|
|
14
|
+
const many = (n, o) => Array.from({ length: n }, () => entry(o));
|
|
15
|
+
|
|
16
|
+
describe("recallEntry", () => {
|
|
17
|
+
it("is ok when every failing test is inside the selection", () => {
|
|
18
|
+
const e = entry({ failed: ["t/b.test.js", "@e2e", "t/b.test.js"], runId: 7, event: "pull_request" });
|
|
19
|
+
assert.deepEqual(e, { v: 1, at: "2026-11-15T00:00:00.000Z", sha: "s", run_id: "7", event: "pull_request", ran: "all", config: "c1", mode: "subset", selected: 2, total: 5, failed: ["@e2e", "t/b.test.js"], missed: [], unattributed: [], ok: true });
|
|
20
|
+
});
|
|
21
|
+
it("records a failure outside the selection as a miss", () => {
|
|
22
|
+
const e = entry({ failed: ["t/a.test.js", "t/c.test.js"] });
|
|
23
|
+
assert.deepEqual([e.ok, e.missed], [false, ["t/c.test.js"]]);
|
|
24
|
+
});
|
|
25
|
+
it("counts an unattributable failure as a miss, unless everything was selected", () => {
|
|
26
|
+
assert.equal(entry({ unattributed: ["some test"] }).ok, false);
|
|
27
|
+
const e = recallEntry({ selection: everything, config: "c1", failed: ["t/zzz.test.js"], unattributed: ["x"], now: NOW });
|
|
28
|
+
assert.deepEqual([e.ok, e.missed, e.unattributed], [true, [], []]);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe("graduation", () => {
|
|
33
|
+
const opts = { after: 50, minFailing: 1, config: "c1" };
|
|
34
|
+
it("needs `after` consecutive measured runs", () => {
|
|
35
|
+
const g = graduation(many(49, { failed: ["t/a.test.js"] }), opts);
|
|
36
|
+
assert.deepEqual([g.graduated, g.streak, g.needed], [false, 49, 50]);
|
|
37
|
+
assert.match(g.why, /49 of 50 consecutive full runs/);
|
|
38
|
+
assert.equal(graduation(many(50, { failed: ["t/a.test.js"] }), opts).graduated, true);
|
|
39
|
+
assert.deepEqual(graduation([], opts).streak, 0);
|
|
40
|
+
});
|
|
41
|
+
it("a streak of green runs does not graduate until a subset selection caught a failure", () => {
|
|
42
|
+
const g = graduation(many(60), opts);
|
|
43
|
+
assert.deepEqual([g.graduated, g.streak, g.caught], [false, 60, 0]);
|
|
44
|
+
assert.match(g.why, /only 0 of the 1 required/);
|
|
45
|
+
assert.equal(graduation([...many(60), entry({ failed: ["t/a.test.js"] })], opts).graduated, true);
|
|
46
|
+
assert.equal(graduation(many(60), { ...opts, minFailing: 0 }).graduated, true);
|
|
47
|
+
const allMode = Array.from({ length: 60 }, () => recallEntry({ selection: everything, config: "c1", failed: ["t/a.test.js"], now: NOW }));
|
|
48
|
+
assert.equal(graduation(allMode, opts).graduated, false, "a failure caught by run-everything proves nothing about the selection");
|
|
49
|
+
});
|
|
50
|
+
it("a miss restarts the count, also after graduation", () => {
|
|
51
|
+
const ok = many(50, { failed: ["t/a.test.js"] });
|
|
52
|
+
const g = graduation([...ok, entry({ failed: ["t/c.test.js"], sha: "bad" }), ...many(3)], opts);
|
|
53
|
+
assert.deepEqual([g.graduated, g.streak, g.last_miss.sha], [false, 3, "bad"]);
|
|
54
|
+
assert.match(g.why, /since the last miss/);
|
|
55
|
+
});
|
|
56
|
+
it("a selection-config change restarts the count", () => {
|
|
57
|
+
const g = graduation([...many(50, { failed: ["t/a.test.js"] }), ...many(2, { config: "c2" })], { ...opts, config: "c2" });
|
|
58
|
+
assert.deepEqual([g.graduated, g.streak], [false, 2]);
|
|
59
|
+
assert.match(g.why, /since the selection config changed/);
|
|
60
|
+
});
|
|
61
|
+
it("an enforced run is neutral: it neither counts nor breaks the streak", () => {
|
|
62
|
+
const g = graduation([...many(50, { failed: ["t/a.test.js"] }), ...many(5, { ran: "selection", failed: ["t/c.test.js"] })], opts);
|
|
63
|
+
assert.deepEqual([g.graduated, g.streak], [true, 50]);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("ledger file", () => {
|
|
68
|
+
it("appends and reads back, skipping torn lines", () => {
|
|
69
|
+
const f = join(tmpDir("recall-"), "deep", "recall.jsonl");
|
|
70
|
+
assert.deepEqual(readLedger(f), []);
|
|
71
|
+
appendLedger(f, entry()); appendFileSync(f, '{"v":1,"at"\n{"other":true}\n'); appendLedger(f, entry({ sha: "t" }));
|
|
72
|
+
assert.deepEqual(readLedger(f).map((e) => e.sha), ["s", "t"]);
|
|
73
|
+
writeFileSync(f, "");
|
|
74
|
+
assert.deepEqual(readLedger(f), []);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("flaky quarantine from the ledger", () => {
|
|
79
|
+
const at = (d) => NOW - d * DAY;
|
|
80
|
+
const flip = (sha, d, test = "t/a.test.js") => [entry({ sha, failed: [test], runId: `${sha}-1`, now: at(d) }), entry({ sha, failed: [], runId: `${sha}-2`, now: at(d) + 1000 })];
|
|
81
|
+
const cfg = { quarantine: "report", quarantineAfter: 3, quarantineWindowDays: 14 };
|
|
82
|
+
it("a test that failed and then passed on one sha is a flip; a consistent failure is not", () => {
|
|
83
|
+
const f = flakesFromLedger([...flip("s1", 1), entry({ sha: "s2", failed: ["t/b.test.js"] }), entry({ sha: "s2", failed: ["t/b.test.js"] })]);
|
|
84
|
+
assert.deepEqual(f.map((x) => [x.check, x.test, x.kind, x.sha, x.run_ids]), [["tests", "t/a.test.js", "flip", "s1", ["s1-1", "s1-2"]]]);
|
|
85
|
+
});
|
|
86
|
+
it("ignores enforced runs (a test that was not run did not pass)", () => {
|
|
87
|
+
assert.deepEqual(flakesFromLedger([entry({ sha: "s1", failed: ["t/a.test.js"] }), entry({ sha: "s1", ran: "selection" })]), []);
|
|
88
|
+
});
|
|
89
|
+
it("reports a test that flipped K times in the window, blocking by default", () => {
|
|
90
|
+
const entries = [...flip("s1", 1), ...flip("s2", 2), ...flip("s3", 3), ...flip("s4", 1, "t/b.test.js")];
|
|
91
|
+
const q = quarantineFromLedger(entries, cfg, NOW);
|
|
92
|
+
assert.deepEqual(q.map((x) => [x.target, x.count, x.blocking]), [["tests:t/a.test.js", 3, true]]);
|
|
93
|
+
assert.match(q[0].why, /report only/);
|
|
94
|
+
assert.deepEqual(quarantineFromLedger([...flip("s1", 1), ...flip("s2", 2), ...flip("s3", 20)], cfg, NOW), [], "outside the window");
|
|
95
|
+
});
|
|
96
|
+
it("non-blocking only by opt-in, never for an unskippable class, and off reports nothing", () => {
|
|
97
|
+
const entries = [...flip("s1", 1), ...flip("s2", 2), ...flip("s3", 3), ...flip("m1", 1, "tests/migration/test_up.py"), ...flip("m2", 2, "tests/migration/test_up.py"), ...flip("m3", 3, "tests/migration/test_up.py")];
|
|
98
|
+
const q = quarantineFromLedger(entries, { ...cfg, quarantine: "non-blocking" }, NOW);
|
|
99
|
+
assert.deepEqual(q.map((x) => [x.test, x.blocking]), [["t/a.test.js", false], ["tests/migration/test_up.py", true]]);
|
|
100
|
+
assert.match(q[1].why, /unskippable/);
|
|
101
|
+
assert.deepEqual(quarantineFromLedger(entries, { ...cfg, quarantine: "off" }, NOW), []);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Test engine, reports and sharding (#5710, Forge CI W3). Pure: text in, records and plans out.
|
|
5
|
+
* - `parseReport` reads JUnit XML, TAP (`node --test` flavour: nested subtests, YAML `duration_ms` / `location`) or a
|
|
6
|
+
* `{file: seconds}` JSON map into one record per test case: {file, name, status, seconds}.
|
|
7
|
+
* - `fileDurations` / `failedFiles` attribute records to the repo's known test files (path suffix, or a dotted pytest
|
|
8
|
+
* classname). A failure nothing attributes is reported as `unattributed`, never dropped.
|
|
9
|
+
* - `planShards` is greedy LPT (longest processing time first onto the least-loaded shard). A file without a recorded
|
|
10
|
+
* duration gets the median of the known ones; with no history at all every file weighs 1, which is the file-count split.
|
|
11
|
+
*/
|
|
12
|
+
const xml = (s) => String(s).replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&/g, "&");
|
|
13
|
+
const attrs = (s) => Object.fromEntries([...String(s).matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)].map((m) => [m[1], xml(m[2] ?? m[3] ?? "")]));
|
|
14
|
+
const secs = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; };
|
|
15
|
+
const pathLike = (s) => /[/\\]/.test(String(s ?? "")) || /\.(py|[cm]?[jt]sx?)$/.test(String(s ?? ""));
|
|
16
|
+
|
|
17
|
+
/** JUnit XML -> records. The file is `file=` of the case or its suite, else a path-like classname or suite name, else the classname. */
|
|
18
|
+
export function parseJunit(text) {
|
|
19
|
+
const out = [], suites = [];
|
|
20
|
+
let cur = null;
|
|
21
|
+
const close = () => { if (cur) { out.push(cur); cur = null; } };
|
|
22
|
+
for (const m of String(text).matchAll(/<(\/?)(testsuite|testcase|failure|error|skipped)\b((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g)) {
|
|
23
|
+
const [, end, tag, raw, selfClose] = m;
|
|
24
|
+
if (tag === "testsuite") { close(); if (end) suites.pop(); else if (!selfClose) suites.push(attrs(raw)); continue; }
|
|
25
|
+
if (tag === "testcase") {
|
|
26
|
+
close();
|
|
27
|
+
if (end) continue;
|
|
28
|
+
const a = attrs(raw), suite = suites.at(-1) ?? {};
|
|
29
|
+
const file = a.file || suite.file || (pathLike(a.classname) ? a.classname : pathLike(suite.name) ? suite.name : a.classname || suite.name || "");
|
|
30
|
+
cur = { file, name: a.name ?? "", status: "pass", seconds: secs(a.time) };
|
|
31
|
+
if (selfClose) close();
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (cur && !end) cur.status = tag === "skipped" ? (cur.status === "fail" ? "fail" : "skip") : "fail";
|
|
35
|
+
}
|
|
36
|
+
close();
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** TAP -> records, one per leaf test point. A point that closes nested subtests is a suite: not counted, but its file is passed down. */
|
|
41
|
+
export function parseTap(text) {
|
|
42
|
+
const out = [];
|
|
43
|
+
let last = null; // the point whose YAML block may follow
|
|
44
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
45
|
+
const p = /^(\s*)(not ok|ok)\b(?:\s+\d+)?(?:\s+-)?\s*(.*)$/.exec(line);
|
|
46
|
+
if (p) {
|
|
47
|
+
const indent = p[1].length, directive = /#\s*(skip|todo)\b/i.exec(p[3])?.[1];
|
|
48
|
+
// node prints the subtests first and their parent point after them, one level out
|
|
49
|
+
const children = out.filter((r) => r.open && r.indent > indent);
|
|
50
|
+
for (const r of children) r.open = false;
|
|
51
|
+
last = { file: "", name: p[3].replace(/\s+#\s*(skip|todo)\b.*$/i, "").trim(), status: directive ? "skip" : p[2] === "ok" ? "pass" : "fail", seconds: 0, indent, open: true, children };
|
|
52
|
+
out.push(last);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!last) continue;
|
|
56
|
+
if (/^\s*\.\.\.\s*$/.test(line)) { last = null; continue; }
|
|
57
|
+
const y = /^\s*(duration_ms|location|file):\s*(.*)$/.exec(line);
|
|
58
|
+
if (!y) continue;
|
|
59
|
+
const v = y[2].replace(/^['"]|['"]$/g, "");
|
|
60
|
+
if (y[1] === "duration_ms") last.seconds = secs(Number(v) / 1000);
|
|
61
|
+
else if (y[1] === "file") last.file = v;
|
|
62
|
+
else last.file = v.replace(/^file:\/\//, "").replace(/:\d+(:\d+)?$/, "");
|
|
63
|
+
}
|
|
64
|
+
for (const r of [...out].reverse()) { if (!r.file && pathLike(r.name)) r.file = r.name; if (r.file) for (const c of r.children) c.file ||= r.file; }
|
|
65
|
+
return out.filter((r) => !r.children.length).map(({ file, name, status, seconds }) => ({ file, name, status, seconds }));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Any supported report text -> records (format by content). */
|
|
69
|
+
export function parseReport(text) {
|
|
70
|
+
const t = String(text ?? "");
|
|
71
|
+
if (/^\s*</.test(t)) return parseJunit(t);
|
|
72
|
+
if (/^\s*\{/.test(t)) {
|
|
73
|
+
try { return Object.entries(JSON.parse(t)).filter(([, v]) => typeof v === "number").map(([file, v]) => ({ file, name: "", status: "pass", seconds: secs(v) })); } catch { return []; }
|
|
74
|
+
}
|
|
75
|
+
return parseTap(t);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The known test file a report's `file` value names: exact, a path suffix either way, or a dotted pytest classname. Null unless unique. */
|
|
79
|
+
export function attributeFile(raw, known) {
|
|
80
|
+
const v = String(raw ?? "").replace(/\\/g, "/").replace(/^\.\//, "");
|
|
81
|
+
if (!v) return null;
|
|
82
|
+
const one = (hits) => (hits.length === 1 ? hits[0] : null);
|
|
83
|
+
if (known.includes(v)) return v;
|
|
84
|
+
const suffix = one(known.filter((k) => v.endsWith(`/${k}`) || k.endsWith(`/${v}`)));
|
|
85
|
+
if (suffix) return suffix;
|
|
86
|
+
if (/^[\w.]+$/.test(v)) {
|
|
87
|
+
const parts = v.split(".");
|
|
88
|
+
for (let k = parts.length; k >= 1; k--) {
|
|
89
|
+
const p = `${parts.slice(0, k).join("/")}.py`;
|
|
90
|
+
const hit = known.includes(p) ? p : one(known.filter((f) => f.endsWith(`/${p}`)));
|
|
91
|
+
if (hit) return hit;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Seconds per known test file (sum of its cases); files with no attributed record are absent. */
|
|
98
|
+
export function fileDurations(records, known) {
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const r of records) { const f = attributeFile(r.file, known); if (f && r.seconds > 0) out[f] = (out[f] ?? 0) + r.seconds; }
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Failing test files of a run, plus the failures no known file could be attributed to (`name` or the raw file value). */
|
|
105
|
+
export function failedFiles(records, known) {
|
|
106
|
+
const failed = new Set(), unattributed = [];
|
|
107
|
+
for (const r of records) {
|
|
108
|
+
if (r.status !== "fail") continue;
|
|
109
|
+
const f = attributeFile(r.file, known);
|
|
110
|
+
if (f) failed.add(f); else unattributed.push(r.file || r.name || "(unnamed test)");
|
|
111
|
+
}
|
|
112
|
+
return { failed: [...failed].sort(), unattributed: [...new Set(unattributed)] };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const round = (n) => Math.round(n * 10) / 10;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Split `files` across shards by recorded duration, greedy LPT.
|
|
119
|
+
* @param {{files: string[], durations?: Record<string, number>, shards?: number, targetS?: number, maxShards?: number}} p
|
|
120
|
+
* `shards` wins; else the count comes from `targetS` (ceil(total / target), capped by `maxShards` and the file count); else 1.
|
|
121
|
+
* @returns {{shards: {index, files, est_s}[], matrix: {include: {shard, total, files}[]}, source: "durations"|"file-count",
|
|
122
|
+
* known: number, est_total_s: number, est_max_s: number, target_s: number, oversize: {file, s}[]}}
|
|
123
|
+
*/
|
|
124
|
+
export function planShards({ files, durations = {}, shards = 0, targetS = 0, maxShards = 0 }) {
|
|
125
|
+
const list = [...new Set(files)].sort();
|
|
126
|
+
const known = list.filter((f) => durations[f] > 0);
|
|
127
|
+
const sorted = known.map((f) => durations[f]).sort((a, b) => a - b);
|
|
128
|
+
const median = sorted.length ? sorted[Math.floor((sorted.length - 1) / 2)] : 1;
|
|
129
|
+
const weight = (f) => (durations[f] > 0 ? durations[f] : median);
|
|
130
|
+
const total = list.reduce((s, f) => s + weight(f), 0);
|
|
131
|
+
let n = shards > 0 ? Math.floor(shards) : targetS > 0 ? Math.ceil(total / targetS) : 1;
|
|
132
|
+
if (maxShards > 0) n = Math.min(n, Math.floor(maxShards));
|
|
133
|
+
n = Math.max(1, Math.min(n, list.length || 1));
|
|
134
|
+
const bins = Array.from({ length: n }, (_, i) => ({ index: i + 1, files: [], est_s: 0 }));
|
|
135
|
+
for (const f of [...list].sort((a, b) => weight(b) - weight(a) || (a < b ? -1 : 1))) {
|
|
136
|
+
const bin = bins.reduce((best, b) => (b.est_s < best.est_s ? b : best));
|
|
137
|
+
bin.files.push(f); bin.est_s += weight(f);
|
|
138
|
+
}
|
|
139
|
+
for (const b of bins) { b.files.sort(); b.est_s = round(b.est_s); }
|
|
140
|
+
return {
|
|
141
|
+
shards: bins,
|
|
142
|
+
matrix: { include: bins.map((b) => ({ shard: b.index, total: n, files: b.files.join(" ") })) },
|
|
143
|
+
source: known.length ? "durations" : "file-count",
|
|
144
|
+
known: known.length,
|
|
145
|
+
est_total_s: round(total),
|
|
146
|
+
est_max_s: Math.max(0, ...bins.map((b) => b.est_s)),
|
|
147
|
+
target_s: targetS,
|
|
148
|
+
oversize: targetS > 0 ? known.filter((f) => durations[f] > targetS).map((f) => ({ file: f, s: round(durations[f]) })) : [],
|
|
149
|
+
};
|
|
150
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { parseJunit, parseTap, parseReport, attributeFile, fileDurations, failedFiles, planShards } from "./testengine-shard.mjs";
|
|
9
|
+
|
|
10
|
+
const rep = (n) => readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "tests", "fixtures", "testengine", "reports", n), "utf8");
|
|
11
|
+
const PY = ["tests/integration/test_checkout.py", "tests/unit/test_pricing.py", "tests/unit/test_tax.py"];
|
|
12
|
+
const JS = ["test/cart.test.js", "test/math.test.js", "web/__tests__/button.tsx"];
|
|
13
|
+
|
|
14
|
+
describe("parseJunit", () => {
|
|
15
|
+
it("reads pytest cases: status, seconds, decoded names", () => {
|
|
16
|
+
const r = parseJunit(rep("pytest-junit.xml"));
|
|
17
|
+
assert.deepEqual(r.map((c) => [c.file, c.status, c.seconds]), [
|
|
18
|
+
["tests.unit.test_pricing", "pass", 0.25], ["tests.unit.test_tax", "fail", 1], ["tests.unit.test_tax", "skip", 0.5],
|
|
19
|
+
["tests.integration.test_checkout.TestCheckout", "pass", 1.5], ["tests.gone.test_removed", "fail", 0.25],
|
|
20
|
+
]);
|
|
21
|
+
});
|
|
22
|
+
it("reads vitest/jest cases: file from the classname or the suite name", () => {
|
|
23
|
+
const r = parseJunit(rep("vitest-junit.xml"));
|
|
24
|
+
assert.deepEqual(r.map((c) => [c.file, c.name, c.status]), [["test/cart.test.js", "cart > total", "fail"], ["test/cart.test.js", "cart > empty", "pass"], ["/work/repo/test/math.test.js", "add", "pass"]]);
|
|
25
|
+
});
|
|
26
|
+
it("prefers a file attribute and survives `>` inside attribute values", () => {
|
|
27
|
+
const r = parseJunit('<testsuite name="s" file="a/b_test.py"><testcase name="x > y" classname="K" time="2"/><testcase name="z" file="c/test_d.py"><error/></testcase></testsuite>');
|
|
28
|
+
assert.deepEqual(r, [{ file: "a/b_test.py", name: "x > y", status: "pass", seconds: 2 }, { file: "c/test_d.py", name: "z", status: "fail", seconds: 0 }]);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe("parseTap", () => {
|
|
33
|
+
it("counts leaf tests of node --test output once, passing a suite's file down", () => {
|
|
34
|
+
const r = parseTap(rep("node-test.tap"));
|
|
35
|
+
assert.deepEqual(r, [
|
|
36
|
+
{ file: "/work/repo/test/math.test.js", name: "one", status: "pass", seconds: 0.0015 },
|
|
37
|
+
{ file: "/work/repo/test/math.test.js", name: "two <bad>", status: "fail", seconds: 0.0025 },
|
|
38
|
+
{ file: "", name: "top", status: "pass", seconds: 0.00025 },
|
|
39
|
+
{ file: "", name: "later", status: "skip", seconds: 0 },
|
|
40
|
+
]);
|
|
41
|
+
});
|
|
42
|
+
it("takes a path-like test name as the file (per-file TAP)", () => {
|
|
43
|
+
assert.deepEqual(parseTap("ok 1 - test/a.test.js\n ---\n duration_ms: 1500\n ...\nnot ok 2 - test/b.test.js\n"), [
|
|
44
|
+
{ file: "test/a.test.js", name: "test/a.test.js", status: "pass", seconds: 1.5 }, { file: "test/b.test.js", name: "test/b.test.js", status: "fail", seconds: 0 },
|
|
45
|
+
]);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe("parseReport", () => {
|
|
50
|
+
it("picks the format by content", () => {
|
|
51
|
+
assert.equal(parseReport(rep("pytest-junit.xml")).length, 5);
|
|
52
|
+
assert.equal(parseReport(rep("node-test.tap")).length, 4);
|
|
53
|
+
assert.deepEqual(parseReport('{"test/a.test.js": 2.5, "note": "x"}'), [{ file: "test/a.test.js", name: "", status: "pass", seconds: 2.5 }]);
|
|
54
|
+
assert.deepEqual(parseReport("{broken"), []);
|
|
55
|
+
assert.deepEqual(parseReport(""), []);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe("attribution", () => {
|
|
60
|
+
it("maps report values to known test files, and never guesses between two", () => {
|
|
61
|
+
assert.equal(attributeFile("test/math.test.js", JS), "test/math.test.js");
|
|
62
|
+
assert.equal(attributeFile("/work/repo/test/math.test.js", JS), "test/math.test.js");
|
|
63
|
+
assert.equal(attributeFile("./test/math.test.js", JS), "test/math.test.js");
|
|
64
|
+
assert.equal(attributeFile("tests.unit.test_tax", PY), "tests/unit/test_tax.py");
|
|
65
|
+
assert.equal(attributeFile("tests.integration.test_checkout.TestCheckout", PY), "tests/integration/test_checkout.py");
|
|
66
|
+
assert.equal(attributeFile("unit.test_tax", PY), "tests/unit/test_tax.py");
|
|
67
|
+
assert.equal(attributeFile("test_x", ["a/test_x.py", "b/test_x.py"]), null);
|
|
68
|
+
assert.equal(attributeFile("tests.gone.test_removed", PY), null);
|
|
69
|
+
assert.equal(attributeFile("", PY), null);
|
|
70
|
+
});
|
|
71
|
+
it("sums seconds per file and lists failing files plus unattributed failures", () => {
|
|
72
|
+
const r = parseReport(rep("pytest-junit.xml"));
|
|
73
|
+
assert.deepEqual(fileDurations(r, PY), { "tests/unit/test_pricing.py": 0.25, "tests/unit/test_tax.py": 1.5, "tests/integration/test_checkout.py": 1.5 });
|
|
74
|
+
assert.deepEqual(failedFiles(r, PY), { failed: ["tests/unit/test_tax.py"], unattributed: ["tests.gone.test_removed"] });
|
|
75
|
+
assert.deepEqual(failedFiles(parseReport(rep("node-test.tap")), JS), { failed: ["test/math.test.js"], unattributed: [] });
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
describe("planShards", () => {
|
|
80
|
+
const files = ["a", "b", "c", "d", "e", "f"];
|
|
81
|
+
it("is greedy LPT over recorded durations", () => {
|
|
82
|
+
const p = planShards({ files, durations: { a: 10, b: 8, c: 7, d: 3, e: 2, f: 1 }, shards: 2 });
|
|
83
|
+
assert.deepEqual(p.shards.map((s) => [s.index, s.files, s.est_s]), [[1, ["a", "d", "e", "f"], 16], [2, ["b", "c"], 15]]);
|
|
84
|
+
assert.deepEqual([p.source, p.known, p.est_total_s, p.est_max_s], ["durations", 6, 31, 16]);
|
|
85
|
+
assert.deepEqual(p.matrix, { include: [{ shard: 1, total: 2, files: "a d e f" }, { shard: 2, total: 2, files: "b c" }] });
|
|
86
|
+
});
|
|
87
|
+
it("falls back to file count without history", () => {
|
|
88
|
+
const p = planShards({ files, shards: 3 });
|
|
89
|
+
assert.equal(p.source, "file-count");
|
|
90
|
+
assert.deepEqual(p.shards.map((s) => s.files.length), [2, 2, 2]);
|
|
91
|
+
});
|
|
92
|
+
it("gives a file without history the median of the known ones", () => {
|
|
93
|
+
const p = planShards({ files: ["a", "b", "new"], durations: { a: 10, b: 2 }, shards: 2 });
|
|
94
|
+
assert.equal(p.est_total_s, 14);
|
|
95
|
+
assert.equal(p.known, 2);
|
|
96
|
+
});
|
|
97
|
+
it("derives the shard count from a target, capped, and reports files no split can shorten", () => {
|
|
98
|
+
const d = { a: 600, b: 100, c: 100, d: 100, e: 50, f: 50 };
|
|
99
|
+
const p = planShards({ files, durations: d, targetS: 240 });
|
|
100
|
+
assert.equal(p.shards.length, 5);
|
|
101
|
+
assert.deepEqual(p.oversize, [{ file: "a", s: 600 }]);
|
|
102
|
+
assert.equal(p.est_max_s, 600);
|
|
103
|
+
assert.equal(planShards({ files, durations: d, targetS: 240, maxShards: 3 }).shards.length, 3);
|
|
104
|
+
assert.equal(planShards({ files, durations: d, targetS: 1 }).shards.length, 6, "never more shards than files");
|
|
105
|
+
});
|
|
106
|
+
it("is deterministic, deduplicates, and handles the empty and default cases", () => {
|
|
107
|
+
assert.deepEqual(planShards({ files: ["b", "a", "a"], shards: 2 }).shards.map((s) => s.files), [["a"], ["b"]]);
|
|
108
|
+
assert.deepEqual(planShards({ files: [] }).shards, [{ index: 1, files: [], est_s: 0 }]);
|
|
109
|
+
assert.equal(planShards({ files }).shards.length, 1);
|
|
110
|
+
});
|
|
111
|
+
});
|