forgedock 1.60.1 → 1.61.1
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 +189 -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 +25 -1
- 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
|
@@ -0,0 +1,303 @@
|
|
|
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 { execFileSync } from "node:child_process";
|
|
6
|
+
import { cpSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { dirname, join, relative } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import {
|
|
11
|
+
globRe, matchGlob, parseSuiteRule, parseTestsConfig, configHash, testFilesOf, jsSpecifiers, pyImports, buildGraph, selectTests,
|
|
12
|
+
fullReason, planRun, testsFromCli, ledgerPath, RUN_ALL_DEFAULT,
|
|
13
|
+
} from "./testengine.mjs";
|
|
14
|
+
import { parseForgeYaml } from "../forge-utils.mjs";
|
|
15
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
16
|
+
|
|
17
|
+
const FIX = join(dirname(fileURLToPath(import.meta.url)), "..", "tests", "fixtures", "testengine");
|
|
18
|
+
const walk = (dir, root = dir) => readdirSync(dir).flatMap((n) => { const p = join(dir, n); return statSync(p).isDirectory() ? walk(p, root) : [relative(root, p).split("\\").join("/")]; });
|
|
19
|
+
const repo = (name) => { const root = join(FIX, name), files = walk(root).sort(); return { root, files, read: (f) => { try { return readFileSync(join(root, f), "utf8"); } catch { return null; } } }; };
|
|
20
|
+
const JS = repo("js-app"), PY = repo("py-app");
|
|
21
|
+
const cfg = (ci = {}) => parseTestsConfig({ selection: "shadow", ...ci });
|
|
22
|
+
const select = (r, changed, ci) => selectTests({ files: r.files, read: r.read, changed, cfg: cfg(ci) });
|
|
23
|
+
|
|
24
|
+
describe("globs", () => {
|
|
25
|
+
it("matches segments, ** and basenames", () => {
|
|
26
|
+
assert.ok(globRe("src/**/*.js").test("src/a.js"));
|
|
27
|
+
assert.ok(globRe("src/**/*.js").test("src/x/y/a.js"));
|
|
28
|
+
assert.ok(!globRe("src/*.js").test("src/x/a.js"));
|
|
29
|
+
assert.ok(matchGlob("web/package.json", "package.json"), "a glob without a slash matches the basename anywhere");
|
|
30
|
+
assert.ok(matchGlob(".github/workflows/ci.yml", ".github/**"));
|
|
31
|
+
assert.ok(!matchGlob("src/a.test.js", "a?.test.js"));
|
|
32
|
+
assert.ok(matchGlob("deploy/docker-compose.prod.yaml", "docker-compose*.y*ml"));
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe("parseTestsConfig", () => {
|
|
37
|
+
it("defaults to off, report-only quarantine and 50 runs", () => {
|
|
38
|
+
const c = parseTestsConfig(undefined);
|
|
39
|
+
assert.equal(c.selection, "off");
|
|
40
|
+
assert.equal(c.quarantine, "report");
|
|
41
|
+
assert.equal(c.graduateAfter, 50);
|
|
42
|
+
assert.equal(c.graduateMinFailing, 1);
|
|
43
|
+
assert.deepEqual(c.runAll, RUN_ALL_DEFAULT);
|
|
44
|
+
assert.deepEqual(c.fullBranches, ["main", "master", "release/**"]);
|
|
45
|
+
assert.deepEqual([c.suites, c.ignore, c.testGlobs, c.shards], [[], [], [], 0]);
|
|
46
|
+
});
|
|
47
|
+
it("reads the flattened ci.tests block from forge.yaml text, and junk keeps the defaults", () => {
|
|
48
|
+
const y = parseForgeYaml('ci:\n mode: local-first\n tests:\n selection: shadow\n suites:\n - "migrations/** => tests/integration/**"\n - "broken entry"\n ignore: ["**/*.md"]\n graduate_after: 20\n graduate_min_failing: 0\n quarantine: non-blocking\n shards: many\n');
|
|
49
|
+
assert.equal(y.ci.mode, "local-first", "ci.tests keys never collide with the ci budget mode");
|
|
50
|
+
const c = parseTestsConfig(y.ci);
|
|
51
|
+
assert.equal(c.selection, "shadow");
|
|
52
|
+
assert.deepEqual(c.suites, [{ when: ["migrations/**"], targets: ["tests/integration/**"] }]);
|
|
53
|
+
assert.deepEqual(c.badSuites, ["broken entry"]);
|
|
54
|
+
assert.deepEqual(c.ignore, ["**/*.md"]);
|
|
55
|
+
assert.deepEqual([c.graduateAfter, c.graduateMinFailing, c.quarantine, c.shards], [20, 0, "non-blocking", 0]);
|
|
56
|
+
assert.equal(parseTestsConfig({ selection: "always" }).selection, "off");
|
|
57
|
+
});
|
|
58
|
+
it("parses suite rules", () => {
|
|
59
|
+
assert.deepEqual(parseSuiteRule("a/** b/*.sql => tests/x/** @e2e"), { when: ["a/**", "b/*.sql"], targets: ["tests/x/**", "@e2e"] });
|
|
60
|
+
assert.equal(parseSuiteRule("a/** =>"), null);
|
|
61
|
+
assert.equal(parseSuiteRule("a => b => c"), null);
|
|
62
|
+
});
|
|
63
|
+
it("hashes only what decides a selection", () => {
|
|
64
|
+
assert.equal(configHash(cfg()), configHash(cfg({ graduate_after: 5, quarantine: "off", selection: "enforce" })));
|
|
65
|
+
assert.notEqual(configHash(cfg()), configHash(cfg({ ignore: ["**/*.md"] })));
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe("source scanning", () => {
|
|
70
|
+
it("finds JS specifiers in every import form", () => {
|
|
71
|
+
const src = 'import a from "./a.js";\nimport {\n b,\n} from "./b";\nimport "./side.css";\nexport * from "./c";\nexport { d } from \'./d\';\nconst e = require("./e");\nconst f = await import("./f.mjs");\nvi.mock("./g");\nconst u = new URL("../h.mjs", import.meta.url);\nimport(`./${x}.js`);\nimport type { T } from "./types";';
|
|
72
|
+
assert.deepEqual(jsSpecifiers(src).sort(), ["../h.mjs", "./a.js", "./b", "./c", "./d", "./e", "./f.mjs", "./g", "./side.css", "./types"]);
|
|
73
|
+
});
|
|
74
|
+
it("finds Python imports, relative levels and run-time string imports", () => {
|
|
75
|
+
const got = pyImports('import os, a.b as ab\nfrom . import x\nfrom ..pkg.mod import (\n one,\n two as t, # note\n)\nfrom a import *\nimportlib.import_module("p.q")\nmock.patch("r.s.func")\npytest_plugins = ["fix.plugin"]\n');
|
|
76
|
+
const key = (i) => `${i.level}:${i.module}:${i.names.join(",")}`;
|
|
77
|
+
assert.deepEqual(got.map(key).sort(), ["0:a.b:", "0:a:", "0:fix.plugin:", "0:os:", "0:p.q:", "0:r.s.func:", "1::x", "2:pkg.mod:one,two"].sort());
|
|
78
|
+
});
|
|
79
|
+
it("lists test files by convention or by ci.tests.test_globs", () => {
|
|
80
|
+
assert.deepEqual(testFilesOf(JS.files), ["packages/shared/src/format.test.js", "test/cart.test.js", "test/legacy.spec.cjs", "test/math.test.js", "test/plugins.test.js", "test/schema.test.js", "web/__tests__/button.tsx"]);
|
|
81
|
+
assert.deepEqual(testFilesOf(PY.files), ["tests/integration/test_checkout.py", "tests/integration/test_report.py", "tests/unit/store_test.py", "tests/unit/test_pricing.py", "tests/unit/test_tax.py"]);
|
|
82
|
+
assert.deepEqual(testFilesOf(PY.files, { testGlobs: ["tests/integration/**/*.py"] }), ["tests/integration/conftest.py", "tests/integration/test_checkout.py", "tests/integration/test_report.py"]);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("buildGraph", () => {
|
|
87
|
+
const deps = (r, f) => [...(buildGraph(r).deps.get(f) ?? [])].sort();
|
|
88
|
+
it("resolves JS relative, extensionless, workspace, tsconfig alias, .js -> .tsx and asset imports", () => {
|
|
89
|
+
assert.deepEqual(deps(JS, "src/cart.js"), ["data/rates.json", "packages/shared/src/index.js", "src/util/math.js"]);
|
|
90
|
+
assert.deepEqual(deps(JS, "src/legacy.cjs"), ["src/util/math.js"]);
|
|
91
|
+
assert.deepEqual(deps(JS, "web/src/button.tsx"), ["web/src/lib/label.ts"]);
|
|
92
|
+
assert.deepEqual(deps(JS, "web/__tests__/button.tsx"), ["web/src/button.tsx"]);
|
|
93
|
+
assert.deepEqual(buildGraph(JS).dynamic, ["src/plugins.js"]);
|
|
94
|
+
});
|
|
95
|
+
it("resolves Python absolute (src layout), relative, package __init__, sibling helper and conftest chain", () => {
|
|
96
|
+
assert.deepEqual(deps(PY, "src/orders/tax.py"), ["src/orders/__init__.py", "src/orders/pricing.py"]);
|
|
97
|
+
assert.deepEqual(deps(PY, "src/orders/service.py"), ["src/orders/__init__.py", "src/orders/store.py", "src/orders/tax.py"]);
|
|
98
|
+
assert.deepEqual(deps(PY, "tests/unit/test_tax.py"), ["src/orders/__init__.py", "src/orders/tax.py", "tests/conftest.py", "tests/helpers.py"]);
|
|
99
|
+
assert.deepEqual(deps(PY, "tests/integration/test_checkout.py"), ["src/orders/__init__.py", "src/orders/service.py", "tests/conftest.py", "tests/integration/conftest.py"]);
|
|
100
|
+
assert.deepEqual(deps(PY, "tests/unit/store_test.py"), ["src/orders/__init__.py", "src/orders/store.py", "tests/conftest.py"]);
|
|
101
|
+
assert.deepEqual(deps(PY, "src/orders/report.py"), ["src/orders/__init__.py", "src/orders/pricing.py"]);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe("selectTests (JS)", () => {
|
|
106
|
+
it("selects the transitive importers of a changed source file, each with a reason", () => {
|
|
107
|
+
const s = select(JS, ["src/util/math.js"]);
|
|
108
|
+
assert.equal(s.mode, "subset");
|
|
109
|
+
assert.deepEqual(s.tests, ["test/cart.test.js", "test/legacy.spec.cjs", "test/math.test.js", "test/plugins.test.js"]);
|
|
110
|
+
assert.deepEqual(s.reasons["test/math.test.js"], ["depends on src/util/math.js"]);
|
|
111
|
+
assert.deepEqual(s.reasons["test/cart.test.js"], ["reaches src/util/math.js through src/cart.js"]);
|
|
112
|
+
assert.equal(s.total, 7);
|
|
113
|
+
assert.deepEqual(s.by_ecosystem, { js: s.tests });
|
|
114
|
+
});
|
|
115
|
+
it("follows a workspace package and a re-export", () => {
|
|
116
|
+
assert.deepEqual(select(JS, ["packages/shared/src/format.js"]).tests, ["packages/shared/src/format.test.js", "test/cart.test.js"]);
|
|
117
|
+
});
|
|
118
|
+
it("follows a tsconfig alias and an imported data file", () => {
|
|
119
|
+
assert.deepEqual(select(JS, ["web/src/lib/label.ts"]).tests, ["web/__tests__/button.tsx"]);
|
|
120
|
+
assert.deepEqual(select(JS, ["data/rates.json"]).tests, ["test/cart.test.js"]);
|
|
121
|
+
});
|
|
122
|
+
it("follows a repo path quoted in a test (a file read by path, not imported)", () => {
|
|
123
|
+
assert.deepEqual(select(JS, ["data/schema.sql"]).tests, ["test/schema.test.js"]);
|
|
124
|
+
assert.deepEqual(select(JS, ["test/fixtures/order.json"]).tests, ["test/schema.test.js"]);
|
|
125
|
+
});
|
|
126
|
+
it("selects a changed test file itself", () => {
|
|
127
|
+
const s = select(JS, ["./test/math.test.js"]);
|
|
128
|
+
assert.deepEqual([s.mode, s.tests, s.reasons["test/math.test.js"]], ["subset", ["test/math.test.js"], ["changed test file"]]);
|
|
129
|
+
});
|
|
130
|
+
it("runs everything for a manifest, lockfile, CI file or runner config", () => {
|
|
131
|
+
for (const f of ["package.json", "packages/shared/package.json", "pnpm-lock.yaml", ".github/workflows/ci.yml", "web/tsconfig.json", "vitest.config.ts", "forge.yaml", "Dockerfile.web", ".env.example"]) {
|
|
132
|
+
const s = select(JS, [f, "src/util/math.js"]);
|
|
133
|
+
assert.equal(s.mode, "all", f);
|
|
134
|
+
assert.equal(s.tests.length, 7, f);
|
|
135
|
+
assert.match(s.run_all[0].why, /run-everything glob/, f);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
it("runs everything for a file nothing maps: no importer, unknown type, deleted, or an empty diff", () => {
|
|
139
|
+
assert.match(select(JS, ["src/orphan.js"]).run_all[0].why, /no test imports it/);
|
|
140
|
+
assert.equal(select(JS, ["data/notes.txt"]).mode, "all");
|
|
141
|
+
assert.equal(select(JS, ["README.md"]).mode, "all");
|
|
142
|
+
assert.match(select(JS, ["src/removed.js"]).run_all[0].why, /deleted or unknown/);
|
|
143
|
+
assert.match(select(JS, []).run_all[0].why, /no changed files/);
|
|
144
|
+
});
|
|
145
|
+
it("a deleted test file alone selects nothing", () => {
|
|
146
|
+
assert.deepEqual([select(JS, ["test/old.test.js"]).mode, select(JS, ["test/old.test.js"]).tests], ["none", []]);
|
|
147
|
+
});
|
|
148
|
+
it("ci.tests.suites maps paths to test globs, named suites or everything", () => {
|
|
149
|
+
const ci = { suites: ["data/*.txt => test/cart.test.js @e2e", "docs/** => *", "src/orphan.js => test/nothing/**"] };
|
|
150
|
+
const s = select(JS, ["data/notes.txt"], ci);
|
|
151
|
+
assert.deepEqual([s.mode, s.tests, s.suites], ["subset", ["test/cart.test.js"], ["@e2e"]]);
|
|
152
|
+
assert.deepEqual(s.reasons["test/cart.test.js"], ["data/notes.txt matches data/*.txt => test/cart.test.js"]);
|
|
153
|
+
assert.equal(select(JS, ["docs/guide.md"], ci).mode, "all");
|
|
154
|
+
const o = select(JS, ["src/orphan.js"], ci);
|
|
155
|
+
assert.equal(o.mode, "none");
|
|
156
|
+
assert.match(o.warnings.join("\n"), /matches no test file/);
|
|
157
|
+
});
|
|
158
|
+
it("ci.tests.ignore drops files, and ci.tests.run_all adds triggers", () => {
|
|
159
|
+
const s = select(JS, ["README.md", "src/util/math.js"], { ignore: ["**/*.md"] });
|
|
160
|
+
assert.deepEqual([s.mode, s.ignored, s.tests.length], ["subset", ["README.md"], 4]);
|
|
161
|
+
assert.equal(select(JS, ["README.md"], { ignore: ["*.md"] }).mode, "none");
|
|
162
|
+
assert.equal(select(JS, ["src/util/math.js"], { run_all: ["src/util/**"] }).mode, "all");
|
|
163
|
+
});
|
|
164
|
+
it("warns about computed imports and bad suite entries", () => {
|
|
165
|
+
const s = select(JS, ["src/util/math.js"], { suites: ["nonsense"] });
|
|
166
|
+
assert.match(s.warnings.join("\n"), /computed import/);
|
|
167
|
+
assert.match(s.warnings.join("\n"), /entry ignored/);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
describe("selectTests (Python)", () => {
|
|
172
|
+
it("selects by module imports through the package", () => {
|
|
173
|
+
const s = select(PY, ["src/orders/pricing.py"]);
|
|
174
|
+
assert.deepEqual(s.tests, ["tests/integration/test_checkout.py", "tests/integration/test_report.py", "tests/unit/test_pricing.py", "tests/unit/test_tax.py"]);
|
|
175
|
+
assert.deepEqual(s.by_ecosystem, { python: s.tests });
|
|
176
|
+
assert.deepEqual(select(PY, ["src/orders/store.py"]).tests, ["tests/integration/test_checkout.py", "tests/unit/store_test.py"]);
|
|
177
|
+
});
|
|
178
|
+
it("a conftest.py change selects the tests under it; a helper selects its importers", () => {
|
|
179
|
+
assert.deepEqual(select(PY, ["tests/integration/conftest.py"]).tests, ["tests/integration/test_checkout.py", "tests/integration/test_report.py"]);
|
|
180
|
+
assert.equal(select(PY, ["tests/conftest.py"]).tests.length, 5);
|
|
181
|
+
assert.deepEqual(select(PY, ["tests/helpers.py"]).tests, ["tests/unit/test_tax.py"]);
|
|
182
|
+
});
|
|
183
|
+
it("a package __init__ change selects every importer of the package", () => {
|
|
184
|
+
assert.equal(select(PY, ["src/orders/__init__.py"]).tests.length, 5);
|
|
185
|
+
});
|
|
186
|
+
it("runs everything for pyproject.toml and for a script no test imports", () => {
|
|
187
|
+
assert.equal(select(PY, ["pyproject.toml"]).mode, "all");
|
|
188
|
+
assert.equal(select(PY, ["scripts/backfill.py"]).mode, "all");
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe("fullReason / planRun", () => {
|
|
193
|
+
const sel = select(JS, ["src/util/math.js"]);
|
|
194
|
+
const grad = (graduated) => ({ graduated, why: graduated ? "graduated" : "3 of 50 consecutive full runs with 100% failure recall" });
|
|
195
|
+
it("forces the full suite on --full, a schedule and a release branch", () => {
|
|
196
|
+
const c = cfg();
|
|
197
|
+
assert.match(fullReason({ flag: true, cfg: c }), /--full/);
|
|
198
|
+
assert.match(fullReason({ event: "schedule", cfg: c }), /nightly/);
|
|
199
|
+
assert.match(fullReason({ baseRef: "main", cfg: c }), /release branch main/);
|
|
200
|
+
assert.match(fullReason({ ref: "refs/heads/release/r1", cfg: c }), /release branch release\/r1/);
|
|
201
|
+
assert.equal(fullReason({ event: "pull_request", baseRef: "staging", ref: "refs/pull/7/merge", cfg: c }), null);
|
|
202
|
+
assert.equal(fullReason({ baseRef: "main", cfg: cfg({ full_branches: ["prod"] }) }), null);
|
|
203
|
+
});
|
|
204
|
+
it("off computes nothing and runs everything", () => {
|
|
205
|
+
assert.deepEqual(planRun({ cfg: parseTestsConfig({}) }), { configured: "off", effective: "off", run: "all", why: "ci.tests.selection is off" });
|
|
206
|
+
});
|
|
207
|
+
it("shadow always runs everything", () => {
|
|
208
|
+
assert.deepEqual([planRun({ cfg: cfg(), selection: sel, graduation: grad(true) }).run, planRun({ cfg: cfg(), selection: sel, graduation: grad(true) }).effective], ["all", "shadow"]);
|
|
209
|
+
});
|
|
210
|
+
it("enforce is refused before graduation and stays shadow", () => {
|
|
211
|
+
const p = planRun({ cfg: cfg({ selection: "enforce" }), selection: sel, graduation: grad(false) });
|
|
212
|
+
assert.deepEqual([p.effective, p.run], ["shadow", "all"]);
|
|
213
|
+
assert.match(p.refused, /enforce refused: 3 of 50/);
|
|
214
|
+
assert.match(planRun({ cfg: cfg({ selection: "enforce" }), selection: sel, graduation: null }).refused, /no recall ledger/);
|
|
215
|
+
});
|
|
216
|
+
it("enforce after graduation runs the selection, unless a full run is forced or everything is selected", () => {
|
|
217
|
+
const c = cfg({ selection: "enforce" });
|
|
218
|
+
assert.deepEqual([planRun({ cfg: c, selection: sel, graduation: grad(true) }).run, planRun({ cfg: c, selection: sel, graduation: grad(true) }).effective], ["selection", "enforce"]);
|
|
219
|
+
assert.equal(planRun({ cfg: c, selection: sel, graduation: grad(true), full: "scheduled run" }).run, "all");
|
|
220
|
+
assert.equal(planRun({ cfg: c, selection: select(JS, ["package.json"]), graduation: grad(true) }).run, "all");
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
describe("forgedock tests CLI", () => {
|
|
225
|
+
const setup = (yaml) => {
|
|
226
|
+
const dir = tmpDir("testengine-");
|
|
227
|
+
cpSync(JS.root, dir, { recursive: true });
|
|
228
|
+
if (yaml) writeFileSync(join(dir, "forge.yaml"), yaml);
|
|
229
|
+
const g = (...a) => execFileSync("git", a, { cwd: dir, stdio: "ignore" });
|
|
230
|
+
g("init", "-q"); g("add", "-A"); g("-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-qm", "init");
|
|
231
|
+
writeFileSync(join(dir, "src/util/math.js"), "export const add = (a, b) => b + a;\n");
|
|
232
|
+
g("-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-qam", "change");
|
|
233
|
+
return dir;
|
|
234
|
+
};
|
|
235
|
+
const run = async (dir, argv, env = {}) => { const lines = []; const code = await testsFromCli(argv, { cwd: dir, out: (l) => lines.push(l), env: { FORGEDOCK_TESTS_DIR: join(dir, ".ledger"), ...env }, now: Date.parse("2026-11-15T00:00:00Z") }); return { code, text: lines.join("\n") }; };
|
|
236
|
+
const SHADOW = "ci:\n tests:\n selection: shadow\n";
|
|
237
|
+
|
|
238
|
+
it("off (no ci.tests): says run everything, computes nothing, records nothing", async () => {
|
|
239
|
+
const dir = setup(null);
|
|
240
|
+
{
|
|
241
|
+
const r = await run(dir, ["select", "--base", "HEAD~1", "--json"]);
|
|
242
|
+
assert.deepEqual(JSON.parse(r.text), { plan: { configured: "off", effective: "off", run: "all", why: "ci.tests.selection is off" }, selection: null, run_tests: null, quarantined: [], graduation: null });
|
|
243
|
+
assert.equal((await run(dir, ["recall", "record", "--selection", "missing.json"])).text, "tests recall: ci.tests.selection is off; nothing recorded");
|
|
244
|
+
assert.equal(readdirSync(dir).includes(".ledger"), false);
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
it("shadow: selects from the git diff, runs everything, records recall, shards, and refuses enforce", async () => {
|
|
248
|
+
const dir = setup(SHADOW);
|
|
249
|
+
{
|
|
250
|
+
const sel = join(dir, "sel.json");
|
|
251
|
+
const r = await run(dir, ["select", "--base", "HEAD~1", "--out", sel]);
|
|
252
|
+
assert.match(r.text, /selection shadow; run all/);
|
|
253
|
+
assert.match(r.text, /selected: 4 of 7 test file\(s\)/);
|
|
254
|
+
assert.match(r.text, /test\/cart\.test\.js: reaches src\/util\/math\.js through src\/cart\.js/);
|
|
255
|
+
const out = JSON.parse(readFileSync(sel, "utf8"));
|
|
256
|
+
assert.equal(out.run_tests.length, 7);
|
|
257
|
+
assert.equal(out.selection.tests.length, 4);
|
|
258
|
+
|
|
259
|
+
const rep = join(FIX, "reports", "vitest-junit.xml");
|
|
260
|
+
assert.match((await run(dir, ["recall", "record", "--selection", sel, "--report", rep, "--sha", "abc", "--run-id", "1"])).text, /recall: ok: 1 failing test file\(s\), 0 outside the selection/);
|
|
261
|
+
const miss = await run(dir, ["recall", "record", "--selection", sel, "--failed", "web/__tests__/button.tsx", "--sha", "abd", "--json"]);
|
|
262
|
+
assert.deepEqual([JSON.parse(miss.text).ok, JSON.parse(miss.text).missed], [false, ["web/__tests__/button.tsx"]]);
|
|
263
|
+
const st = await run(dir, ["recall", "status"]);
|
|
264
|
+
assert.match(st.text, /0 of 50 consecutive full runs with 100% failure recall since the last miss/);
|
|
265
|
+
assert.match(st.text, /last miss: abd/);
|
|
266
|
+
assert.equal((await run(dir, ["recall", "check"])).code, 1);
|
|
267
|
+
|
|
268
|
+
const sh = await run(dir, ["shard", "--shards", "2", "--report", rep, "--json"]);
|
|
269
|
+
const plan = JSON.parse(sh.text);
|
|
270
|
+
assert.deepEqual([plan.shards.length, plan.source, plan.shards.flatMap((s) => s.files).length], [2, "durations", 7]);
|
|
271
|
+
const m = JSON.parse((await run(dir, ["shard", "--shards", "3", "--from", sel, "--matrix"])).text);
|
|
272
|
+
assert.deepEqual(m.include.map((i) => [i.shard, i.total]), [[1, 3], [2, 3], [3, 3]]);
|
|
273
|
+
|
|
274
|
+
writeFileSync(join(dir, "forge.yaml"), SHADOW.replace("shadow", "enforce"));
|
|
275
|
+
const e = await run(dir, ["select", "--changed", "src/util/math.js", "--json"]);
|
|
276
|
+
assert.deepEqual([JSON.parse(e.text).plan.effective, JSON.parse(e.text).plan.run, JSON.parse(e.text).run_tests.length], ["shadow", "all", 7]);
|
|
277
|
+
assert.match(JSON.parse(e.text).plan.refused, /enforce refused/);
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
it("enforce after graduation returns only the selection, and the full suite on a schedule", async () => {
|
|
281
|
+
const dir = setup("ci:\n tests:\n selection: enforce\n graduate_after: 2\n");
|
|
282
|
+
{
|
|
283
|
+
const sel = join(dir, "sel.json");
|
|
284
|
+
await run(dir, ["select", "--changed", "src/util/math.js", "--out", sel]);
|
|
285
|
+
for (const id of ["1", "2"]) await run(dir, ["recall", "record", "--selection", sel, "--failed", "test/math.test.js", "--sha", `s${id}`, "--run-id", id]);
|
|
286
|
+
assert.equal((await run(dir, ["recall", "check"])).code, 0);
|
|
287
|
+
const e = JSON.parse((await run(dir, ["select", "--changed", "src/util/math.js", "--json"])).text);
|
|
288
|
+
assert.deepEqual([e.plan.effective, e.plan.run, e.run_tests.length], ["enforce", "selection", 4]);
|
|
289
|
+
const n = JSON.parse((await run(dir, ["select", "--changed", "src/util/math.js", "--json"], { GITHUB_EVENT_NAME: "schedule" })).text);
|
|
290
|
+
assert.deepEqual([n.plan.run, n.run_tests.length], ["all", 7]);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
it("rejects unknown subcommands and flags", async () => {
|
|
294
|
+
await assert.rejects(testsFromCli(["nope"], { out: () => {} }), /usage: forgedock tests select/);
|
|
295
|
+
await assert.rejects(testsFromCli(["select", "--bogus"], { out: () => {}, cwd: FIX }), /unknown argument --bogus/);
|
|
296
|
+
await assert.rejects(testsFromCli(["recall", "wat"], { out: () => {}, cwd: FIX }), /unknown tests recall subcommand/);
|
|
297
|
+
});
|
|
298
|
+
it("puts the default ledger outside the checkout", () => {
|
|
299
|
+
assert.equal(ledgerPath({ cwd: "/x", cfg: { ledger: "" }, flag: "/a/l.jsonl", env: {} }), "/a/l.jsonl");
|
|
300
|
+
assert.equal(ledgerPath({ cwd: "/x", cfg: { ledger: "/c/l.jsonl" }, env: {} }), "/c/l.jsonl");
|
|
301
|
+
assert.match(ledgerPath({ cwd: tmpdir(), cfg: { ledger: "" }, env: { FORGEDOCK_TESTS_DIR: "/state" } }), /^\/state\/[^/]+\/recall\.jsonl$/);
|
|
302
|
+
});
|
|
303
|
+
});
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5718: verify.settle (condition wait for unreported gate checks) and verify.cancel_superseded.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { DEFAULT_GRACE_MS, SETTLE_MIN_MS, cancelSuperseded, parseCancelSuperseded, parseVerify, runCiVerify, settleKnown, supersededRuns } from "./verify.mjs";
|
|
7
|
+
|
|
8
|
+
/** A clock-driven fake: `checks(elapsedMs)` and `suites(elapsedMs)` answer by time since the first read. */
|
|
9
|
+
function fake({ checks, suites = null }) {
|
|
10
|
+
const f = { clock: 0, suiteReads: 0, settle: [] };
|
|
11
|
+
f.io = { commitChecks: async () => checks(f.clock), failedLogs: async () => "", ...(suites ? { checkSuites: async () => { f.suiteReads++; const s = suites(f.clock); if (s === "throw") throw new Error("HTTP 502"); return s; } } : {}) };
|
|
12
|
+
f.args = (settle) => ({ io: f.io, branch: "feat/x", head: "abc123", changedFiles: ["src/a.ts"], verify: parseVerify({ mode: "ci", ...(settle ? { settle } : {}) }), gate: ["lint", "test"],
|
|
13
|
+
now: () => f.clock, sleep: async (ms) => { f.clock += ms; }, random: () => 0.5, onSettle: (r) => f.settle.push(r) });
|
|
14
|
+
return f;
|
|
15
|
+
}
|
|
16
|
+
const lintOnly = () => [{ name: "lint", state: "success", id: 1 }];
|
|
17
|
+
const done = (...ids) => ids.map((id) => ({ id, status: "completed", conclusion: "success" }));
|
|
18
|
+
|
|
19
|
+
describe("verify.settle config (#5718)", () => {
|
|
20
|
+
it("defaults add no key: the parsed config is unchanged when settle and cancel_superseded are off", () => {
|
|
21
|
+
assert.ok(!("settle" in parseVerify({}))); assert.ok(!("cancelSuperseded" in parseVerify({})));
|
|
22
|
+
assert.ok(!("settle" in parseVerify({ settle: "fixed" }))); assert.ok(!("settle" in parseVerify({ settle: "soon" })));
|
|
23
|
+
assert.ok(!("cancelSuperseded" in parseVerify({ cancel_superseded: "false" })));
|
|
24
|
+
assert.equal(parseVerify({ settle: "Condition" }).settle, "condition"); assert.equal(parseVerify({ settle: "shadow" }).settle, "shadow");
|
|
25
|
+
assert.equal(parseVerify({ cancel_superseded: "true" }).cancelSuperseded, "own"); assert.equal(parseVerify({ cancel_superseded: "all" }).cancelSuperseded, "all");
|
|
26
|
+
assert.equal(parseCancelSuperseded("sometimes"), "off");
|
|
27
|
+
});
|
|
28
|
+
it("settleKnown: every suite completed, the same ids on two polls, and the minimum wait passed", () => {
|
|
29
|
+
const k = (o) => settleKnown({ suites: done(1, 2), prev: ["1", "2"], elapsedMs: SETTLE_MIN_MS, ...o }).known;
|
|
30
|
+
assert.equal(k({}), true);
|
|
31
|
+
assert.equal(k({ prev: null }), false, "first poll");
|
|
32
|
+
assert.equal(k({ prev: ["1"] }), false, "a suite appeared since the last poll");
|
|
33
|
+
assert.equal(k({ elapsedMs: SETTLE_MIN_MS - 1 }), false);
|
|
34
|
+
assert.equal(k({ suites: [...done(1), { id: 2, status: "queued" }] }), false, "a queued suite may still register checks");
|
|
35
|
+
assert.equal(k({ suites: [...done(1), { id: 2, status: "in_progress" }] }), false);
|
|
36
|
+
assert.equal(k({ suites: [], prev: [] }), false, "no suite yet");
|
|
37
|
+
assert.equal(k({ suites: null, prev: [] }), false);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe("runCiVerify settle modes (#5718)", () => {
|
|
42
|
+
it("fixed (default): waits the whole grace period for an unreported gate check and never reads check suites", async () => {
|
|
43
|
+
for (const mode of [undefined, "fixed"]) {
|
|
44
|
+
const f = fake({ checks: lintOnly, suites: () => done(1) });
|
|
45
|
+
const r = await runCiVerify(f.args(mode));
|
|
46
|
+
assert.equal(r.result, "pass"); assert.ok(f.clock >= DEFAULT_GRACE_MS); assert.equal(f.suiteReads, 0); assert.deepEqual(f.settle, []);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
it("condition: decides once the head's check suites are complete and stable, with the same verdict", async () => {
|
|
50
|
+
const fixed = fake({ checks: lintOnly }), cond = fake({ checks: lintOnly, suites: () => done(1) });
|
|
51
|
+
const a = await runCiVerify(fixed.args()), b = await runCiVerify(cond.args("condition"));
|
|
52
|
+
assert.deepEqual({ result: b.result, detail: b.detail }, { result: a.result, detail: a.detail });
|
|
53
|
+
assert.ok(cond.clock >= SETTLE_MIN_MS && cond.clock < DEFAULT_GRACE_MS / 2, `decided at ${cond.clock} ms`);
|
|
54
|
+
assert.equal(cond.settle.length, 1); assert.equal(cond.settle[0].mode, "condition"); assert.deepEqual(cond.settle[0].missing, ["test"]); assert.equal(cond.settle[0].agreed, true);
|
|
55
|
+
});
|
|
56
|
+
it("condition: a suite that is still running keeps the wait, so a late required check still gates", async () => {
|
|
57
|
+
const f = fake({ checks: (t) => (t < 120000 ? lintOnly() : [...lintOnly(), { name: "test", state: "failure", id: 2, url: "https://github.com/o/r/actions/runs/7/job/1" }]),
|
|
58
|
+
suites: (t) => (t < 120000 ? [...done(1), { id: 2, status: "queued" }] : done(1, 2)) });
|
|
59
|
+
const r = await runCiVerify(f.args("condition"));
|
|
60
|
+
assert.equal(r.result, "fail"); assert.deepEqual(r.failures.map((x) => x.job), ["test"]); assert.ok(f.clock >= 120000);
|
|
61
|
+
});
|
|
62
|
+
it("condition: unreadable or absent check suites never shorten the wait; the grace period is the maximum", async () => {
|
|
63
|
+
const f = fake({ checks: lintOnly, suites: () => "throw" });
|
|
64
|
+
assert.equal((await runCiVerify(f.args("condition"))).result, "pass"); assert.ok(f.clock >= DEFAULT_GRACE_MS);
|
|
65
|
+
const g = fake({ checks: lintOnly, suites: () => [{ id: 1, status: "in_progress" }] });
|
|
66
|
+
await runCiVerify(g.args("condition")); assert.ok(g.clock >= DEFAULT_GRACE_MS);
|
|
67
|
+
const h = fake({ checks: lintOnly }); // no seam: fixed
|
|
68
|
+
await runCiVerify(h.args("condition")); assert.ok(h.clock >= DEFAULT_GRACE_MS);
|
|
69
|
+
});
|
|
70
|
+
it("shadow: waits as fixed and records when the condition held and whether the gating set agreed", async () => {
|
|
71
|
+
const f = fake({ checks: lintOnly, suites: () => done(1) });
|
|
72
|
+
const r = await runCiVerify(f.args("shadow"));
|
|
73
|
+
assert.equal(r.result, "pass"); assert.ok(f.clock >= DEFAULT_GRACE_MS);
|
|
74
|
+
assert.equal(f.settle.length, 1); assert.equal(f.settle[0].mode, "shadow"); assert.equal(f.settle[0].agreed, true);
|
|
75
|
+
assert.ok(f.settle[0].known_at_ms < DEFAULT_GRACE_MS / 2 && f.settle[0].waited_ms >= DEFAULT_GRACE_MS);
|
|
76
|
+
// a check that registers after every suite looked complete: the shadow record disagrees
|
|
77
|
+
const g = fake({ checks: (t) => (t < 200000 ? [{ name: "docs", state: "success", id: 1 }] : [{ name: "docs", state: "success", id: 1 }, { name: "lint", state: "success", id: 2 }]), suites: (t) => (t < 200000 ? done(1) : done(1, 2)) });
|
|
78
|
+
await runCiVerify(g.args("shadow"));
|
|
79
|
+
assert.equal(g.settle[0].agreed, false);
|
|
80
|
+
});
|
|
81
|
+
it("no gate name missing: no suite read in any mode", async () => {
|
|
82
|
+
const f = fake({ checks: () => [{ name: "lint", state: "success", id: 1 }, { name: "test", state: "success", id: 2 }], suites: () => done(1) });
|
|
83
|
+
assert.equal((await runCiVerify(f.args("condition"))).result, "pass"); assert.equal(f.suiteReads, 0); assert.equal(f.clock, 0);
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe("verify.cancel_superseded (#5718)", () => {
|
|
88
|
+
const runs = [
|
|
89
|
+
{ id: 1, headSha: "old1", status: "in_progress", event: "pull_request", actor: "forge-bot[bot]", createdAt: "2026-03-01T10:00:00Z" },
|
|
90
|
+
{ id: 2, headSha: "old1", status: "queued", event: "pull_request", actor: "someone", createdAt: "2026-03-01T10:00:00Z" },
|
|
91
|
+
{ id: 3, headSha: "new2", status: "in_progress", event: "pull_request", actor: "forge-bot[bot]", createdAt: "2026-03-01T10:10:00Z" },
|
|
92
|
+
{ id: 4, headSha: "old1", status: "in_progress", event: "push", actor: "forge-bot[bot]", createdAt: "2026-03-01T10:00:00Z" },
|
|
93
|
+
{ id: 5, headSha: "old1", status: "completed", event: "pull_request", actor: "forge-bot[bot]", createdAt: "2026-03-01T10:00:00Z" },
|
|
94
|
+
{ id: 6, headSha: "old0", status: "in_progress", event: "pull_request_target", actor: "Forge-Bot[bot]", createdAt: "2026-03-01T09:00:00Z" },
|
|
95
|
+
];
|
|
96
|
+
const ids = (o) => supersededRuns({ runs, head: "new2", actor: "forge-bot[bot]", ...o }).map((r) => r.id);
|
|
97
|
+
it("own: only this actor's queued or running verification runs of an older head", () => {
|
|
98
|
+
assert.deepEqual(ids({ mode: "own" }), [1, 6]);
|
|
99
|
+
assert.deepEqual(ids({ mode: "all" }), [1, 2, 6]);
|
|
100
|
+
assert.deepEqual(ids({ mode: "off" }), []); assert.deepEqual(ids({ mode: "own", actor: null }), []);
|
|
101
|
+
assert.deepEqual(supersededRuns({ runs, head: null, mode: "all" }), []);
|
|
102
|
+
assert.deepEqual(ids({ mode: "all", pushedAt: Date.parse("2026-03-01T09:30:00Z") }), [6], "a run created after the push is not superseded by it");
|
|
103
|
+
assert.ok(!ids({ mode: "all" }).includes(4), "a push run may deploy: never cancelled");
|
|
104
|
+
assert.ok(!ids({ mode: "all" }).includes(3), "the current head is never cancelled");
|
|
105
|
+
});
|
|
106
|
+
it("cancelSuperseded: off makes no call; on cancels through the seam and never throws", async () => {
|
|
107
|
+
const calls = [];
|
|
108
|
+
const io = { branchRuns: async (b) => { calls.push(`list ${b}`); return runs; }, cancelRun: async (id) => { calls.push(`cancel ${id}`); if (id === 6) throw new Error("HTTP 409"); }, viewerLogin: async () => "forge-bot[bot]" };
|
|
109
|
+
assert.deepEqual(await cancelSuperseded({ io, branch: "release", head: "new2" }), { cancelled: [], failed: [], skipped: "off" });
|
|
110
|
+
assert.deepEqual(calls, []);
|
|
111
|
+
assert.deepEqual(await cancelSuperseded({ io, branch: "release", head: "new2", mode: "own" }), { cancelled: [1], failed: [6] });
|
|
112
|
+
assert.deepEqual(calls, ["list release", "cancel 1", "cancel 6"]);
|
|
113
|
+
assert.deepEqual((await cancelSuperseded({ io, branch: "release", head: "new2", mode: "all", dryRun: true })).cancelled, [1, 2, 6]);
|
|
114
|
+
assert.equal((await cancelSuperseded({ io: { ...io, viewerLogin: async () => null }, branch: "release", head: "new2", mode: "own" })).skipped, "actor unknown");
|
|
115
|
+
assert.equal((await cancelSuperseded({ io: { ...io, branchRuns: async () => { throw new Error("HTTP 502"); } }, branch: "release", head: "new2", mode: "all" })).skipped, "runs unreadable");
|
|
116
|
+
assert.equal((await cancelSuperseded({ io: {}, branch: "release", head: "new2", mode: "all" })).skipped, "no seam");
|
|
117
|
+
});
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
describe("forgedock ci cancel-superseded and the gh seams (#5718)", () => {
|
|
121
|
+
it("ciRunSeams reads suites and runs through gh --paginate and cancels with one POST", async () => {
|
|
122
|
+
const { ciRunSeams } = await import("./effects.mjs");
|
|
123
|
+
const calls = [];
|
|
124
|
+
const gh = async (args) => {
|
|
125
|
+
calls.push(args.join(" "));
|
|
126
|
+
if (args.includes("user")) return "forge-bot[bot]\n";
|
|
127
|
+
if (/check-suites/.test(args.join(" "))) return '{"id":1,"status":"completed","conclusion":"success","app":"github-actions"}\n{"id":2,"status":"queued","conclusion":null,"app":"other"}\n';
|
|
128
|
+
if (/status=queued/.test(args.join(" "))) return '{"id":7,"headSha":"old","status":"queued","event":"pull_request","actor":"forge-bot[bot]","createdAt":"2026-03-01T10:00:00Z"}\n';
|
|
129
|
+
return "";
|
|
130
|
+
};
|
|
131
|
+
const io = ciRunSeams({ gh, repo: "acme/widgets" });
|
|
132
|
+
assert.deepEqual((await io.checkSuites("abc")).map((s) => [s.id, s.status]), [[1, "completed"], [2, "queued"]]);
|
|
133
|
+
assert.deepEqual((await io.branchRuns("feat/x y")).map((r) => r.id), [7]);
|
|
134
|
+
await io.cancelRun(7);
|
|
135
|
+
const prev = process.env.FORGE_BOT_LOGIN; delete process.env.FORGE_BOT_LOGIN;
|
|
136
|
+
try { assert.equal(await io.viewerLogin(), "forge-bot[bot]"); process.env.FORGE_BOT_LOGIN = "app[bot]"; assert.equal(await io.viewerLogin(), "app[bot]"); }
|
|
137
|
+
finally { if (prev === undefined) delete process.env.FORGE_BOT_LOGIN; else process.env.FORGE_BOT_LOGIN = prev; }
|
|
138
|
+
assert.ok(calls[0].startsWith("api --paginate repos/acme/widgets/commits/abc/check-suites"));
|
|
139
|
+
assert.ok(calls.some((c) => c.includes("actions/runs?branch=feat%2Fx%20y&status=in_progress")));
|
|
140
|
+
assert.ok(calls.includes("api -X POST repos/acme/widgets/actions/runs/7/cancel"));
|
|
141
|
+
});
|
|
142
|
+
it("the CLI is off without the forge.yaml switch or --mode, and cancels for a PR head when on", async () => {
|
|
143
|
+
const { cancelSupersededFromCli } = await import("./verify.mjs");
|
|
144
|
+
const out = [], cancelled = [];
|
|
145
|
+
const runs = [{ id: 1, headSha: "old", status: "in_progress", event: "pull_request", actor: "bot", createdAt: "2026-03-01T10:00:00Z" }, { id: 2, headSha: "new", status: "in_progress", event: "pull_request", actor: "bot", createdAt: "2026-03-01T10:05:00Z" }];
|
|
146
|
+
const deps = (config = {}) => ({ print: (s) => out.push(s), repo: "acme/widgets", config, gh: async (args) => (args[0] === "pr" ? JSON.stringify({ headRefName: "release", headRefOid: "new" }) : "new\n"),
|
|
147
|
+
seams: () => ({ branchRuns: async () => runs, cancelRun: async (id) => { cancelled.push(id); }, viewerLogin: async () => "bot" }) });
|
|
148
|
+
assert.equal(await cancelSupersededFromCli(["--pr", "12"], deps()), 0);
|
|
149
|
+
assert.match(out.pop(), /off \(set verify\.cancel_superseded/); assert.deepEqual(cancelled, []);
|
|
150
|
+
assert.equal(await cancelSupersededFromCli(["--pr", "12", "--dry-run"], deps({ cancelSuperseded: "own" })), 0);
|
|
151
|
+
assert.match(out.pop(), /release at new \(own, dry run\): 1 run\(s\) would be cancelled: 1/); assert.deepEqual(cancelled, []);
|
|
152
|
+
assert.equal(await cancelSupersededFromCli(["--branch", "release", "--mode", "all"], deps()), 0);
|
|
153
|
+
assert.deepEqual(cancelled, [1]);
|
|
154
|
+
assert.equal(await cancelSupersededFromCli([], deps()), 2); assert.equal(await cancelSupersededFromCli(["--pr", "x"], deps()), 2);
|
|
155
|
+
});
|
|
156
|
+
});
|
package/bin/lean/verify.mjs
CHANGED
|
@@ -29,6 +29,30 @@ export const VERIFY_CHECK_NAME = "forgedock/verify";
|
|
|
29
29
|
/** Checks API output.text limit is 65535 characters; stay well under it. */
|
|
30
30
|
export const VERIFY_TEXT_CAP = 60000;
|
|
31
31
|
const OK = ["success", "neutral", "skipped"];
|
|
32
|
+
/** #5718 `verify.cancel_superseded`: off (default) | own (runs this actor triggered) | all (every run of the branch). */
|
|
33
|
+
export const CANCEL_SUPERSEDED_MODES = Object.freeze(["off", "own", "all"]);
|
|
34
|
+
export const parseCancelSuperseded = (v) => { const s = String(v ?? "").trim().toLowerCase(); return s === "true" ? "own" : CANCEL_SUPERSEDED_MODES.includes(s) ? s : "off"; };
|
|
35
|
+
/**
|
|
36
|
+
* #5718 `verify.settle`: how long gate checks that have not reported are waited on. `fixed` (default): the whole grace
|
|
37
|
+
* period, as before. `condition`: until the head's check suites say nothing more can report (settleKnown), at most the
|
|
38
|
+
* grace period. `shadow`: waits as `fixed` and records when `condition` would have decided and whether the gating set
|
|
39
|
+
* was the same.
|
|
40
|
+
*/
|
|
41
|
+
export const SETTLE_MODES = Object.freeze(["fixed", "shadow", "condition"]);
|
|
42
|
+
/** The condition never holds before this long after the push: GitHub creates check suites asynchronously. */
|
|
43
|
+
export const SETTLE_MIN_MS = 20000;
|
|
44
|
+
/**
|
|
45
|
+
* #5718: true when the required set of a head is known: its check suites were read on two consecutive polls with the
|
|
46
|
+
* same ids, at least one exists, every suite is completed, and `minMs` has passed. A suite that is queued or in progress
|
|
47
|
+
* may still register checks, so the set is not known. `prev` is the id list of the previous poll (null on the first).
|
|
48
|
+
* @returns {{known: boolean, ids: string[]}}
|
|
49
|
+
*/
|
|
50
|
+
export function settleKnown({ suites, prev, elapsedMs, minMs = SETTLE_MIN_MS }) {
|
|
51
|
+
const list = Array.isArray(suites) ? suites : [];
|
|
52
|
+
const ids = list.map((x) => String(x?.id)).sort();
|
|
53
|
+
const stable = Array.isArray(prev) && prev.length === ids.length && prev.every((id, i) => id === ids[i]);
|
|
54
|
+
return { known: ids.length > 0 && stable && elapsedMs >= minMs && list.every((x) => String(x?.status).toLowerCase() === "completed"), ids };
|
|
55
|
+
}
|
|
32
56
|
|
|
33
57
|
/**
|
|
34
58
|
* forge.yaml `verify:` section (block style; parseForgeYaml gives strings) → {mode, workflow, pathsInput, skipPaths,
|
|
@@ -56,6 +80,7 @@ export function parseVerify(sec = {}) {
|
|
|
56
80
|
const rawChecks = Array.isArray(s.checks) ? s.checks : str(s.checks).split(",");
|
|
57
81
|
const names = rawChecks.map((x) => String(x ?? "").trim()).filter(Boolean);
|
|
58
82
|
const checks = names.length ? [...new Set(names)] : null;
|
|
83
|
+
const settle = SETTLE_MODES.includes(str(s.settle).toLowerCase()) ? str(s.settle).toLowerCase() : "fixed"; // #5718: both keys are absent from the result at their defaults
|
|
59
84
|
const postMerge = str(s.post_merge) || null;
|
|
60
85
|
// a flow list (`[a, "b c"]`) arrives as one scalar from the one-level reader: strip the brackets and quotes
|
|
61
86
|
const rawFlaky = Array.isArray(s.flaky) ? s.flaky : str(s.flaky).trim().replace(/^\[(.*)\]$/s, "$1").split(",");
|
|
@@ -75,7 +100,7 @@ export function parseVerify(sec = {}) {
|
|
|
75
100
|
const baselines = parseBaselines(s.baselines); // #5448: suites validate runs when matching paths change
|
|
76
101
|
const precheckBlock = str(s.precheck_block).toLowerCase() === "true"; // #5079: a still-failing declared check stops the lane (ci.red)
|
|
77
102
|
const guardBlock = str(s.guard_block).toLowerCase() !== "false"; // #5239: verify.invariants (the pre-merge guard set) block the merge unless false
|
|
78
|
-
return { mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s) };
|
|
103
|
+
return { ...(settle !== "fixed" ? { settle } : {}), ...(parseCancelSuperseded(s.cancel_superseded) !== "off" ? { cancelSuperseded: parseCancelSuperseded(s.cancel_superseded) } : {}), mode, workflow, pathsInput, skipPaths, maxRounds, precheckTimeoutSeconds, precheckTotalSeconds, checkRun, checks, postMerge, flaky, duplicateExports, enumeratingMechanical, invariants, ...(precheckBlock ? { precheckBlock } : {}), ...(guardBlock ? {} : { guardBlock: false }), ...(Object.keys(guardCommand).length ? { guardCommand } : {}), ...(baselines.length ? { baselines } : {}), ...(Object.keys(sandboxes).length ? { sandboxes } : {}), e2e: parseE2e(s) };
|
|
79
104
|
}
|
|
80
105
|
|
|
81
106
|
const globRe = (g) => new RegExp(`^${g.split("**").map((p) => p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")).join(".*")}$`);
|
|
@@ -170,8 +195,11 @@ const sameSha = (a, b) => Boolean(a && b) && (String(a).startsWith(b) || String(
|
|
|
170
195
|
* (rerunTarget) makes the re-verify after a rerun wait for newer attempts than the ones judged red.
|
|
171
196
|
*/
|
|
172
197
|
export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMaxMinutes = 360, now = () => Date.now(), sleep, random = Math.random,
|
|
173
|
-
push = async () => {}, exclude = [], onPoll = async () => {}, graceMs = DEFAULT_GRACE_MS, gate = null, rerunOf = null }) {
|
|
198
|
+
push = async () => {}, exclude = [], onPoll = async () => {}, graceMs = DEFAULT_GRACE_MS, gate = null, rerunOf = null, onSettle = () => {} }) {
|
|
174
199
|
const v = verify ?? parseVerify({});
|
|
200
|
+
// #5718: `fixed` never reads check suites; the two other modes need the seam, else they are `fixed` too.
|
|
201
|
+
const settleMode = SETTLE_MODES.includes(v.settle) && v.settle !== "fixed" && io?.checkSuites ? v.settle : "fixed";
|
|
202
|
+
const st = { prev: null, knownAt: null, knownNames: null, reported: false };
|
|
175
203
|
const files = verifiableFiles(changedFiles);
|
|
176
204
|
if (skipsCi(files, v.skipPaths)) return { result: "skipped", failures: [], runUrl: null, detail: `all ${files.length} changed file(s) match skip_paths` };
|
|
177
205
|
await push();
|
|
@@ -211,7 +239,20 @@ export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMa
|
|
|
211
239
|
const gating = gateSet ? latest.filter((c) => gateSet.has(c.name)) : [];
|
|
212
240
|
const relevant = gating.length ? gating : latest;
|
|
213
241
|
const missing = gateSet ? [...gateSet].filter((n) => !latest.some((c) => c.name === n)) : [];
|
|
214
|
-
|
|
242
|
+
let waitMissing = missing.length && now() - startedAt < graceMs;
|
|
243
|
+
if (settleMode !== "fixed" && missing.length && st.knownAt === null && waitMissing) {
|
|
244
|
+
let suites = null;
|
|
245
|
+
try { suites = await io.checkSuites(head); } catch { suites = null; } // unreadable: not known, keep waiting
|
|
246
|
+
const k = settleKnown({ suites, prev: st.prev, elapsedMs: now() - startedAt });
|
|
247
|
+
st.prev = suites ? k.ids : null;
|
|
248
|
+
if (k.known) { st.knownAt = now() - startedAt; st.knownNames = (gating.length ? gating : latest).map((c) => c.name).sort(); }
|
|
249
|
+
}
|
|
250
|
+
if (settleMode === "condition" && st.knownAt !== null) waitMissing = false;
|
|
251
|
+
if (settleMode !== "fixed" && missing.length && !waitMissing && !st.reported) {
|
|
252
|
+
st.reported = true;
|
|
253
|
+
const names = relevant.map((c) => c.name).sort();
|
|
254
|
+
try { onSettle({ mode: settleMode, missing, waited_ms: now() - startedAt, known_at_ms: st.knownAt, grace_ms: graceMs, agreed: st.knownNames === null ? null : JSON.stringify(st.knownNames) === JSON.stringify(names) }); } catch { /* a record, never a verdict */ }
|
|
255
|
+
}
|
|
215
256
|
if (relevant.length && !waitMissing && relevant.every((c) => c.state !== "pending")) {
|
|
216
257
|
const failed = relevant.filter((c) => c.state === "failure");
|
|
217
258
|
const ignored = gating.length ? latest.filter((c) => !gateSet.has(c.name) && c.state === "failure").map((c) => c.name) : [];
|
|
@@ -227,6 +268,37 @@ export async function runCiVerify({ io, branch, head, changedFiles, verify, ciMa
|
|
|
227
268
|
}
|
|
228
269
|
}
|
|
229
270
|
|
|
271
|
+
/** Events whose runs only verify a head; a push or dispatch run may deploy, so it is never cancelled here. */
|
|
272
|
+
export const SUPERSEDED_EVENTS = Object.freeze(["pull_request", "pull_request_target"]);
|
|
273
|
+
/**
|
|
274
|
+
* #5718: the runs of `branch` a push of `head` superseded (pure): queued or running, of a verification event, for another
|
|
275
|
+
* head sha, created before `pushedAt` when it is given, and under `own` triggered by `actor`. `runs`: [{id, headSha, status, event, actor, createdAt}].
|
|
276
|
+
*/
|
|
277
|
+
export function supersededRuns({ runs, head, mode = "own", actor = null, events = SUPERSEDED_EVENTS, pushedAt = null }) {
|
|
278
|
+
if (mode !== "own" && mode !== "all") return [];
|
|
279
|
+
if (!head || (mode === "own" && !actor)) return [];
|
|
280
|
+
const live = ["queued", "in_progress", "waiting", "pending", "requested"];
|
|
281
|
+
return (runs ?? []).filter((r) => r?.id != null && r.headSha && !sameSha(r.headSha, head) && live.includes(String(r.status).toLowerCase()) && events.includes(r.event)
|
|
282
|
+
&& (mode === "all" || String(r.actor ?? "").toLowerCase() === String(actor).toLowerCase()) && (pushedAt == null || !(Date.parse(r.createdAt) > pushedAt)));
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* #5718: cancel the superseded runs of `branch` after `head` was pushed. Seams: `io.branchRuns(branch)`, `io.cancelRun(id)`,
|
|
286
|
+
* `io.viewerLogin()` (only for `own`). Never throws and never touches a run of `head`: {cancelled: id[], failed: id[], skipped?: why}.
|
|
287
|
+
*/
|
|
288
|
+
export async function cancelSuperseded({ io, branch, head, mode = "off", pushedAt = null, dryRun = false }) {
|
|
289
|
+
if (mode !== "own" && mode !== "all") return { cancelled: [], failed: [], skipped: "off" };
|
|
290
|
+
if (!io?.branchRuns || !io?.cancelRun) return { cancelled: [], failed: [], skipped: "no seam" };
|
|
291
|
+
let runs = [], actor = null;
|
|
292
|
+
try { actor = mode === "own" ? await io.viewerLogin?.() : null; runs = (await io.branchRuns(branch)) ?? []; } catch { return { cancelled: [], failed: [], skipped: "runs unreadable" }; }
|
|
293
|
+
if (mode === "own" && !actor) return { cancelled: [], failed: [], skipped: "actor unknown" };
|
|
294
|
+
const out = { cancelled: [], failed: [] };
|
|
295
|
+
for (const r of supersededRuns({ runs, head, mode, actor, pushedAt })) {
|
|
296
|
+
if (dryRun) { out.cancelled.push(r.id); continue; }
|
|
297
|
+
try { await io.cancelRun(r.id); out.cancelled.push(r.id); } catch { out.failed.push(r.id); } // already finished (409) or no permission: the run just completes
|
|
298
|
+
}
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
230
302
|
const VALIDATE_KINDS = ["validate_missing", "validate_failed"], REQUIREMENT_KINDS = ["requirement_unimplemented", "untracked_deferral"];
|
|
231
303
|
/**
|
|
232
304
|
* #4270: the `forgedock/verify` check-run payload from the results the lane already computed (no gate logic of its own).
|
|
@@ -265,3 +337,26 @@ export function verifyReport({ head = null, commands = null, structure = null, u
|
|
|
265
337
|
if (json.length > VERIFY_TEXT_CAP) json = JSON.stringify({ head, conclusion, truncated: true, gates: gates.map((g) => ({ id: g.id, ok: g.ok, ran: g.ran, evidence: JSON.stringify(g.evidence).slice(0, Math.floor(VERIFY_TEXT_CAP / (gates.length + 1))) })) }, null, 2);
|
|
266
338
|
return { conclusion, gates, title, summary, text: "```json\n" + json + "\n```" };
|
|
267
339
|
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* #5718 `forgedock ci cancel-superseded (--pr N | --branch B) [--repo o/r] [--mode own|all] [--dry-run]`: cancel the
|
|
343
|
+
* verification runs an older head of a branch still has in flight. The mode comes from forge.yaml
|
|
344
|
+
* `verify.cancel_superseded` unless `--mode` is given; off does nothing. `deps`: {seams({repo}), gh(args), config, print}.
|
|
345
|
+
*/
|
|
346
|
+
export async function cancelSupersededFromCli(argv, deps) {
|
|
347
|
+
const print = deps.print ?? ((s) => process.stdout.write(`${s}\n`));
|
|
348
|
+
const opt = (name) => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith("--") ? argv[i + 1] : null; };
|
|
349
|
+
const pr = opt("--pr"), dryRun = argv.includes("--dry-run");
|
|
350
|
+
let branch = opt("--branch"), head = null;
|
|
351
|
+
const mode = opt("--mode") ? parseCancelSuperseded(opt("--mode")) : deps.config?.cancelSuperseded ?? "off";
|
|
352
|
+
const repo = opt("--repo") ?? deps.repo ?? null;
|
|
353
|
+
if (!repo || (!pr && !branch) || (pr && !/^\d+$/.test(pr))) { print("usage: forgedock ci cancel-superseded (--pr N | --branch B) [--repo owner/repo] [--mode own|all] [--dry-run]"); return 2; }
|
|
354
|
+
if (mode === "off") { print("cancel-superseded: off (set verify.cancel_superseded: own|all in forge.yaml, or pass --mode)"); return 0; }
|
|
355
|
+
try {
|
|
356
|
+
if (pr) { const v = JSON.parse(await deps.gh(["pr", "view", pr, "-R", repo, "--json", "headRefName,headRefOid"])); branch = v.headRefName; head = v.headRefOid; }
|
|
357
|
+
else head = String(await deps.gh(["api", `repos/${repo}/branches/${encodeURIComponent(branch)}`, "--jq", ".commit.sha"])).trim();
|
|
358
|
+
} catch (e) { print(`cancel-superseded: cannot read the head of ${pr ? `#${pr}` : branch}: ${String(e?.stderr ?? e?.message ?? e).split("\n")[0].slice(0, 200)}`); return 1; }
|
|
359
|
+
const r = await cancelSuperseded({ io: deps.seams({ repo }), branch, head, mode, dryRun });
|
|
360
|
+
print(`cancel-superseded: ${branch} at ${String(head).slice(0, 12)} (${mode}${dryRun ? ", dry run" : ""}): ${r.skipped ? `skipped (${r.skipped})` : `${r.cancelled.length} run(s) ${dryRun ? "would be cancelled" : "cancelled"}${r.cancelled.length ? `: ${r.cancelled.join(", ")}` : ""}${r.failed.length ? `; ${r.failed.length} could not be cancelled` : ""}`}`);
|
|
361
|
+
return r.skipped && r.skipped !== "off" ? 1 : 0;
|
|
362
|
+
}
|