forgedock 1.63.0 → 1.65.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 (89) 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 +8 -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/clear-breaker.mjs +15 -0
  14. package/bin/lean/clear-breaker.test.mjs +100 -0
  15. package/bin/lean/conformance.e2e.test.mjs +32 -6
  16. package/bin/lean/conformance.mjs +57 -13
  17. package/bin/lean/conformance.test.mjs +93 -1
  18. package/bin/lean/execution.mjs +18 -8
  19. package/bin/lean/execution.test.mjs +44 -3
  20. package/bin/lean/issuewatch-reconcile.mjs +2 -0
  21. package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
  22. package/bin/lean/issuewatch.mjs +3 -0
  23. package/bin/lean/lanecheck.test.mjs +13 -1
  24. package/bin/lean/lean.mjs +157 -28
  25. package/bin/lean/lean.test.mjs +289 -21
  26. package/bin/lean/live-execution.mjs +25 -0
  27. package/bin/lean/live-execution.test.mjs +35 -1
  28. package/bin/lean/merged-park.mjs +76 -0
  29. package/bin/lean/merged-park.test.mjs +64 -0
  30. package/bin/lean/mergetrain.mjs +357 -0
  31. package/bin/lean/mergetrain.test.mjs +348 -0
  32. package/bin/lean/mirror-bundle.mjs +84 -0
  33. package/bin/lean/orchestrate-envhold.test.mjs +62 -0
  34. package/bin/lean/orchestrate-stacking.test.mjs +23 -1
  35. package/bin/lean/orchestrate-train.test.mjs +130 -0
  36. package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
  37. package/bin/lean/orchestrate.mjs +170 -13
  38. package/bin/lean/prompts.mjs +4 -3
  39. package/bin/lean/release-review.mjs +8 -1
  40. package/bin/lean/release-review.test.mjs +42 -2
  41. package/bin/lean/release-status.test.mjs +53 -1
  42. package/bin/lean/release.mjs +6 -3
  43. package/bin/lean/render.mjs +6 -1
  44. package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
  45. package/bin/lean/sandbox-remote.mjs +43 -3
  46. package/bin/lean/sched.mjs +19 -2
  47. package/bin/lean/sched.test.mjs +33 -1
  48. package/bin/lean/schedd-health.mjs +2 -1
  49. package/bin/lean/schedd-health.test.mjs +7 -0
  50. package/bin/lean/schedd.mjs +58 -7
  51. package/bin/lean/schedd.test.mjs +78 -1
  52. package/bin/lean/stacking.mjs +45 -0
  53. package/bin/lean/stacking.test.mjs +25 -1
  54. package/bin/lean/statuscomment.mjs +14 -8
  55. package/bin/lean/statuscomment.test.mjs +18 -1
  56. package/bin/lean/validate-catalog.mjs +1 -1
  57. package/bin/lean/validate-catalog.test.mjs +3 -0
  58. package/bin/lean/worktree.mjs +8 -3
  59. package/bin/lean/worktree.test.mjs +18 -0
  60. package/bin/pool/agent.mjs +309 -33
  61. package/bin/pool/cache-sweep.mjs +4 -2
  62. package/bin/pool/cli.mjs +125 -6
  63. package/bin/pool/disk.mjs +43 -0
  64. package/bin/pool/docker.mjs +11 -0
  65. package/bin/pool/health.mjs +95 -0
  66. package/bin/pool/mirror-seed.mjs +103 -0
  67. package/bin/pool/router.mjs +301 -27
  68. package/bin/runner.mjs +3 -1
  69. package/bin/stats/chains.mjs +101 -0
  70. package/bin/stats/chains.test.mjs +53 -0
  71. package/bin/stats/efficiency.mjs +7 -6
  72. package/bin/stats/efficiency.test.mjs +48 -7
  73. package/bin/stats/index.mjs +11 -3
  74. package/bin/stats/stats.test.mjs +9 -0
  75. package/docs/CONFIG.md +8 -1
  76. package/docs/OUTCOME-CODES.md +4 -0
  77. package/package.json +1 -1
  78. package/pool/README.md +10 -0
  79. package/pool/image/Dockerfile +2 -1
  80. package/pool/image/entrypoint.sh +25 -6
  81. package/pool/image/mirror.sh +71 -0
  82. package/pool/install/install-agent-linux.sh +57 -5
  83. package/pool/install/install-agent-macos.sh +148 -0
  84. package/pool/install/install-agent.ps1 +11 -0
  85. package/pool/install/install-agent.sh +59 -7
  86. package/pool/install/uninstall-agent-linux.sh +75 -0
  87. package/pool/install/uninstall-agent-macos.sh +60 -0
  88. package/pool/install/uninstall-agent.ps1 +1 -0
  89. package/scripts/transition-label.sh +11 -0
@@ -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
+ });
@@ -0,0 +1,53 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5947: git transport failures (curl 56, early EOF, invalid index-pack output) are `net.transient` deferrals with backoff,
4
+ // never engine-errors, and never reach the circuit breaker; any other engine-error still counts. --clear-breaker reaches a live runner.
5
+ import { describe, it } from "node:test";
6
+ import assert from "node:assert/strict";
7
+ import { orchestrate, isTransientEngineError, GIT_TRANSPORT_TEXT } from "./orchestrate.mjs";
8
+
9
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
10
+ const EE = (detail) => ({ terminalReason: "engine-error", detail });
11
+ const MERGED = { terminalReason: "merged", pr: 9 };
12
+ const run = async ({ script, issues, breaker = { errors: 2, window_min: 10 }, extra = {} }) => {
13
+ let t = 1_000_000;
14
+ const store = memStore(), updates = [];
15
+ const calls = [];
16
+ const rows = await orchestrate({ issues, parallel: 1, readBody: async () => "", now: () => t, store, pollMs: 1000, breaker,
17
+ sleep: async (ms) => { t += Math.max(1, Number(ms) || 0); },
18
+ runOne: async (n) => { calls.push(n); t += 1000; const l = script[n]; return l[Math.min(calls.filter((c) => c === n).length - 1, l.length - 1)]; },
19
+ onUpdate: (r) => updates.push(r), ...extra });
20
+ return { rows, calls, updates, store };
21
+ };
22
+
23
+ describe("#5947 git transport failures", () => {
24
+ it("classifies git transport text, and not an ordinary failure (negative examples)", () => {
25
+ for (const d of ["error: RPC failed; curl 56 GnuTLS recv error", "fatal: early EOF", "fatal: invalid index-pack output", "fatal: the remote end hung up: unexpected disconnect while reading", "curl 28 Operation timed out", "'/cache/git/x.git' is not a local repository"]) assert.ok(GIT_TRANSPORT_TEXT.test(d) && isTransientEngineError(d), d);
26
+ for (const d of ["TypeError: x is not a function", "validate failed: 56 tests", "curl 5600 bytes"]) assert.equal(GIT_TRANSPORT_TEXT.test(d), false, d);
27
+ });
28
+
29
+ it("engine-errors with curl 56 / invalid index-pack output defer as net.transient; the breaker stays closed", async () => {
30
+ const r = await run({ issues: [1, 2], script: { 1: [EE("fatal: early EOF\nerror: RPC failed; curl 56 recv"), MERGED], 2: [EE("fatal: invalid index-pack output"), MERGED] } });
31
+ const d = r.updates.filter((u) => u.outcome === "deferred");
32
+ assert.equal(d.length, 2);
33
+ assert.ok(d.every((u) => u.code === "net.transient"));
34
+ assert.deepEqual(r.rows.map((x) => x.outcome).sort(), ["merged", "merged"]);
35
+ const st = r.store.peek();
36
+ assert.deepEqual(st.errorTimes, []);
37
+ assert.equal(st.breaker ?? null, null);
38
+ assert.equal(r.updates.some((u) => u.outcome === "breaker" || u.outcome === "engine-error"), false);
39
+ });
40
+
41
+ it("a non-transport engine-error still counts toward the breaker", async () => {
42
+ const r = await run({ issues: [1, 2, 3], breaker: { errors: 2, window_min: 10 }, script: { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] } });
43
+ assert.ok(r.updates.some((u) => u.outcome === "breaker"), "two real engine-errors trip it");
44
+ });
45
+
46
+ it("getClearBreaker resets a tripped breaker in the running batch and acks", async () => {
47
+ let tripSeen = false; const acks = [];
48
+ const r = await run({ issues: [1, 2, 3], breaker: { errors: 2, window_min: 10 }, script: { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] },
49
+ extra: { onUpdate: (u) => { if (u.outcome === "breaker") tripSeen = true; }, getClearBreaker: () => tripSeen, ackClearBreaker: (i) => acks.push(i) } });
50
+ assert.ok(acks.length >= 1 && acks[0].cleared === true, "the live runner acked a real clear");
51
+ assert.equal(r.store.peek().breaker ?? null, null);
52
+ });
53
+ });
@@ -124,6 +124,7 @@
124
124
  * then queue order. A sub-issue's estimate is the parent's ÷ N, floored at the M default. Without `estimate` the order is
125
125
  * the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
126
126
  */
127
+ import { decideClear } from "./clear-breaker.mjs";
127
128
  import { parseDependsOn } from "../engine/phases.mjs";
128
129
  import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
129
130
  import { detectGateDeadlock, formatGateDeadlock } from "./gatewatch.mjs";
@@ -143,6 +144,9 @@ import { openPrerequisites } from "./prereq.mjs";
143
144
 
144
145
  // A dependency that finished like this no longer blocks its dependents.
145
146
  const SATISFIED = new Set(["merged", "invalid"]);
147
+ const DEFAULT_TRAIN_EVERY_MS = 30000; // #5836: merge-train poll period
148
+ // #5836: a lane that ended pr-ready is waiting on the merge train, not failed: its dependents wait
149
+ const WAITING_ON_TRAIN = (row) => row?.outcome === "pr-ready";
146
150
  // #5162: a dependent of a root that ended like this is held (resumable), not skipped. #5805: also behind a root held on an engine/env change.
147
151
  const HOLD_ROOT = new Set(["needs-human", "engine-error", "deferred", "budget-exceeded", "held"]);
148
152
  /** #5162: members of a real dependency cycle (a nontrivial SCC or a self-loop) among `nodes`; `edgesOf(n)` lists n's dependencies. */
@@ -171,11 +175,15 @@ export const MAX_REQUEUES = 2;
171
175
  export const DEFAULT_MAX_DEFERRALS = 3;
172
176
  // Relaunches of an issue whose lane ended engine-error.
173
177
  export const ENGINE_ERROR_RELAUNCHES = 1;
178
+ // #5859: lanes of one pool agent lost without a result within the window that make it an agent restart (`sandbox.lost`), and their requeue delay
179
+ export const AGENT_LOST_MIN = 3;
180
+ export const AGENT_LOST_WINDOW_MS = 60000;
181
+ export const AGENT_LOST_REQUEUE_MS = 60000;
174
182
  export const HOST_BUSY_RETRY_S = 60;
175
183
  // #4528: a busy host or a full sandbox pool is a wait, not a failure: requeued after its retry-in, never capped.
176
184
  // A lane that could not be resolved because gh/git failed (network blip) is the same kind of wait (#4791).
177
185
  // #4788: an unreachable pool is a wait too (the lane already retried for unreachable_window_min); a stall is reported by poolStall.
178
- const UNCAPPED_DEFERRALS = new Set(["host.busy", "sandbox.capacity", "sandbox.unreachable", "lane.unresolved"]);
186
+ const UNCAPPED_DEFERRALS = new Set(["host.busy", "sandbox.capacity", "sandbox.unreachable", "sandbox.repo_missing", "lane.unresolved"]);
179
187
  export const POOL_OFFLINE_ALERT_MIN = 10;
180
188
  // #5112: `sandbox.capacity` deferrals of one issue after which `execution.fallback_local` runs it on the host (headroom permitting).
181
189
  export const CAPACITY_FALLBACK_AFTER = 3;
@@ -183,7 +191,9 @@ export const RATE_LIMIT_FALLBACK_S = 15 * 60;
183
191
  export const DEFER_BACKOFF_S = 120;
184
192
  export const DEFER_BACKOFF_MAX_S = 30 * 60;
185
193
  // #4685 + #5161: an engine-error detail that names a link or gateway failure (curl's "returned error: 502", HTTP/1.1 503, ...).
186
- export const TRANSPORT_TEXT = /fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|HTTP 50[234]|returned error: 5\d\d|HTTP\/\d(\.\d)? 5\d\d|Bad Gateway|Service Unavailable|overloaded/i;
194
+ // #5947: git transport failures (a dropped clone/fetch, a half-built mirror): a `net.transient` deferral, never an engine-error.
195
+ export const GIT_TRANSPORT_TEXT = /curl (56|28)\b|early EOF|RPC failed|invalid index-pack output|unexpected disconnect|is not a local repository/i;
196
+ export const TRANSPORT_TEXT = new RegExp(`fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|socket hang up|HTTP 50[234]|returned error: 5\\d\\d|HTTP\\/\\d(\\.\\d)? 5\\d\\d|Bad Gateway|Service Unavailable|overloaded|${GIT_TRANSPORT_TEXT.source}`, "i");
187
197
  /** #5161: a transient engine failure (model gateway 5xx, connection reset): retried with backoff, not the single relaunch. */
188
198
  export const isTransientEngineError = (detail) => TRANSPORT_TEXT.test(String(detail ?? ""));
189
199
  // #5161: transient engine-error retries per issue (forge.yaml `orchestration.transient_retries`) and their backoff: 30s, 2m, 8m, then 15m.
@@ -326,12 +336,14 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
326
336
  * @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
327
337
  */
328
338
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
329
- store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000,
339
+ store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, consumeClearBreaker = null, ackClearBreaker = null,
330
340
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
331
341
  recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
332
342
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
333
- getChildren = null, autoChildren = null, baseWait = null, rotator = null, stacking = "off", readPrReady = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null }) {
343
+ getChildren = null, autoChildren = null, baseWait = null, rotator = null, stacking = "off", readPrReady = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null,
344
+ train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS }) {
334
345
  const saved = store?.load?.() ?? null;
346
+ if (train && saved?.train) train.restore(saved.train); // #5836: the merge train resumes with the batch
335
347
  const order = saved ? [...saved.order] : [];
336
348
  const set = new Set(order);
337
349
  const deps = toMap(saved?.deps); // issue -> declared dependencies (any issue); only those in `set` are edges
@@ -344,6 +356,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
344
356
  const notBefore = toMap(saved?.notBefore);
345
357
  const requeues = toMap(saved?.requeues);
346
358
  const deferrals = toMap(saved?.deferrals);
359
+ const capReasons = toMap(saved?.capReasons); // #5938: issue -> the pool's last `sandbox.capacity` / host-disk reason (read by the batch health stall verdict)
347
360
  const capDefers = toMap(saved?.capDeferrals); // #5112: issue -> `sandbox.capacity` deferrals (uncapped, so not in `deferrals`)
348
361
  const capFellBack = new Set(); // #5112: issues already reported as a capacity fallback (one decision each)
349
362
  const engineErrors = toMap(saved?.engineErrors);
@@ -369,6 +382,9 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
369
382
  const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
370
383
  const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
371
384
  let errorTimes = [...(saved?.errorTimes ?? [])];
385
+ // #5859: agent restarts of this batch (one record each, shown by `status --batch`) and the lanes already requeued as `sandbox.lost`
386
+ const agentRestarts = [...(saved?.agentRestarts ?? [])];
387
+ const lostOnce = new Set(saved?.lostRequeued ?? []); // a lane lost again after its requeue is an ordinary engine-error
372
388
  // A legacy batch-local `holdUntil` (pre-#4190) names no account and is ignored: a same-account lane re-sets the hold.
373
389
  const holds = limits ?? memoryLimits(now);
374
390
  // #5205: accounts lanes reported limited (account -> until ms), persisted with the batch, excluded from headroom until then.
@@ -468,6 +484,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
468
484
  const stackedTried = new Set(saved?.stackedTried ?? []);
469
485
  const planned = toMap(saved?.planned);
470
486
  const planTried = new Set(saved?.planTried ?? []);
487
+ const firstAdmit = new Map(), planMs = new Map(); // #5834: issue -> first admission ms; issue -> plan lane run ms (chain metrics)
471
488
  const recovering = toMap(saved?.recovering); // issue -> {code, attempt, detail, outcome, ...} of the recovery lane queued or running
472
489
  const freeRecovered = new Set(); // #5727: issues whose one free (no-attempt) recovery for a recipe-less remote tool miss was spent
473
490
  const requeueApplied = new Set(saved?.requeueApplied ?? []); // #4550: `--requeue` entries already applied (batch `requeue` file)
@@ -483,14 +500,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
483
500
  const save = () => {
484
501
  if (!store || halted) return;
485
502
  store.save({ v: 1, ...(setup ? { phase: "setup", setup: { ...setup } } : {}), engineVersion: version, order, deps: toObj(deps), lanes: toObj(lanes), crossSeen: [...crossSeen], results: toObj(results), running: toObj(runRecs),
486
- pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}),
487
- prefilter: toObj(checked), errorTimes, breaker: tripped, ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
503
+ pending, notBefore: toObj(notBefore), requeues: toObj(requeues), deferrals: toObj(deferrals), engineErrors: toObj(engineErrors), ...(transients.size ? { transientRetries: toObj(transients) } : {}), ...(quota.size ? { quota: toObj(quota) } : {}), ...(limitedAccounts.size ? { limitedAccounts: toObj(limitedAccounts) } : {}), ...(capDefers.size ? { capDeferrals: toObj(capDefers) } : {}), ...(capReasons.size ? { capReasons: toObj(capReasons) } : {}),
504
+ prefilter: toObj(checked), errorTimes, breaker: tripped, ...(agentRestarts.length ? { agentRestarts, lostRequeued: [...lostOnce] } : {}), ...(budget ? { classes: toObj(classes), dispatch: { ...dispatch } } : {}),
488
505
  ...(reg ? { priorities: toObj(priorities) } : {}), ...(sandboxUse.size ? { sandbox: toObj(sandboxUse) } : {}),
489
506
  ...(recoveries.size || recovering.size ? { recoveries: toObj(recoveries), recovering: toObj(recovering), recoveryClasses: toObj(classUsed) } : {}),
490
507
  ...(planned.size || planTried.size ? { planned: toObj(planned), planTried: [...planTried] } : {}),
491
508
  ...(stackedTried.size ? { stacked: toObj(stackedOf), stackedTried: [...stackedTried] } : {}),
492
509
  ...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
493
- ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}),
510
+ ...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
494
511
  ...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
495
512
  ...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}) });
496
513
  };
@@ -830,6 +847,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
830
847
  };
831
848
  const requeue = (n, delayMs) => { pending.push(n); enqueued.set(n, now()); if (delayMs > 0) notBefore.set(n, now() + delayMs); else notBefore.delete(n); };
832
849
  const TRANSPORT_COOLDOWN_MS = 5 * 60000;
850
+ const netTransients = new Map(); // #5947: issue -> net.transient deferrals (backoff step)
833
851
  let transportErrors = 0; // #4685: engine-errors in the current window that were link failures
834
852
  const noteEngineError = (detail = "") => {
835
853
  if (!breaker) return;
@@ -840,20 +858,68 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
840
858
  tripped = { at: t, ...(transportErrors >= errorTimes.length ? { transport: true } : {}), detail: `circuit breaker: ${errorTimes.length} engine-errors within ${breaker.window_min} min; admissions stopped` };
841
859
  update({ issue: null, outcome: "breaker", detail: tripped.detail });
842
860
  }
861
+ return t;
862
+ };
863
+ // #5859: sandboxes of one pool agent ending without a result in a burst (AGENT_LOST_MIN within AGENT_LOST_WINDOW_MS) are an agent/VM
864
+ // restart: `sandbox.lost`, requeued once (after `remote.agentHealthy(agent)` answers, when the provider has it), never counted by the
865
+ // breaker or the engine-error relaunch. Lanes of the burst that settled as engine-errors first are rolled back. One batch event each.
866
+ const lostSeen = new Map(); // agent -> [{n, at, err, ee, tr, sig}]: lost lanes settled as ordinary engine-errors in the window
867
+ const openRestart = (agent, t) => agentRestarts.find((g) => g.agent === agent && !g.closed && t - g.last < AGENT_LOST_WINDOW_MS);
868
+ const markLost = (agent, n, row, why) => {
869
+ lostOnce.add(n);
870
+ let g = openRestart(agent, now());
871
+ if (!g) agentRestarts.push(g = { agent, at: new Date(now()).toISOString(), last: now(), lanes: [] });
872
+ if (!g.lanes.includes(n)) g.lanes.push(n);
873
+ g.last = now(); g.requeued = g.lanes.length;
874
+ update({ ...row, outcome: "deferred", code: OUTCOME_CODES.SANDBOX_LOST, detail: `requeued: ${OUTCOME_CODES.SANDBOX_LOST} (agent ${agent} restarted): ${why ?? ""}` });
875
+ };
876
+ const rollBackLost = (agent, x) => {
877
+ if (x.err !== undefined) { const i = errorTimes.lastIndexOf(x.err); if (i >= 0) errorTimes.splice(i, 1); transportErrors = Math.min(transportErrors, errorTimes.length); }
878
+ if (!pending.includes(x.n) && !running.has(x.n)) return; // it already ended (its relaunch was used before): only the breaker count goes
879
+ for (const [m, v] of [[engineErrors, x.ee], [transients, x.tr], [engineSigs, x.sig]]) { if (v === undefined) m.delete(x.n); else m.set(x.n, v); }
880
+ if (pending.includes(x.n)) notBefore.set(x.n, now() + AGENT_LOST_REQUEUE_MS);
881
+ markLost(agent, x.n, { issue: x.n }, "settled as an engine-error before the restart was visible; rolled back");
882
+ };
883
+ const closeRestart = (g) => {
884
+ g.closed = true; g.requeued = g.lanes.length; g.detail = `agent ${g.agent} restarted at ${g.at}; ${g.lanes.length} lanes requeued`;
885
+ const ev = { event: "agent.restarted", batch: batchId ?? null, agent: g.agent, at: g.at, requeued: g.lanes.length, issues: [...g.lanes], detail: g.detail };
886
+ try { store?.log?.(ev); } catch { /* best effort */ }
887
+ onUpdate(ev);
888
+ };
889
+ const agentLostPass = async (t) => {
890
+ let changed = false;
891
+ for (const g of agentRestarts) {
892
+ if (g.closed) continue;
893
+ if (!g.healthyAt) {
894
+ let ok = true;
895
+ if (typeof remote?.agentHealthy === "function") { try { ok = (await remote.agentHealthy(g.agent)) === true; } catch { ok = false; } }
896
+ if (ok) { g.healthyAt = new Date(t).toISOString(); changed = true; } else for (const m of g.lanes) if (pending.includes(m)) notBefore.set(m, Math.max(notBefore.get(m) ?? 0, t + pollMs));
897
+ }
898
+ if (g.healthyAt && t - g.last >= AGENT_LOST_WINDOW_MS) { closeRestart(g); changed = true; }
899
+ }
900
+ if (changed) save();
843
901
  };
844
902
 
845
903
  // Apply one lane's result: requeue it (deferred, dependency-open, engine-error) or record its final row.
846
904
  const settleLane = async (n, r, rec, pf) => {
847
905
  if (halted) return; // #4454: a resume adopts the lane and settles it
906
+ // #5947: a git transport failure ends the lane as a `net.transient` deferral with backoff; the breaker never sees it.
907
+ if (!cancelled && (r?.terminalReason ?? "engine-error") === "engine-error" && GIT_TRANSPORT_TEXT.test(String(r?.detail ?? ""))) {
908
+ const k = (netTransients.get(n) ?? 0) + 1;
909
+ netTransients.set(n, k);
910
+ r = { ...r, terminalReason: "deferred", code: OUTCOME_CODES.NET_TRANSIENT, retryInSeconds: Math.round(transientRetryDelayMs(k) / 1000), detail: r.detail };
911
+ }
848
912
  // #5241: the lane ended: its lease goes with it. #5654: also an interrupted or engine-error end, which is requeued at once
849
913
  if (releaseLease && (cancelled || (r?.terminalReason ?? "engine-error") === "engine-error" || (r?.terminalReason === "deferred" && r?.code === "run.interrupted"))) { try { await releaseLease(n, rec); } catch { /* best effort: the lease expires */ } }
850
914
  // #4304: the pre-filter runs once per issue; a recovery pass's row adds the earlier attempt's cost, which already holds it.
851
915
  const pfCost = recovering.has(n) ? 0 : (pf?.cost_usd ?? 0);
852
- const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(pf ? { prefilter: pf } : {}), ...(rec?.stackedOn ? { stacked: true, stackedOn: rec.stackedOn } : {}),
916
+ const row = { issue: n, outcome: r?.terminalReason ?? "engine-error", pr: r?.pr ?? null, cost_usd: (r?.cost_usd ?? 0) + pfCost, minutes: Math.round((now() - rec.startedAt) / 6000) / 10, detail: r?.detail, ...(r?.code ? { code: r.code } : {}), ...(r?.culprit ? { culprit: r.culprit } : {}), ...(pf ? { prefilter: pf } : {}), ...(rec?.stackedOn ? { stacked: true, stackedOn: rec.stackedOn } : {}),
853
917
  ...(() => { const w = capWait.take(n, r?.waits); return w && typeof w === "object" ? { waits: w } : {}; })(), ...(Number.isInteger(r?.heavyQueueMax) ? { heavyQueueMax: r.heavyQueueMax } : {}),
854
918
  ...(Number.isFinite(r?.wall_ms) ? { wall_ms: r.wall_ms } : {}), ...(Number.isFinite(r?.model_ms) ? { model_ms: r.model_ms } : {}), // #4451
855
919
  ...(phasesOf(r, rec) ? { phases: phasesOf(r, rec) } : {}), // #4908
856
920
  ...(Array.isArray(r?.followups) && r.followups.length ? { followups: r.followups } : {}), // #5078
921
+ ...(r?.cascade ? { cascade: r.cascade, cascades: Array.isArray(r.cascades) ? r.cascades : [r.cascade], ...(Number.isFinite(r.cascade_cost_usd) ? { cascade_cost_usd: r.cascade_cost_usd } : {}), ...(Number.isFinite(r.cascade_minutes) ? { cascade_minutes: r.cascade_minutes } : {}) } : {}), // #5833
922
+ ...(edges(n).length ? { deps: edges(n) } : {}), ...(firstAdmit.has(n) ? { admitted_at: firstAdmit.get(n), ended_at: now() } : {}), ...(planMs.has(n) ? { plan_minutes: Math.round(planMs.get(n) / 6000) / 10 } : {}), // #5834
857
923
  ...(Number.isFinite(r?.precheckMs) ? { precheck_ms: r.precheckMs } : {}), ...(Number.isInteger(r?.precheckDeferred) && r.precheckDeferred > 0 ? { precheck_deferred: r.precheckDeferred } : {}), // #4331
858
924
  ...(typeof r?.firstPass === "boolean" ? { first_pass: r.firstPass } : {}), // #4362
859
925
  ...(r?.turns && typeof r.turns === "object" ? { turns: r.turns } : {}), // #4392
@@ -880,10 +946,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
880
946
  }
881
947
  if (sandboxUse.has(n)) row.sandbox = { ...sandboxUse.get(n), ...(sandboxUse.get(n).by_agent ? { by_agent: { ...sandboxUse.get(n).by_agent } } : {}) };
882
948
  const done = () => { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); };
949
+ if (train && row.outcome === "pr-ready" && Number.isInteger(r?.pr) && r?.head) { // #5836: the slot frees now; the train merges the PR
950
+ const p = recovering.get(n);
951
+ if (p) { recovering.delete(n); row.cost_usd = Math.round(((Number(row.cost_usd) || 0) + (Number(p.cost_usd) || 0)) * 1e6) / 1e6; row.minutes = Math.round(((Number(row.minutes) || 0) + (Number(p.minutes) || 0)) * 10) / 10; }
952
+ train.add({ issue: n, pr: r.pr, head: r.head, required: Array.isArray(r.required) ? r.required : [], policy: r.policy, lane: r.lane ?? rec?.lane ?? null, milestone: r.milestone, postMerge: r.postMerge, laneSide: r.laneSide });
953
+ results.set(n, row); done(); save(); update(row);
954
+ return;
955
+ }
883
956
  if (rec?.plan) {
884
957
  // #5831: a plan lane ends `planned` or `plan-failed` and goes back to pending for its build lane. It is never a final row and
885
958
  // never counts toward the breaker, the engine-error relaunch, the deferral or the requeue budgets (it returns before them).
886
959
  done();
960
+ planMs.set(n, (planMs.get(n) ?? 0) + Math.max(0, now() - rec.startedAt)); // #5834
887
961
  const ok = r?.terminalReason === "planned" && r?.planned?.contractHash && r?.planned?.baseSha;
888
962
  if (ok) planned.set(n, { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha });
889
963
  store?.log?.({ event: ok ? "STACK_PLANNED" : "STACK_PLAN_FAILED", issue: n, ...(ok ? { contractHash: r.planned.contractHash, baseSha: r.planned.baseSha } : { reason: row.outcome }) });
@@ -952,12 +1026,25 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
952
1026
  update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
953
1027
  return;
954
1028
  }
1029
+ if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
1030
+ // #5833: the stacked dependent's PR and branch were dropped. replan: it builds as a normal lane on the lane base (today's held/skipped
1031
+ // rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
1032
+ const so = stackedOf.get(n);
1033
+ stackedOf.delete(n); planned.delete(n);
1034
+ if (r.code === "stack.restart") { stackedTried.delete(n); if (so) prReady.delete(so.dependency); }
1035
+ requeue(n, 0); done(); save();
1036
+ store?.log?.({ event: "STACK_CASCADE", issue: n, cascade: r.cascade, ...(so ? { dependency: so.dependency } : {}) });
1037
+ decided({ issue: n, what: `stacked cascade ${r.cascade} for #${n}`, why: firstLine(row.detail) || "the stacked dependency moved or ended", alternative: "keep the stacked PR" });
1038
+ update({ ...row, detail: `requeued after cascade ${r.cascade}: ${firstLine(row.detail)}` });
1039
+ return;
1040
+ }
955
1041
  if (row.outcome === "deferred") {
956
1042
  const pol = deferPolicy(r, { now: now(), deferrals: deferrals.get(n) ?? 0, maxDeferrals });
957
1043
  let capGated = false; // #4909: the pool reports free slots, so the slot (not the retry-in timer) gates the relaunch
958
1044
  if (r?.code === "sandbox.unreachable") notePool(true, r.detail ?? "sandbox unreachable");
959
1045
  if (r?.code === "sandbox.capacity") {
960
1046
  capWait.refused(n);
1047
+ if (r.detail) capReasons.set(n, String(r.detail).slice(0, 300));
961
1048
  capDefers.set(n, (capDefers.get(n) ?? 0) + 1); // #5112: counted for the fallback_local capacity fallback
962
1049
  try { capGated = Number.isInteger(remote?.capacity?.()?.free); } catch { capGated = false; }
963
1050
  }
@@ -1003,8 +1090,27 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1003
1090
  }
1004
1091
  row.detail = `gave up after ${deferrals.get(n) ?? 0} deferrals: ${r?.detail ?? r?.code ?? ""}`;
1005
1092
  }
1093
+ const la = row.outcome === "engine-error" && r?.lostWithoutResult && !cancelled && !lostOnce.has(n) ? (r.agent ?? r.sandbox?.agent ?? null) : null;
1094
+ let lostNow = null;
1095
+ if (la) { // #5859
1096
+ const t = now(), win = (lostSeen.get(la) ?? []).filter((x) => t - x.at < AGENT_LOST_WINDOW_MS);
1097
+ if (openRestart(la, t) || win.length + 1 >= AGENT_LOST_MIN) {
1098
+ lostSeen.delete(la);
1099
+ for (const x of win) rollBackLost(la, x);
1100
+ if (tripped && !tripped.transport && breaker && errorTimes.length < breaker.errors && win.length && tripped.at >= win[0].at) {
1101
+ tripped = null;
1102
+ update({ issue: null, outcome: "breaker", detail: `circuit breaker cleared: the engine-errors were agent ${la} restarting (${OUTCOME_CODES.SANDBOX_LOST})` });
1103
+ }
1104
+ markLost(la, n, row, row.detail);
1105
+ requeue(n, AGENT_LOST_REQUEUE_MS); done(); save();
1106
+ return;
1107
+ }
1108
+ lostNow = { n, at: t, ee: engineErrors.get(n), tr: transients.get(n), sig: engineSigs.get(n) };
1109
+ lostSeen.set(la, [...win, lostNow]);
1110
+ }
1006
1111
  if (row.outcome === "engine-error") {
1007
- noteEngineError(r?.detail);
1112
+ const errAt = noteEngineError(r?.detail);
1113
+ if (lostNow) lostNow.err = errAt;
1008
1114
  // #5161: a transient failure (gateway 5xx, reset) waits out the outage with backoff instead of the single immediate relaunch.
1009
1115
  if (transientMax > 0 && isTransientEngineError(row.detail)) {
1010
1116
  const k = (transients.get(n) ?? 0) + 1;
@@ -1192,7 +1298,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1192
1298
  const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
1193
1299
  heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
1194
1300
  const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
1195
- runRecs.set(n, rec); notBefore.delete(n); save();
1301
+ if (!firstAdmit.has(n)) firstAdmit.set(n, rec.startedAt); // #5834: chain wall time starts at the first admission, plan lane included
1302
+ runRecs.set(n, rec); notBefore.delete(n); capReasons.delete(n); save();
1196
1303
  track(n, (async () => {
1197
1304
  // Pre-filter once per issue (a requeued issue is not re-checked); fail-open: an error means a normal lane.
1198
1305
  if (prefilter && !checked.has(n)) { let pf = null; try { pf = await prefilter(n, lane); } catch { pf = null; } checked.set(n, pf); save(); }
@@ -1387,6 +1494,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1387
1494
  continue;
1388
1495
  }
1389
1496
  if (!row || !REQUEUABLE(row.outcome) || running.has(e.issue)) continue;
1497
+ train?.drop(e.issue); // #5836: a requeued pr-ready row leaves the train
1390
1498
  const moved = [e.issue], priors = new Map([[e.issue, row]]);
1391
1499
  results.delete(e.issue);
1392
1500
  for (let i = 0; i < moved.length; i++) { // dependents skipped behind a requeued issue (fixpoint)
@@ -1681,6 +1789,38 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1681
1789
  if (back.size) save();
1682
1790
  };
1683
1791
  const K = () => { let k = null; try { k = getParallel?.(); } catch { k = null; } return Number.isInteger(k) && k >= 1 ? k : parallel; };
1792
+ // #5836: one train poll (throttled): a merged PR becomes a merged row; a red, conflicting or moved-head PR is handed back as a
1793
+ // needs-human row through the normal settle path, so in-batch recovery requeues a fix lane.
1794
+ let lastTrainTick = -Infinity;
1795
+ const runTrain = async () => {
1796
+ if (!train?.size() || signal?.aborted || now() - lastTrainTick < trainEveryMs) return;
1797
+ lastTrainTick = now();
1798
+ let evs = [];
1799
+ try { evs = await train.tick(); } catch { evs = []; }
1800
+ for (const e of evs) {
1801
+ const n = e.issue, prev = results.get(n) ?? { issue: n };
1802
+ if (e.kind === "merged") {
1803
+ const { waiting, ...rest } = prev;
1804
+ const row = { ...rest, outcome: "merged", detail: e.detail };
1805
+ results.set(n, row);
1806
+ if (lifecycle && e.entry.milestone) lifecycleTitles.add(String(e.entry.milestone));
1807
+ if (integration?.onMerged && String(e.entry.lane ?? "").startsWith("milestone/")) {
1808
+ try { await integration.onMerged(n, { ...row, lane: e.entry.lane }, { milestone: e.entry.milestone }); } catch (err) { update({ issue: n, outcome: "integration", detail: `integration check failed: ${String(err?.message ?? err).slice(0, 300)}` }); }
1809
+ }
1810
+ save(); update(row);
1811
+ } else {
1812
+ results.delete(n);
1813
+ // #5838: a bisection culprit broke the merged tree of its batch, not its own head; the recovery note leads with that.
1814
+ const c = e.culprit, detail = c ? `Recovery note: PR #${c.pr} broke the merged tree of train batch ${c.batch} (required check ${c.check}${c.url ? ` ${c.url}` : ""}), not its own head; fix it against ${e.entry.lane ?? "the base"} with the PRs merged before it.\n${e.detail}` : e.detail;
1815
+ await settleLane(n, { terminalReason: "needs-human", code: e.code, detail, pr: e.pr, cost_usd: prev.cost_usd ?? 0, lane: e.entry.lane, ...(c ? { culprit: c } : {}) }, { startedAt: now() - Math.round((Number(prev.minutes) || 0) * 60000), lane: e.entry.lane }, null);
1816
+ if (results.get(n)?.outcome === "needs-human" && !everRelabelled.has(n) && typeof relabelNeedsHuman === "function") {
1817
+ everRelabelled.add(n);
1818
+ try { await relabelNeedsHuman({ issue: n, evidence: detail }); } catch { /* best effort */ }
1819
+ }
1820
+ }
1821
+ }
1822
+ save();
1823
+ };
1684
1824
  let firstPass = true; // #5805: a resume (e.g. after an upgrade) re-checks the engine/env holds at once
1685
1825
  try {
1686
1826
  for (;;) {
@@ -1688,10 +1828,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1688
1828
  await drainAdds();
1689
1829
  await drainRequeues();
1690
1830
  checkCancel();
1831
+ await runTrain();
1691
1832
  await watchBlockers(!pending.length && !running.size);
1692
1833
  await watchEnvHolds(firstPass || (!pending.length && !running.size)); // #5805
1693
1834
  firstPass = false;
1694
- if (!pending.length && !running.size) {
1835
+ if (!pending.length && !running.size && !train?.size()) {
1695
1836
  if (envWaiting() && !signal?.aborted) { await nap(ehWatchMs); continue; } // #5805: only engine/env holds remain: keep re-checking them
1696
1837
  break;
1697
1838
  }
@@ -1701,7 +1842,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1701
1842
  for (let i = pending.length - 1; i >= 0; i--) {
1702
1843
  const n = pending[i];
1703
1844
  if (results.has(n)) { pending.splice(i, 1); continue; }
1704
- const bad = edges(n).find((d) => results.has(d) && !SATISFIED.has(results.get(d).outcome));
1845
+ const bad = edges(n).find((d) => results.has(d) && !SATISFIED.has(results.get(d).outcome) && !WAITING_ON_TRAIN(results.get(d)));
1705
1846
  if (bad !== undefined) {
1706
1847
  pending.splice(i, 1); again = true;
1707
1848
  const br = results.get(bad), root = br.root ?? bad, ro = results.get(root)?.outcome ?? br.outcome;
@@ -1710,6 +1851,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1710
1851
  }
1711
1852
  }
1712
1853
  }
1854
+ if (agentRestarts.length) await agentLostPass(now()); // #5859
1713
1855
  const t = now();
1714
1856
  const holdUntil = heldUntil();
1715
1857
  let started = 0;
@@ -1841,6 +1983,18 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1841
1983
  if (reg) withdrawExcept(wanted);
1842
1984
  // #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
1843
1985
  if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
1986
+ // #5947: --clear-breaker on a schedd-hosted batch reaches this runner through the batch's request file
1987
+ if (getClearBreaker) { // #5964: time-scoped; the request is consumed only after the decision, so a long pass never loses it
1988
+ let req = null; try { req = getClearBreaker(); } catch { req = null; }
1989
+ if (req) {
1990
+ const d = decideClear({ tripped, requestAt: req });
1991
+ const wasTripped = Boolean(tripped);
1992
+ if (d.clear) { const was = wasTripped; tripped = null; errorTimes = []; transportErrors = 0; save(); try { ackClearBreaker?.({ cleared: was }); } catch { /* advisory */ } }
1993
+ else if (d.stale) { try { ackClearBreaker?.({ cleared: false }); } catch { /* advisory */ } }
1994
+ try { consumeClearBreaker?.(); } catch { /* advisory */ }
1995
+ if (d.clear && wasTripped) continue; // admission ran before this check: re-run the pass so the cleared batch resumes instead of falling to the "nothing runnable" skip
1996
+ }
1997
+ }
1844
1998
  if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
1845
1999
  if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
1846
2000
  if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
@@ -1875,12 +2029,14 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1875
2029
  if (syncParked && running.size && parkedPrs().length) wake = Math.min(wake ?? syncEveryMs, Math.max(0, syncEveryMs - (t - (lastParkedSync ?? t)))); // #4525
1876
2030
  if (running.size && watchable()) wake = Math.min(wake ?? WATCH_EVERY_MS, WATCH_EVERY_MS); // #4595: re-check the blockers of skipped rows
1877
2031
  if (running.size && envWaiting()) wake = Math.min(wake ?? ehWatchMs, ehWatchMs); // #5805: re-check engine/env holds while lanes run
1878
- if (tripped) wake = null;
2032
+ if (train?.size()) wake = Math.min(wake ?? trainEveryMs, Math.max(0, trainEveryMs - (now() - lastTrainTick))); // #5836
2033
+ if (tripped) wake = getClearBreaker ? Math.min(wake ?? pollMs, pollMs) : null;
1879
2034
  if (getCancelled && running.size && (!cancelled || [...running.keys()].some((n) => { const x = stopSent.get(n); return x && !(x.accepted && x.reported); }))) wake = Math.min(wake ?? pollMs, pollMs); // #5241: a cancel keeps polling a lane whose stop is unconfirmed // #4376: notice a cancel while lanes run
1880
2035
  if (running.size) {
1881
2036
  if (wake === null) await race(running.values());
1882
2037
  else { const ac = new AbortController(); await race([...running.values(), sleep(wake, ac.signal)]); ac.abort(); }
1883
2038
  } else if (started) continue; // only lane-refused rows settled (synchronously): re-resolve skips first
2039
+ else if (train?.size()) await nap(wake ?? trainEveryMs); // #5836: only train-held PRs are left: poll the train
1884
2040
  else if (pending.length && offered.size) await nap(wake); // waiting for a host slot
1885
2041
  else if (pending.length && (pfAll || pfRemote)) await nap(Math.min(wake ?? pollMs, pollMs)); // #4866: a failing lane preflight is re-checked on the next poll
1886
2042
  else if (pending.length && blockedHit.size) await nap(wake ?? pollMs); // #4773: only blocked issues wait: poll for the label's removal
@@ -1914,6 +2070,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1914
2070
  throw e;
1915
2071
  }
1916
2072
  await Promise.allSettled([...postRuns]); // #5437
2073
+ if (agentRestarts.some((g) => !g.closed) && !halted) { for (const g of agentRestarts) if (!g.closed) closeRestart(g); save(); } // #5859
1917
2074
  if (reg) withdrawExcept(new Set());
1918
2075
  await relabelQueued();
1919
2076
  // #4657: a milestone whose `close_on` state is reached closes here; a failure is a row, never an outcome change.