forgedock 1.63.0 → 1.64.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.
Files changed (84) hide show
  1. package/bin/config-schema.mjs +3 -0
  2. package/bin/engine/outcome-codes.mjs +5 -0
  3. package/bin/engine-cli.mjs +88 -12
  4. package/bin/env/cli.mjs +18 -1
  5. package/bin/lean/basered.mjs +56 -11
  6. package/bin/lean/basered.test.mjs +58 -5
  7. package/bin/lean/batch-health.mjs +46 -4
  8. package/bin/lean/batch-health.test.mjs +55 -1
  9. package/bin/lean/batch.mjs +6 -1
  10. package/bin/lean/batch.test.mjs +71 -6
  11. package/bin/lean/ceiling.mjs +47 -3
  12. package/bin/lean/ceiling.test.mjs +32 -1
  13. package/bin/lean/conformance.e2e.test.mjs +32 -6
  14. package/bin/lean/conformance.mjs +57 -13
  15. package/bin/lean/conformance.test.mjs +93 -1
  16. package/bin/lean/execution.mjs +15 -6
  17. package/bin/lean/execution.test.mjs +44 -3
  18. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  19. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  20. package/bin/lean/issuewatch.mjs +3 -0
  21. package/bin/lean/lanecheck.test.mjs +13 -1
  22. package/bin/lean/lean.mjs +157 -28
  23. package/bin/lean/lean.test.mjs +289 -21
  24. package/bin/lean/live-execution.mjs +25 -0
  25. package/bin/lean/live-execution.test.mjs +35 -1
  26. package/bin/lean/merged-park.mjs +76 -0
  27. package/bin/lean/merged-park.test.mjs +64 -0
  28. package/bin/lean/mergetrain.mjs +357 -0
  29. package/bin/lean/mergetrain.test.mjs +348 -0
  30. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  31. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  32. package/bin/lean/orchestrate-train.test.mjs +130 -0
  33. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  34. package/bin/lean/orchestrate.mjs +159 -13
  35. package/bin/lean/prompts.mjs +4 -3
  36. package/bin/lean/release-review.mjs +8 -1
  37. package/bin/lean/release-review.test.mjs +42 -2
  38. package/bin/lean/release-status.test.mjs +53 -1
  39. package/bin/lean/release.mjs +6 -3
  40. package/bin/lean/render.mjs +6 -1
  41. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  42. package/bin/lean/sandbox-remote.mjs +12 -2
  43. package/bin/lean/sched.mjs +19 -2
  44. package/bin/lean/sched.test.mjs +33 -1
  45. package/bin/lean/schedd-health.mjs +2 -1
  46. package/bin/lean/schedd-health.test.mjs +7 -0
  47. package/bin/lean/schedd.mjs +55 -7
  48. package/bin/lean/schedd.test.mjs +42 -1
  49. package/bin/lean/stacking.mjs +45 -0
  50. package/bin/lean/stacking.test.mjs +25 -1
  51. package/bin/lean/statuscomment.mjs +14 -8
  52. package/bin/lean/statuscomment.test.mjs +18 -1
  53. package/bin/lean/validate-catalog.mjs +1 -1
  54. package/bin/lean/validate-catalog.test.mjs +3 -0
  55. package/bin/lean/worktree.mjs +8 -3
  56. package/bin/lean/worktree.test.mjs +18 -0
  57. package/bin/pool/agent.mjs +296 -31
  58. package/bin/pool/cli.mjs +120 -6
  59. package/bin/pool/disk.mjs +43 -0
  60. package/bin/pool/docker.mjs +10 -0
  61. package/bin/pool/health.mjs +95 -0
  62. package/bin/pool/router.mjs +274 -27
  63. package/bin/runner.mjs +3 -1
  64. package/bin/stats/chains.mjs +101 -0
  65. package/bin/stats/chains.test.mjs +53 -0
  66. package/bin/stats/efficiency.mjs +7 -6
  67. package/bin/stats/efficiency.test.mjs +48 -7
  68. package/bin/stats/index.mjs +11 -3
  69. package/bin/stats/stats.test.mjs +9 -0
  70. package/docs/CONFIG.md +8 -1
  71. package/docs/OUTCOME-CODES.md +4 -0
  72. package/package.json +1 -1
  73. package/pool/README.md +10 -0
  74. package/pool/image/Dockerfile +2 -1
  75. package/pool/image/entrypoint.sh +6 -6
  76. package/pool/image/mirror.sh +71 -0
  77. package/pool/install/install-agent-linux.sh +57 -5
  78. package/pool/install/install-agent-macos.sh +148 -0
  79. package/pool/install/install-agent.ps1 +11 -0
  80. package/pool/install/install-agent.sh +59 -7
  81. package/pool/install/uninstall-agent-linux.sh +75 -0
  82. package/pool/install/uninstall-agent-macos.sh +60 -0
  83. package/pool/install/uninstall-agent.ps1 +1 -0
  84. package/scripts/transition-label.sh +11 -0
@@ -0,0 +1,348 @@
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 { codeForTerminalReason } from "../engine/outcome-codes.mjs";
6
+ import { createMergeTrain, formatTrainSummary, judgeChecks, p50, waitP90, rollupStates } from "./mergetrain.mjs";
7
+
8
+ const H = "a".repeat(40);
9
+ /** A fake gh over `prs`: {pr: {state, head, mergeable, mergeState, base, branch, checks}}; records every call. */
10
+ function fake(prs, { mergeError = null } = {}) {
11
+ const calls = [];
12
+ const gh = async (a) => {
13
+ calls.push(a);
14
+ const sub = a.slice(0, 2).join(" ");
15
+ if (sub === "pr view") {
16
+ const p = prs[a[2]];
17
+ if (a.includes("headRefOid") && !a.join(",").includes("state,")) return JSON.stringify({ headRefOid: p.head });
18
+ if (a.join(",").endsWith("state")) return JSON.stringify({ state: p.state ?? "OPEN" });
19
+ return JSON.stringify({ state: p.state ?? "OPEN", headRefOid: p.head, headRefName: p.branch ?? `feat/${a[2]}`, mergeable: p.mergeable ?? "MERGEABLE", mergeStateStatus: p.mergeState ?? "CLEAN", baseRefName: p.base ?? "staging", statusCheckRollup: p.checks ?? [] });
20
+ }
21
+ if (sub === "pr merge") { if (mergeError) throw mergeError; prs[a[2]].state = "MERGED"; return ""; }
22
+ if (sub === "pr update-branch") { prs[a[2]].mergeState = "CLEAN"; prs[a[2]].head = "b".repeat(40); return ""; }
23
+ if (sub === "issue view") return JSON.stringify({ labels: [{ name: "workflow:in-progress" }] });
24
+ return "";
25
+ };
26
+ return { gh, calls };
27
+ }
28
+ const ok = (name) => ({ name, conclusion: "SUCCESS" });
29
+ const entry = (issue, pr, extra = {}) => ({ issue, pr, head: H, required: ["build"], policy: "required", lane: "staging", ...extra });
30
+
31
+ describe("mergetrain (#5836)", () => {
32
+ it("merges a green PR at the reviewed head, then closes, labels and deletes the branch", async () => {
33
+ const f = fake({ 5: { head: H, checks: [ok("build")] } });
34
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
35
+ const ev = await t.tick();
36
+ assert.deepEqual(ev.map((e) => [e.kind, e.issue]), [["merged", 1]]);
37
+ assert.deepEqual(f.calls.find((a) => a[1] === "merge").slice(-2), ["--match-head-commit", H]);
38
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "close" && a.includes("completed")));
39
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "edit" && a.includes("workflow:merged")));
40
+ assert.ok(f.calls.some((a) => a.join(" ").includes("DELETE repos/o/r/git/refs/heads/feat/5")));
41
+ assert.equal(t.size(), 0);
42
+ });
43
+ it("merges at most one PR per base per poll; another base merges in the same poll", async () => {
44
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, checks: [ok("build")] }, 7: { head: H, base: "milestone/x", checks: [ok("build")] } });
45
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5)); t.add(entry(2, 6)); t.add(entry(3, 7, { lane: "milestone/x" }));
46
+ assert.deepEqual((await t.tick()).map((e) => e.issue), [1, 3]);
47
+ assert.deepEqual((await t.tick()).map((e) => e.issue), [2]);
48
+ });
49
+ it("keeps a pending PR waiting and does not merge it", async () => {
50
+ const f = fake({ 5: { head: H, checks: [{ name: "build", status: "IN_PROGRESS", conclusion: "" }] } });
51
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
52
+ assert.deepEqual(await t.tick(), []);
53
+ assert.equal(t.size(), 1);
54
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
55
+ });
56
+ it("updates a green PR that is behind its base, then merges once the head is current", async () => {
57
+ const f = fake({ 5: { head: H, mergeState: "BEHIND", checks: [ok("build")] } });
58
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
59
+ assert.deepEqual(await t.tick(), []);
60
+ assert.ok(f.calls.some((a) => a.slice(0, 3).join(" ") === "pr update-branch 5"));
61
+ assert.equal(t.stats().syncs, 1);
62
+ assert.equal(t.snapshot().entries[0].head, "b".repeat(40), "the train adopts the synced head");
63
+ });
64
+ it("hands a red PR back as ci.red naming the failing checks and their URLs", async () => {
65
+ const f = fake({ 5: { head: H, checks: [{ name: "build", conclusion: "FAILURE", detailsUrl: "https://ci/run/9" }] } });
66
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5));
67
+ const [e] = await t.tick();
68
+ assert.equal(e.kind, "handback"); assert.equal(e.code, "ci.red");
69
+ assert.match(e.detail, /- build https:\/\/ci\/run\/9/);
70
+ assert.equal(t.stats().handedBack["ci.red"], 1);
71
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
72
+ });
73
+ it("hands a conflicting PR back as base.conflict and a moved head as merge.head_mismatch", async () => {
74
+ const f = fake({ 5: { head: H, mergeable: "CONFLICTING", checks: [ok("build")] }, 6: { head: "c".repeat(40), checks: [ok("build")] } });
75
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5)); t.add(entry(2, 6));
76
+ assert.deepEqual((await t.tick()).map((e) => e.code), ["base.conflict", "merge.head_mismatch"]);
77
+ assert.ok(!f.calls.some((a) => a[1] === "merge"));
78
+ });
79
+ it("a merge refused because the head moved is handed back; a transient failure is retried", async () => {
80
+ const moved = fake({ 5: { head: H, checks: [ok("build")] } }, { mergeError: Object.assign(new Error("Head branch was modified"), { stderr: "" }) });
81
+ const t = createMergeTrain({ gh: moved.gh, repo: "o/r" }); t.add(entry(1, 5));
82
+ assert.equal((await t.tick())[0].code, "merge.head_mismatch");
83
+ const flaky = fake({ 5: { head: H, checks: [ok("build")] } }, { mergeError: new Error("502 bad gateway") });
84
+ const t2 = createMergeTrain({ gh: flaky.gh, repo: "o/r" }); t2.add(entry(1, 5));
85
+ assert.deepEqual(await t2.tick(), []); assert.equal(t2.size(), 1);
86
+ });
87
+ it("persists through snapshot and restore, with stats and the p50 wait", async () => {
88
+ let clock = 0;
89
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, base: "other", checks: [ok("build")] } });
90
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r", now: () => clock }); t.add(entry(1, 5)); t.add(entry(2, 6, { lane: "other" }));
91
+ clock = 60000; await t.tick();
92
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
93
+ const t2 = createMergeTrain({ gh: f.gh, repo: "o/r" }); t2.restore(snap);
94
+ assert.equal(t2.stats().merged, 2); assert.deepEqual(t2.stats().waits, [60000, 60000]);
95
+ assert.equal(p50([30000, 60000, 90000]), 60000); assert.equal(p50([]), null);
96
+ });
97
+ it("pr-ready carries the awaiting_merge code", () => assert.equal(codeForTerminalReason("pr-ready"), "awaiting_merge"));
98
+ it("formats the batch report line", () => {
99
+ assert.equal(formatTrainSummary({ merged: 3, handedBack: { "ci.red": 1, "base.conflict": 1 }, waits: [60000, 120000], syncs: 2 }), "merge train: merged 3, handed back 2 (base.conflict 1, ci.red 1), wait p50 1.0 min p90 2.0 min, base-syncs 2 (lane 0), base.conflict 1 (lane 0)");
100
+ assert.equal(formatTrainSummary({ merged: 0, handedBack: {}, waits: [], syncs: 0 }), null);
101
+ });
102
+ it("judges policy all and required checks", () => {
103
+ const st = rollupStates([ok("a"), { name: "b", status: "IN_PROGRESS" }]);
104
+ assert.equal(judgeChecks(st, { required: ["a"] }).green, true);
105
+ assert.equal(judgeChecks(st, { required: ["a", "missing"] }).green, false);
106
+ assert.equal(judgeChecks(st, { policy: "all" }).green, false);
107
+ });
108
+ });
109
+
110
+ /** #5837: a fake gh with candidate-ref support on top of `fake`. `conflict` = PR heads whose candidate merge 409s. */
111
+ function batchWorld(prs, { conflict = [], runs = [{ name: "build", status: "completed", conclusion: "success" }], mergeRefuse = null } = {}) {
112
+ const f = fake(prs); const refs = new Set(); let checkRuns = runs;
113
+ const gh = async (a) => {
114
+ const s = a.join(" ");
115
+ if (s.includes("/git/ref/heads/") && !s.includes("forge-train")) return JSON.stringify({ object: { sha: "c".repeat(40) } });
116
+ if (s.includes("/git/ref/heads/forge-train")) { f.calls.push(a); return JSON.stringify({ object: { sha: "d".repeat(40) } }); }
117
+ if (s.startsWith("api -X POST repos/o/r/git/refs")) { f.calls.push(a); refs.add(a[5].slice(15)); return "{}"; }
118
+ if (s.startsWith("api -X POST repos/o/r/merges")) { f.calls.push(a); const head = a.find((x) => x.startsWith("head=")).slice(5); if (conflict.includes(head)) throw Object.assign(new Error("Merge conflict (HTTP 409)"), { stderr: "" }); return "{}"; }
119
+ if (s.startsWith("api -X DELETE repos/o/r/git/refs/heads/forge-train")) { f.calls.push(a); refs.delete(a[3].split("/heads/")[1]); return ""; }
120
+ if (s.startsWith("api -X POST repos/o/r/actions")) { f.calls.push(a); return ""; }
121
+ if (s.includes("/check-runs")) { f.calls.push(a); return JSON.stringify({ check_runs: checkRuns }); }
122
+ if (s.includes("compare/")) return JSON.stringify({ files: [{ filename: "x.js" }] });
123
+ if (a[0] === "pr" && a[1] === "view" && a.includes("files")) return JSON.stringify({ files: [{ path: "x.js" }, { path: "y.js" }] });
124
+ if (a[0] === "pr" && a[1] === "merge" && mergeRefuse === a[2]) { f.calls.push(a); throw new Error("base branch policy prohibits the merge"); }
125
+ return f.gh(a);
126
+ };
127
+ return { gh, calls: f.calls, refs, setRuns: (r) => { checkRuns = r; } };
128
+ }
129
+ const hd = (c) => c.repeat(40);
130
+ const bprs = () => ({ 5: { head: hd("1"), mergeState: "BEHIND", checks: [ok("build")] }, 6: { head: hd("2"), mergeState: "BEHIND", checks: [ok("build")] }, 7: { head: hd("3"), mergeState: "BEHIND", checks: [ok("build")] } });
131
+ const eb = (issue, pr, head) => entry(issue, pr, { head });
132
+ const fill = (t) => { t.add(eb(1, 5, hd("1"))); t.add(eb(2, 6, hd("2"))); t.add(eb(3, 7, hd("3"))); };
133
+
134
+ describe("mergetrain batches (#5837)", () => {
135
+ it("N BEHIND PRs share one candidate CI run, no update-branch, merged FIFO at their heads", async () => {
136
+ const w = batchWorld(bprs()); let clock = 0;
137
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
138
+ assert.deepEqual(await t.tick(), []); // builds + validating
139
+ assert.ok(w.refs.size === 1 && [...w.refs][0].startsWith("forge-train/staging/"));
140
+ const merges = w.calls.filter((a) => a[0] === "api" && a[3] === "repos/o/r/merges");
141
+ assert.equal(merges.length, 3);
142
+ assert.ok(merges.every((a) => a.includes("base=" + [...w.refs][0])), "merge into the candidate, never a rebase");
143
+ assert.equal(t.snapshot().batches[0].state, "validating");
144
+ assert.deepEqual(await t.tick(), []); // candidate checks green -> merging
145
+ const all = await t.tick(); // merges the batch in order
146
+ assert.deepEqual(all.map((e) => e.issue), [1, 2, 3]);
147
+ const pm = w.calls.filter((a) => a[1] === "merge").map((a) => [a[2], a.at(-1)]);
148
+ assert.deepEqual(pm.slice(0, 3), [["5", hd("1")], ["6", hd("2")], ["7", hd("3")]]);
149
+ assert.equal(w.calls.filter((a) => a[1] === "update-branch").length, 0);
150
+ assert.equal(w.refs.size, 0, "candidate ref deleted when finished");
151
+ assert.equal(t.stats().candidateRuns, 1);
152
+ assert.equal(t.stats().merged, 3);
153
+ assert.match(formatTrainSummary(t.stats()), /batches 1, candidate CI runs 1/);
154
+ });
155
+ it("a conflict on the candidate removes only that PR, as base.conflict with the files; the rest merge", async () => {
156
+ const w = batchWorld(bprs(), { conflict: [hd("2")] }); let clock = 0;
157
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
158
+ const ev = await t.tick();
159
+ assert.deepEqual(ev.map((e) => [e.kind, e.issue, e.code]), [["handback", 2, "base.conflict"]]);
160
+ assert.match(ev[0].detail, /x\.js/);
161
+ assert.deepEqual(t.snapshot().batches[0].prs.map((p) => p.pr), [5, 7]);
162
+ await t.tick(); await t.tick();
163
+ assert.deepEqual(w.calls.filter((a) => a[1] === "merge").map((a) => a[2]), ["5", "7"]);
164
+ });
165
+ it("a protection refusal keeps the PR in the train and holds order", async () => {
166
+ const w = batchWorld(bprs(), { mergeRefuse: "5" }); let clock = 0;
167
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
168
+ await t.tick(); await t.tick(); await t.tick();
169
+ assert.equal(t.size(), 3);
170
+ assert.deepEqual([...new Set(w.calls.filter((a) => a[1] === "merge").map((a) => a[2]))], ["5"]);
171
+ });
172
+ it("a restored validating batch re-reads the candidate checks and does not rebuild it", async () => {
173
+ const w = batchWorld(bprs(), { runs: [{ name: "build", status: "in_progress", conclusion: null }] }); let clock = 0;
174
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
175
+ await t.tick();
176
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
177
+ const before = w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length;
178
+ const t2 = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved: snap, now: () => ++clock });
179
+ await t2.tick();
180
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length, before);
181
+ assert.equal(t2.snapshot().batches[0].state, "validating");
182
+ assert.equal(t2.stats().candidateRuns, 1);
183
+ });
184
+ it("a candidate red on the bare base tip too deletes the ref, hands back nothing and goes on serially, without re-batching (#5838)", async () => {
185
+ const w = batchWorld(bprs(), { runs: [{ name: "build", status: "completed", conclusion: "failure" }] }); let clock = 0;
186
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill(t);
187
+ assert.deepEqual([...await t.tick(), ...await t.tick(), ...await t.tick()], []);
188
+ assert.equal(w.refs.size, 0);
189
+ assert.equal(t.snapshot().batches.length, 0);
190
+ assert.equal(t.stats().candidateRed, 1);
191
+ await t.tick();
192
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 1, "no second candidate");
193
+ assert.ok(w.calls.some((a) => a[1] === "update-branch"), "serial sync resumed");
194
+ });
195
+ it("batchSize 1 keeps the serial train: no candidate calls", async () => {
196
+ const w = batchWorld(bprs());
197
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r" }); fill(t);
198
+ await t.tick();
199
+ assert.ok(!w.calls.some((a) => a[0] === "api" && String(a[3]).includes("merges")));
200
+ assert.equal(t.stats().batches, 0);
201
+ });
202
+ it("the summary line stays unchanged without batches", () => {
203
+ assert.ok(!/batches/.test(formatTrainSummary({ merged: 1, handedBack: {}, waits: [0], syncs: 0 })));
204
+ });
205
+ });
206
+
207
+ /** #5838: candidate refs whose sha names the PR heads merged into them; `bad(heads)` says whether `build` fails on that tree. */
208
+ function bisectWorld(prs, { bad, baseRed = false, rerunGreen = false, stuck = null } = {}) {
209
+ const f = fake(prs); const refs = new Map(); const reruns = new Set(); let ids = 100; const runIds = new Map();
210
+ const shaOf = (r) => `t_${r.replaceAll("/", "~")}_${refs.get(r).join(",")}`;
211
+ const runOf = (sha) => { if (!runIds.has(sha)) runIds.set(sha, ids++); return runIds.get(sha); };
212
+ const gh = async (a) => {
213
+ const s = a.join(" ");
214
+ if (s.includes("/git/ref/heads/") && !s.includes("forge-train")) return JSON.stringify({ object: { sha: "base" } });
215
+ if (s.includes("/git/ref/heads/forge-train")) return JSON.stringify({ object: { sha: shaOf(s.split("/git/ref/heads/")[1]) } });
216
+ if (s.startsWith("api -X POST repos/o/r/git/refs")) { f.calls.push(a); refs.set(a[5].slice(15), []); return "{}"; }
217
+ if (s.startsWith("api -X POST repos/o/r/merges")) { f.calls.push(a); refs.get(a.find((x) => x.startsWith("base=")).slice(5)).push(a.find((x) => x.startsWith("head=")).slice(5, 6)); return "{}"; }
218
+ if (s.startsWith("api -X DELETE repos/o/r/git/refs/heads/forge-train")) { f.calls.push(a); refs.delete(a[3].split("/heads/")[1]); return ""; }
219
+ if (s.startsWith("api -X POST repos/o/r/actions/jobs/")) { f.calls.push(a); reruns.add(Number(a[3].split("/")[5])); return ""; }
220
+ if (s.includes("/check-runs")) {
221
+ f.calls.push(a);
222
+ const sha = a[1].split("/")[4];
223
+ if (sha === "base") return JSON.stringify({ check_runs: [{ id: 1, name: "build", status: "completed", conclusion: baseRed ? "failure" : "success", html_url: "https://ci/base" }] });
224
+ const heads = sha.split("_")[2].split(",");
225
+ if (stuck && stuck(heads)) return JSON.stringify({ check_runs: [{ id: runOf(sha), name: "build", status: "in_progress", conclusion: null }] });
226
+ const id = runOf(sha), out = [{ id, name: "build", status: "completed", conclusion: bad(heads) ? "failure" : "success", html_url: `https://ci/${heads.join("")}` }];
227
+ if (reruns.has(id)) out.push({ id: id + 1000, name: "build", status: "completed", conclusion: rerunGreen || !bad(heads) ? "success" : "failure", html_url: `https://ci/${heads.join("")}/rerun` });
228
+ return JSON.stringify({ check_runs: out });
229
+ }
230
+ return f.gh(a);
231
+ };
232
+ return { gh, calls: f.calls, refs };
233
+ }
234
+ const four = () => Object.fromEntries([5, 6, 7, 8].map((pr, i) => [pr, { head: hd(String(i + 1)), checks: [ok("build")] }]));
235
+ const fill4 = (t) => [5, 6, 7, 8].forEach((pr, i) => t.add(eb(i + 1, pr, hd(String(i + 1)))));
236
+ const ticks = async (t, n) => { const out = []; for (let i = 0; i < n; i++) out.push(...await t.tick()); return out; };
237
+
238
+ describe("mergetrain bisection (#5838)", () => {
239
+ it("isolates the culprit of 4 within ceil(log2 4)+1 runs; only it is handed back, the innocents merge in the next batch", async () => {
240
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
241
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill4(t);
242
+ const ev = await ticks(t, 6);
243
+ const hb = ev.filter((e) => e.kind === "handback");
244
+ assert.deepEqual(hb.map((e) => [e.issue, e.code]), [[3, "ci.red"]]);
245
+ const batchId = [...w.calls.filter((a) => a[3] === "repos/o/r/git/refs")][0][5].split("/").at(-1);
246
+ assert.deepEqual(hb[0].culprit, { pr: 7, check: "build", url: "https://ci/3", batch: batchId });
247
+ assert.match(hb[0].detail, new RegExp(`broke the merged tree of train batch ${batchId}.*build`));
248
+ const runsSpent = t.stats().candidateRuns - 1; // the original candidate run is not a bisection step
249
+ assert.ok(runsSpent <= Math.ceil(Math.log2(4)) + 1, `spent ${runsSpent}`);
250
+ assert.equal(t.stats().bisections, 1); assert.equal(t.stats().culprits, 1);
251
+ // half candidates hold the FIFO first half: PRs 5,6 then 7
252
+ assert.deepEqual(w.calls.filter((a) => a[3] === "repos/o/r/merges" && /bisect/.test(a.at(-1))).map((a) => a.at(-1).split("#")[1]), ["5", "6", "7"]);
253
+ const rest = await ticks(t, 4);
254
+ assert.deepEqual(rest.filter((e) => e.kind === "merged").map((e) => e.issue), [1, 2, 4]);
255
+ assert.equal(t.stats().batches, 2, "the innocents shared a second batch");
256
+ assert.equal(w.calls.filter((a) => a[1] === "update-branch").length, 0, "no serial fallback, no lane rerun");
257
+ assert.equal(w.refs.size, 0, "every candidate ref deleted");
258
+ assert.match(formatTrainSummary(t.stats()), /batches 2, candidate CI runs \d+ \(1 red\), bisections 1, culprits 1/);
259
+ });
260
+ it("a red base tip calls onBaseRed, hands back no PR and builds no candidate on that tip again", async () => {
261
+ const w = bisectWorld(four(), { bad: () => true, baseRed: true }); let clock = 0; const reported = [];
262
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock, onBaseRed: async (r) => { reported.push(r); } }); fill4(t);
263
+ const ev = await ticks(t, 4);
264
+ assert.ok(!ev.some((e) => e.kind === "handback"));
265
+ assert.equal(reported.length, 1);
266
+ assert.equal(reported[0].baseSha, "base"); assert.deepEqual(reported[0].checks.map((c) => c.name), ["build"]);
267
+ assert.equal(t.stats().bisections, 0); assert.equal(t.stats().redBase, 1); assert.equal(t.size(), 4);
268
+ await ticks(t, 2);
269
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 1, "no new candidate on the red tip");
270
+ assert.equal(JSON.parse(JSON.stringify(t.snapshot())).redBases.staging, "base");
271
+ });
272
+ it("a known-flaky check green on its one rerun merges the batch without bisection", async () => {
273
+ const w = bisectWorld(four(), { bad: () => true, rerunGreen: true }); let clock = 0;
274
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock, flaky: ["build"] }); fill4(t);
275
+ const ev = await ticks(t, 4);
276
+ assert.equal(w.calls.filter((a) => String(a[3]).includes("/actions/jobs/")).length, 1, "rerun once");
277
+ assert.deepEqual(ev.map((e) => e.kind), ["merged", "merged", "merged", "merged"]);
278
+ assert.equal(t.stats().bisections, 0); assert.equal(t.stats().culprits, 0);
279
+ });
280
+ it("a half that never finishes exhausts the budget: the whole batch falls back to serial phase-1 merging", async () => {
281
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3"), stuck: (h) => h.length === 2 }); let clock = 0;
282
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, batchTimeoutMs: 5, now: () => (clock += 3) }); fill4(t);
283
+ const ev = await ticks(t, 6);
284
+ assert.ok(!ev.some((e) => e.kind === "handback"));
285
+ assert.equal(t.snapshot().batches.length, 0);
286
+ assert.ok(t.snapshot().entries.every((e) => e.noBatch), "every member serial");
287
+ });
288
+ it("a spent run budget goes serial instead of building another half", async () => {
289
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
290
+ const saved = { entries: [5, 6, 7, 8].map((pr, i) => ({ ...eb(i + 1, pr, hd(String(i + 1))), since: 1 })), stats: { merged: 0, handedBack: {}, waits: [], syncs: 0, batches: 1, candidateRuns: 3 },
291
+ batches: [{ id: "x", base: "staging", baseSha: "base", prs: [5, 6, 7, 8].map((pr, i) => ({ issue: i + 1, pr, head: hd(String(i + 1)) })), candidate: "forge-train/staging/x", candSha: "t_forge-train~staging~x_1,2,3,4", state: "bisecting", startedAt: 1,
292
+ bisect: { runs: 3, budget: 3, failed: [{ name: "build", url: "u" }], frame: [3, 4], step: "probe", stale: [], at: 1, halves: 2 } }] };
293
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved, now: () => ++clock });
294
+ assert.deepEqual(await t.tick(), []);
295
+ assert.ok(t.snapshot().entries.every((e) => e.noBatch)); assert.equal(t.snapshot().batches.length, 0);
296
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs").length, 0);
297
+ });
298
+ it("a resume mid-bisection re-reads the half's checks and rebuilds nothing; a phase-2a snapshot still restores", async () => {
299
+ const w = bisectWorld(four(), { bad: (h) => h.includes("3") }); let clock = 0;
300
+ const t = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, now: () => ++clock }); fill4(t);
301
+ await ticks(t, 3); // build, red -> rerun, rerun red -> probe
302
+ await t.tick(); // probe green -> first half built
303
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
304
+ assert.equal(snap.batches[0].bisect.step, "half");
305
+ const built = w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length;
306
+ const t2 = createMergeTrain({ gh: w.gh, repo: "o/r", batchSize: 4, saved: snap, now: () => ++clock });
307
+ await t2.tick();
308
+ assert.equal(w.calls.filter((a) => a[3] === "repos/o/r/git/refs" || a[3] === "repos/o/r/merges").length, built + 2, "only the next half (one ref + one merge)");
309
+ assert.deepEqual(t2.snapshot().batches[0].bisect.frame, [3, 4]);
310
+ const old = createMergeTrain({ gh: w.gh, repo: "o/r", saved: { entries: [], stats: { merged: 1, handedBack: {}, waits: [], syncs: 0, batches: 1, candidateRuns: 1 }, batches: [] } });
311
+ assert.deepEqual([old.stats().bisections, old.stats().culprits], [0, 0]);
312
+ });
313
+ });
314
+
315
+ describe("mergetrain phase 3 (#5839)", () => {
316
+ it("replays the post-merge record: notes are posted and a keepOpen record leaves the issue open", async () => {
317
+ const f = fake({ 5: { head: H, checks: [ok("build")] }, 6: { head: H, checks: [ok("build")], base: "main" } });
318
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" });
319
+ t.add(entry(1, 5, { postMerge: { keepOpen: true, notes: [{ marker: "FORGE:TRACKED", body: "left open" }] } }));
320
+ await t.tick();
321
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "comment" && a.join(" ").includes("FORGE:TRACKED")));
322
+ assert.ok(!f.calls.some((a) => a[0] === "issue" && a[1] === "close"), "keepOpen: not closed");
323
+ t.add(entry(2, 6, { lane: "main" }));
324
+ await t.tick();
325
+ assert.ok(f.calls.some((a) => a[0] === "issue" && a[1] === "close"), "a plain entry closes");
326
+ });
327
+ it("counts base.conflict hand-backs and lane-side counts per batch; p90 in the report line", async () => {
328
+ const f = fake({ 5: { head: H, mergeable: "CONFLICTING", checks: [ok("build")] } });
329
+ const t = createMergeTrain({ gh: f.gh, repo: "o/r" }); t.add(entry(1, 5, { laneSide: { syncs: 2, baseConflicts: 1 } }));
330
+ const ev = await t.tick();
331
+ assert.equal(ev[0].code, "base.conflict");
332
+ const st = t.stats();
333
+ assert.equal(st.baseConflicts, 1); assert.deepEqual(st.laneSide, { syncs: 2, baseConflicts: 1 });
334
+ assert.match(formatTrainSummary({ ...st, waits: [60000, 120000, 600000] }), /p90 10\.0 min.*base\.conflict 1 \(lane 1\)/);
335
+ assert.equal(waitP90([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 9);
336
+ });
337
+ it("snapshot round-trips the record and counts; a phase-2 snapshot restores as zero", () => {
338
+ const t = createMergeTrain({ gh: async () => "", repo: "o/r" });
339
+ t.add(entry(1, 5, { postMerge: { keepOpen: false, notes: [] }, laneSide: { syncs: 1, baseConflicts: 0 } }));
340
+ const snap = JSON.parse(JSON.stringify(t.snapshot()));
341
+ const t2 = createMergeTrain({ gh: async () => "", repo: "o/r", saved: snap });
342
+ assert.deepEqual(t2.snapshot().entries[0].postMerge, { keepOpen: false, notes: [] }); assert.equal(t2.stats().laneSide.syncs, 1);
343
+ const old = { entries: [], stats: { merged: 2, handedBack: {}, waits: [], syncs: 1 } };
344
+ const t3 = createMergeTrain({ gh: async () => "", repo: "o/r", saved: old });
345
+ assert.deepEqual([t3.stats().baseConflicts, t3.stats().laneSide], [0, { syncs: 0, baseConflicts: 0 }]);
346
+ t3.restore(old); assert.equal(t3.stats().baseConflicts, 0);
347
+ });
348
+ });
@@ -243,3 +243,65 @@ describe("#5755 one env issue per signature", () => {
243
243
  assert.equal(byIssue[1].envHold.envIssue, undefined);
244
244
  });
245
245
  });
246
+
247
+ describe("#5859 agent restart: correlated sandbox loss is sandbox.lost, not engine-error", () => {
248
+ const LOST = (n, agent = "legion") => ({ terminalReason: "engine-error", detail: `sandbox fake-${n} exited without a result`, lostWithoutResult: true, agent });
249
+ const BREAKER = { errors: 3, window_min: 10 };
250
+
251
+ it("agent restart: 20 lanes lost on one agent are sandbox.lost, not engine-errors", async () => {
252
+ const issues = Array.from({ length: 20 }, (_, i) => i + 1);
253
+ const script = Object.fromEntries(issues.map((n) => [n, [LOST(n), MERGED]]));
254
+ const store = memStore(), logged = [];
255
+ store.log = (ev) => logged.push(ev);
256
+ let probes = 0; // the agent is still booting for its first two probes, then reports a fresh boot
257
+ const r = await harness({ script, issues, parallel: 20, store, envHold: undefined,
258
+ extra: { envHold: null, breaker: BREAKER, remote: { agentHealthy: async () => ++probes > 2 } } });
259
+ assert.ok(!r.updates.some((u) => u.outcome === "breaker"), "the breaker never trips");
260
+ const lost = r.updates.filter((u) => u.code === "sandbox.lost");
261
+ assert.deepEqual([...new Set(lost.map((u) => u.issue))].sort((a, b) => a - b), issues, "all 20 requeued with sandbox.lost");
262
+ for (const n of issues) assert.equal(r.byIssue[n].outcome, "merged", `#${n} admitted again once the agent is healthy`);
263
+ assert.equal(r.calls.length, 40, "each lane relaunched exactly once");
264
+ const st = store.load();
265
+ assert.deepEqual(st.engineErrors, {}, "relaunch counters unchanged");
266
+ assert.deepEqual(st.errorTimes, [], "nothing counted by the breaker");
267
+ assert.equal(st.breaker, null);
268
+ const ev = logged.filter((e) => e.event === "agent.restarted");
269
+ assert.equal(ev.length, 1, "one batch-level event");
270
+ assert.equal(ev[0].requeued, 20);
271
+ assert.match(ev[0].detail, /^agent legion restarted at \d{4}-.*Z; 20 lanes requeued$/);
272
+ assert.equal(r.updates.filter((u) => u.event === "agent.restarted").length, 1);
273
+ assert.equal(st.agentRestarts.length, 1);
274
+ assert.equal(st.agentRestarts[0].requeued, 20);
275
+ assert.ok(probes >= 3, "admission waited for the agent's healthy probe");
276
+ });
277
+
278
+ it("agent restart: failure after healthy is an ordinary engine-error", async () => {
279
+ const store = memStore();
280
+ const r = await harness({ script: { 1: [LOST(1), LOST(1), MERGED], 2: [LOST(2), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
281
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 5, window_min: 10 } } });
282
+ assert.deepEqual(r.calls.filter((c) => c.n === 1).length, 3, "#1: sandbox.lost requeue, then the ordinary single relaunch");
283
+ assert.ok(r.updates.some((u) => u.issue === 1 && /^relaunching once: sandbox fake-1/.test(u.detail ?? "")));
284
+ const st = store.load();
285
+ assert.deepEqual(st.engineErrors, { 1: 1 });
286
+ assert.equal(st.errorTimes.length, 1, "the second loss of #1 counts toward the breaker");
287
+ for (const n of [1, 2, 3]) assert.equal(r.byIssue[n].outcome, "merged");
288
+ });
289
+
290
+ it("two unrelated sandbox exits stay engine-errors", async () => {
291
+ const store = memStore();
292
+ const r = await harness({ script: { 1: [LOST(1), MERGED], 2: [LOST(2, "box2"), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
293
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 5, window_min: 10 } } });
294
+ // #1 and #3 share an agent (2 < 3), #2 is on another: no restart
295
+ assert.ok(!r.updates.some((u) => u.code === "sandbox.lost" || u.event === "agent.restarted"));
296
+ const st = store.load();
297
+ assert.deepEqual(st.engineErrors, { 1: 1, 2: 1, 3: 1 });
298
+ assert.equal(st.errorTimes.length, 3, "each counts toward the breaker as today");
299
+ assert.equal(st.agentRestarts, undefined);
300
+ });
301
+
302
+ it("two lost lanes with a 3-error breaker still trip it", async () => {
303
+ const r = await harness({ script: { 1: [LOST(1), EE("real bug")], 2: [LOST(2, "box2"), EE("real bug 2")] }, issues: [1, 2], parallel: 2,
304
+ envHold: undefined, extra: { envHold: null, breaker: { errors: 2, window_min: 10 } } });
305
+ assert.ok(r.updates.some((u) => u.outcome === "breaker"));
306
+ });
307
+ });
@@ -39,6 +39,7 @@ describe("orchestrate stacking (#5831)", () => {
39
39
  assert.deepEqual(h.calls.map((c) => [c.n, !!c.ctx.plan]), [[1, false], [2, true], [2, false]]);
40
40
  assert.deepEqual(h.calls[2].ctx.planned, { contractHash: HASH, baseSha: SHA });
41
41
  assert.deepEqual(h.updates.filter((u) => u.issue === 2).map((u) => u.outcome), ["planned", "merged"]);
42
+ assert.ok(h.updates.find((u) => u.issue === 2 && u.outcome === "merged").plan_minutes >= 0, "#5834: plan lane minutes ride the final row");
42
43
  assert.deepEqual(h.events.filter((e) => e.event?.startsWith("STACK_")).map((e) => e.event), ["STACK_PLAN_START", "STACK_PLANNED"]);
43
44
  });
44
45
  it("plan: one plan lane per issue; a failed plan lane is plan-failed, not counted, and the build lane runs without ctx.planned", async () => {
@@ -91,6 +92,8 @@ describe("orchestrate stacked builds, phase 2 (#5832)", () => {
91
92
  assert.equal(ev.issue, 2); assert.equal(ev.stacked, true);
92
93
  const row = h.updates.find((u) => u.issue === 2 && u.outcome === "merged");
93
94
  assert.equal(row.stacked, true); assert.equal(row.stackedOn.dependency, 1);
95
+ assert.deepEqual(row.deps, [1], "#5834: the row carries its in-batch edges");
96
+ assert.ok(Number.isFinite(row.admitted_at) && row.ended_at >= row.admitted_at, "#5834: admission and end timestamps");
94
97
  });
95
98
  it("full: nothing is stacked before the dependency is PR-ready (it falls back to waiting for the merge)", async () => {
96
99
  let ready = false;
@@ -118,5 +121,24 @@ describe("orchestrate stacked builds, phase 2 (#5832)", () => {
118
121
  assert.deepEqual(saved.stackedTried, [2]);
119
122
  assert.equal(saved.stacked[2].dependency, 1);
120
123
  });
124
+ it("cascade (#5833): a stack.replan end requeues the dependent as a normal lane; the row records the cascade and its rework", async () => {
125
+ let gate; const g = new Promise((r) => { gate = r; });
126
+ const calls = [];
127
+ const runOne = async (n, lane, ctx = {}) => {
128
+ calls.push({ n, ctx });
129
+ if (n === 1) { await g; return { terminalReason: "merged", cost_usd: 0 }; }
130
+ if (ctx.plan) return { terminalReason: "planned", planned: { contractHash: HASH, baseSha: SHA } };
131
+ if (ctx.stackedOn) { gate(); return { terminalReason: "deferred", code: "stack.replan", cascade: "replan", cascades: ["replan"], cascade_cost_usd: 0.25, cascade_minutes: 2, cost_usd: 0.25, detail: "dependency ended unsatisfied" }; }
132
+ return { terminalReason: "merged", cost_usd: 0 };
133
+ };
134
+ const updates = [], events = [];
135
+ const store = { load: () => null, save: () => {}, log: (r) => events.push(r) };
136
+ await orchestrate({ issues: [1, 2], parallel: 2, readBody: body, runOne, stacking: "full", readPrReady: async () => RD, store, onUpdate: (r) => updates.push(r), maxDeferrals: 2 });
137
+ const cas = updates.find((u) => u.issue === 2 && u.cascade);
138
+ assert.equal(cas.cascade, "replan"); assert.equal(cas.stacked, true); assert.equal(cas.cascade_cost_usd, 0.25);
139
+ assert.ok(events.some((e) => e.event === "STACK_CASCADE" && e.issue === 2 && e.cascade === "replan"));
140
+ const later = calls.filter((c) => c.n === 2 && !c.ctx.plan && !c.ctx.stackedOn);
141
+ assert.equal(later.length, 1, "rebuilt as a normal lane");
142
+ assert.equal(updates.filter((u) => u.issue === 2).pop().outcome, "merged");
143
+ });
121
144
  });
122
-
@@ -0,0 +1,130 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5836: the merge train in the batch runner: pr-ready frees the slot, dependents wait, hand-backs recover, resume continues.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { orchestrate } from "./orchestrate.mjs";
8
+ import { createMergeTrain, formatTrainSummary } from "./mergetrain.mjs";
9
+
10
+ process.env.FORGEDOCK_SCHED_DIR = tmpDir("train-sched-");
11
+ const H = "a".repeat(40);
12
+ const READY = (pr) => ({ terminalReason: "pr-ready", pr, head: H, required: ["build"], policy: "required", lane: "staging" });
13
+ /** A fake gh: `checks[pr]` is the list of rollups the PR shows poll by poll (the last repeats). */
14
+ function world(checks) {
15
+ const merged = new Set(), calls = [];
16
+ const gh = async (a) => {
17
+ calls.push(a);
18
+ if (a[0] === "pr" && a[1] === "view") {
19
+ const pr = Number(a[2]); const seq = checks[pr]; const c = seq.length > 1 ? seq.shift() : seq[0];
20
+ return JSON.stringify({ state: merged.has(pr) ? "MERGED" : "OPEN", headRefOid: H, headRefName: `b${pr}`, mergeable: "MERGEABLE", mergeStateStatus: "CLEAN", baseRefName: "staging", statusCheckRollup: [{ name: "build", status: c === "pending" ? "IN_PROGRESS" : "COMPLETED", conclusion: c === "pending" ? "" : c === "red" ? "FAILURE" : "SUCCESS", detailsUrl: `https://ci/${pr}` }] });
21
+ }
22
+ if (a[0] === "pr" && a[1] === "merge") merged.add(Number(a[2]));
23
+ return "";
24
+ };
25
+ return { gh, merged, calls };
26
+ }
27
+ const go = (extra) => orchestrate({ parallel: 1, readBody: async () => "", pollMs: 1, trainEveryMs: 0, sleep: async () => {}, ...extra });
28
+
29
+ describe("merge train in the batch runner (#5836)", () => {
30
+ it("frees the slot at pr-ready, merges via the train, and counts it in the report line", async () => {
31
+ const w = world({ 10: ["pending", "green"] }); const train = createMergeTrain({ gh: w.gh, repo: "o/r" });
32
+ const started = [];
33
+ const rows = await go({ issues: [1, 2], train, runOne: async (n) => { started.push([n, w.merged.size]); return n === 1 ? READY(10) : { terminalReason: "merged" }; } });
34
+ assert.deepEqual(started, [[1, 0], [2, 0]], "issue 2 started before the train merged PR 10");
35
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
36
+ assert.ok(w.calls.some((a) => a[1] === "merge" && a.slice(-2).join() === `--match-head-commit,${H}`));
37
+ assert.match(formatTrainSummary(train.stats()), /^merge train: merged 1, handed back 0/);
38
+ });
39
+ it("a dependent waits for the train's merge", async () => {
40
+ const w = world({ 10: ["pending", "pending", "green"] }); const train = createMergeTrain({ gh: w.gh, repo: "o/r" });
41
+ const seen = [];
42
+ const rows = await go({ issues: [1, 2], train, readBody: async (n) => (n === 2 ? "Depends on #1" : ""),
43
+ runOne: async (n) => { seen.push([n, w.merged.has(10)]); return n === 1 ? READY(10) : { terminalReason: "merged" }; } });
44
+ assert.deepEqual(seen, [[1, false], [2, true]]);
45
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
46
+ });
47
+ it("a red PR is handed back as ci.red and a recovery lane runs, then merges", async () => {
48
+ const w = world({ 10: ["red"] }); const train = createMergeTrain({ gh: w.gh, repo: "o/r" });
49
+ const marks = []; let k = 0;
50
+ const rows = await go({ issues: [1], train, recovery: { maxAttempts: 1 }, markRecovering: async (x) => { marks.push(x); },
51
+ runOne: async () => (k++ === 0 ? READY(10) : { terminalReason: "merged" }) });
52
+ assert.deepEqual(marks.map((m) => m.code), ["ci.red"]);
53
+ assert.equal(rows[0].outcome, "merged"); assert.equal(rows[0].recovered, "ci.red");
54
+ assert.equal(train.stats().handedBack["ci.red"], 1);
55
+ assert.equal(w.merged.size, 0, "the train never merged the red PR");
56
+ });
57
+ it("a hand-back with no recovery budget ends needs-human with the failing check URL", async () => {
58
+ const w = world({ 10: ["red"] }); const train = createMergeTrain({ gh: w.gh, repo: "o/r" });
59
+ const rows = await go({ issues: [1], train, recovery: { maxAttempts: 0 }, runOne: async () => READY(10) });
60
+ assert.equal(rows[0].outcome, "needs-human"); assert.equal(rows[0].code, "ci.red");
61
+ assert.match(rows[0].detail, /build https:\/\/ci\/10/);
62
+ });
63
+ it("a stopped batch reports the pr-ready row and --resume continues it through the train", async () => {
64
+ const w = world({ 10: ["pending"] }); let state = null;
65
+ const ac = new AbortController();
66
+ const store = { load: () => null, save: (s) => { state = JSON.parse(JSON.stringify(s)); if (s.train?.entries.length) ac.abort(); }, log: () => {} };
67
+ await go({ issues: [1], train: createMergeTrain({ gh: w.gh, repo: "o/r" }), store, signal: ac.signal, runOne: async () => READY(10) }).catch(() => {});
68
+ assert.equal(state.results[1].outcome, "pr-ready");
69
+ assert.equal(state.train.entries[0].pr, 10);
70
+ const w2 = world({ 10: ["green"] }); const train2 = createMergeTrain({ gh: w2.gh, repo: "o/r" });
71
+ const rows = await go({ issues: [1], train: train2, store: { load: () => state, save: () => {}, log: () => {} }, runOne: async () => { throw new Error("must not relaunch"); } });
72
+ assert.equal(rows[0].outcome, "merged"); assert.ok(w2.merged.has(10));
73
+ });
74
+ it("without a train nothing changes: a merged lane is a merged row", async () => {
75
+ const rows = await go({ issues: [1, 2], runOne: async () => ({ terminalReason: "merged" }) });
76
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
77
+ });
78
+ });
79
+
80
+ describe("batched merge train resume (#5837)", () => {
81
+ it("a saved snapshot with a validating batch is restored by orchestrate; tick re-reads checks and does not rebuild", async () => {
82
+ const calls = []; const ac = new AbortController();
83
+ const gh = async (a) => {
84
+ calls.push(a);
85
+ const s = a.join(" ");
86
+ if (s.includes("/check-runs")) ac.abort();
87
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "OPEN", headRefOid: H, headRefName: "b", mergeable: "MERGEABLE", mergeStateStatus: "BEHIND", baseRefName: "staging", statusCheckRollup: [{ name: "build", conclusion: "SUCCESS" }] });
88
+ if (s.includes("/check-runs")) return JSON.stringify({ check_runs: [{ name: "build", status: "in_progress", conclusion: null }] });
89
+ return "";
90
+ };
91
+ const mk = (n) => ({ issue: n, pr: 10 + n, head: H, required: ["build"], policy: "required", lane: "staging", since: 1 });
92
+ const saved = { entries: [mk(1), mk(2)], stats: { merged: 0, handedBack: {}, waits: [], syncs: 0, batches: 1, candidateRuns: 1 },
93
+ batches: [{ id: "x", base: "staging", baseSha: "c".repeat(40), prs: [1, 2].map((n) => ({ issue: n, pr: 10 + n, head: H })), candidate: "forge-train/staging/x", candSha: "d".repeat(40), state: "validating", startedAt: Date.now() }] };
94
+ const train = createMergeTrain({ gh, repo: "o/r", batchSize: 4 });
95
+ const store = { load: () => ({ order: [1, 2], results: { 1: { issue: 1, outcome: "pr-ready", pr: 11 }, 2: { issue: 2, outcome: "pr-ready", pr: 12 } }, train: saved }), save: () => {}, log: () => {} };
96
+ await go({ issues: [1, 2], train, store, signal: ac.signal, runOne: async () => { throw new Error("must not relaunch"); } }).catch(() => {});
97
+ assert.ok(calls.some((a) => a.join(" ").includes("/check-runs")), "orchestrate restored the train and ticked it");
98
+ assert.ok(calls.some((a) => a.join(" ").includes("/check-runs")));
99
+ assert.ok(!calls.some((a) => a.join(" ").includes("git/refs") && a.includes("POST")), "candidate not rebuilt");
100
+ assert.equal(train.snapshot().batches.length, 1);
101
+ });
102
+ });
103
+
104
+ describe("merge train bisection culprit in the batch runner (#5838)", () => {
105
+ it("a culprit handback reaches settleLane with a merged-tree recovery note; only the culprit is requeued", async () => {
106
+ const w = world({ 10: ["pending", "green"], 11: ["pending", "green"] }); const real = createMergeTrain({ gh: w.gh, repo: "o/r" });
107
+ const culprit = { pr: 10, check: "build", url: "https://ci/batch", batch: "b1" };
108
+ const train = { ...real, tick: async () => {
109
+ if (!real.has(1)) return real.tick();
110
+ const entry = real.snapshot().entries.find((e) => e.issue === 1); real.drop(1);
111
+ return [{ kind: "handback", issue: 1, pr: 10, code: "ci.red", detail: "PR #10 broke the merged tree of train batch b1", entry, culprit }, ...await real.tick()];
112
+ } };
113
+ const runs = [], decisions = [], marks = [];
114
+ const rows = await go({ issues: [1, 2], train, recovery: { maxAttempts: 1 }, decide: (d) => decisions.push(d), markRecovering: async (x) => { marks.push(x); },
115
+ runOne: async (n) => { runs.push(n); return runs.filter((x) => x === n).length === 1 ? READY(n === 1 ? 10 : 11) : { terminalReason: "merged" }; } });
116
+ assert.deepEqual(runs.sort(), [1, 1, 2], "only the culprit gets a fix lane");
117
+ assert.deepEqual(marks.map((m) => [m.issue, m.code]), [[1, "ci.red"]]);
118
+ const why = decisions.find((d) => d.issue === 1 && /recovery lane for ci\.red/.test(d.what))?.why ?? "";
119
+ assert.match(why, /PR #10 broke the merged tree of train batch b1 \(required check build https:\/\/ci\/batch\), not its own head/);
120
+ assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
121
+ });
122
+ it("with no recovery budget the needs-human row carries the culprit and the merged-tree note", async () => {
123
+ const w = world({ 10: ["pending"] }); const real = createMergeTrain({ gh: w.gh, repo: "o/r" });
124
+ const train = { ...real, tick: async () => { const entry = real.snapshot().entries[0]; real.drop(1); return [{ kind: "handback", issue: 1, pr: 10, code: "ci.red", detail: "d", entry, culprit: { pr: 10, check: "build", url: null, batch: "b2" } }]; } };
125
+ const rows = await go({ issues: [1], train, recovery: { maxAttempts: 0 }, runOne: async () => READY(10) });
126
+ assert.equal(rows[0].outcome, "needs-human");
127
+ assert.deepEqual(rows[0].culprit, { pr: 10, check: "build", url: null, batch: "b2" });
128
+ assert.match(rows[0].detail, /^Recovery note: PR #10 broke the merged tree of train batch b2/);
129
+ });
130
+ });