forgedock 1.62.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.
- package/bin/config-schema.mjs +5 -0
- package/bin/engine/outcome-codes.mjs +5 -0
- package/bin/engine-cli.mjs +109 -21
- package/bin/env/cli.mjs +18 -1
- package/bin/lean/basered.mjs +56 -11
- package/bin/lean/basered.test.mjs +58 -5
- package/bin/lean/batch-health.mjs +46 -4
- package/bin/lean/batch-health.test.mjs +55 -1
- package/bin/lean/batch.mjs +9 -1
- package/bin/lean/batch.test.mjs +74 -7
- package/bin/lean/ceiling.mjs +47 -3
- package/bin/lean/ceiling.test.mjs +32 -1
- package/bin/lean/conformance.e2e.test.mjs +32 -6
- package/bin/lean/conformance.mjs +57 -13
- package/bin/lean/conformance.test.mjs +93 -1
- package/bin/lean/execution.mjs +24 -12
- package/bin/lean/execution.test.mjs +59 -9
- package/bin/lean/forgedock-lane-workflow.test.mjs +62 -2
- package/bin/lean/issuewatch-reconcile.mjs +2 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +25 -0
- package/bin/lean/issuewatch.mjs +3 -0
- package/bin/lean/lanecheck.test.mjs +13 -1
- package/bin/lean/lean.mjs +214 -32
- package/bin/lean/lean.test.mjs +406 -21
- package/bin/lean/live-execution.mjs +25 -0
- package/bin/lean/live-execution.test.mjs +35 -1
- package/bin/lean/merged-park.mjs +76 -0
- package/bin/lean/merged-park.test.mjs +64 -0
- package/bin/lean/mergetrain.mjs +357 -0
- package/bin/lean/mergetrain.test.mjs +348 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -0
- package/bin/lean/orchestrate-stacking.test.mjs +144 -0
- package/bin/lean/orchestrate-train.test.mjs +130 -0
- package/bin/lean/orchestrate-transient-git.test.mjs +53 -0
- package/bin/lean/orchestrate.mjs +234 -17
- package/bin/lean/prompts.mjs +4 -3
- package/bin/lean/release-review.mjs +8 -1
- package/bin/lean/release-review.test.mjs +42 -2
- package/bin/lean/release-status.test.mjs +53 -1
- package/bin/lean/release.mjs +6 -3
- package/bin/lean/render.mjs +6 -1
- package/bin/lean/run-issue-placement.test.mjs +27 -3
- package/bin/lean/sandbox-provider.contract.test.mjs +6 -0
- package/bin/lean/sandbox-remote.mjs +12 -2
- package/bin/lean/sched.mjs +19 -2
- package/bin/lean/sched.test.mjs +33 -1
- package/bin/lean/schedd-health.mjs +2 -1
- package/bin/lean/schedd-health.test.mjs +7 -0
- package/bin/lean/schedd.mjs +55 -7
- package/bin/lean/schedd.test.mjs +42 -1
- package/bin/lean/stacking.mjs +140 -0
- package/bin/lean/stacking.test.mjs +98 -0
- package/bin/lean/statuscomment.mjs +14 -8
- package/bin/lean/statuscomment.test.mjs +18 -1
- package/bin/lean/validate-catalog.mjs +1 -1
- package/bin/lean/validate-catalog.test.mjs +3 -0
- package/bin/lean/worktree.mjs +8 -3
- package/bin/lean/worktree.test.mjs +18 -0
- package/bin/pool/agent.mjs +325 -46
- package/bin/pool/cache-sweep.mjs +2 -0
- package/bin/pool/cli.mjs +120 -6
- package/bin/pool/disk.mjs +43 -0
- package/bin/pool/docker.mjs +21 -5
- package/bin/pool/health.mjs +95 -0
- package/bin/pool/router.mjs +274 -27
- package/bin/runner.mjs +3 -1
- package/bin/stats/chains.mjs +101 -0
- package/bin/stats/chains.test.mjs +53 -0
- package/bin/stats/efficiency.mjs +7 -6
- package/bin/stats/efficiency.test.mjs +48 -7
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/stats.test.mjs +9 -0
- package/docs/CONFIG.md +23 -1
- package/docs/OUTCOME-CODES.md +4 -0
- package/package.json +1 -1
- package/pool/README.md +10 -0
- package/pool/image/Dockerfile +2 -1
- package/pool/image/entrypoint.sh +6 -6
- package/pool/image/mirror.sh +71 -0
- package/pool/install/install-agent-linux.sh +57 -5
- package/pool/install/install-agent-macos.sh +148 -0
- package/pool/install/install-agent.ps1 +11 -0
- package/pool/install/install-agent.sh +59 -7
- package/pool/install/uninstall-agent-linux.sh +75 -0
- package/pool/install/uninstall-agent-macos.sh +60 -0
- package/pool/install/uninstall-agent.ps1 +1 -0
- package/scripts/transition-label.sh +11 -0
|
@@ -41,10 +41,13 @@ describe("base red (#5239)", () => {
|
|
|
41
41
|
|
|
42
42
|
it("runOnBase runs each command in a detached base worktree and removes it", async () => {
|
|
43
43
|
const calls = [], cwds = [];
|
|
44
|
-
const git = async (a) => { calls.push(a.slice(0, 3).join(" ")); return ""; };
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
44
|
+
const git = async (a) => { calls.push(a.slice(0, 3).join(" ")); return a[0] === "rev-parse" ? `${"d".repeat(40)}\n` : ""; };
|
|
45
|
+
const envs = [];
|
|
46
|
+
const out = await runOnBase({ commands: ["x", "y"], git, mergeBase: "origin/staging", cwd: "/nonexistent", timeoutMs: 1000, env: { A: "1" },
|
|
47
|
+
runCommand: async ({ command, cwd, env }) => { cwds.push(cwd); envs.push(env); return { rc: command === "x" ? 1 : 0, output: `${"z".repeat(5000)}tail-${command}` }; } });
|
|
48
|
+
assert.deepEqual(out.map((o) => [o.command, o.rc]), [["x", 1], ["y", 0]]);
|
|
49
|
+
assert.equal(out[0].output.length, 4096); assert.ok(out[0].output.endsWith("tail-x"), "the tail of the output is kept");
|
|
50
|
+
assert.deepEqual(envs[0], { A: "1", BASE_SHA: "d".repeat(40), LANE_CHECK_BASE: "d".repeat(40) });
|
|
48
51
|
assert.match(calls[0], /^worktree add --detach$|^worktree add --detach /);
|
|
49
52
|
assert.ok(calls.some((c) => c.startsWith("worktree remove --force")));
|
|
50
53
|
assert.equal(cwds[0], cwds[1]);
|
|
@@ -60,7 +63,57 @@ describe("base red (#5239)", () => {
|
|
|
60
63
|
assert.match(gh[2].at(-1), /FORGE:BASE_RED[\s\S]*Lane #5 is deferred/);
|
|
61
64
|
gh.length = 0;
|
|
62
65
|
assert.equal(await reportBaseRed({ ghc, repo: "o/r", base: "staging", att: null, laneIssue: 5, commands: ["pytest g"] }), 77);
|
|
63
|
-
assert.
|
|
66
|
+
assert.ok(gh.some((a) => a[1] === "create"));
|
|
64
67
|
assert.equal(await reportBaseRed({ ghc: async () => { throw new Error("x"); }, repo: "o/r", base: "s", att: null, laneIssue: 5, commands: ["c"] }), null);
|
|
65
68
|
});
|
|
66
69
|
});
|
|
70
|
+
|
|
71
|
+
describe("base red dedupe and env classification (#5945)", () => {
|
|
72
|
+
const SHA12 = "a".repeat(12);
|
|
73
|
+
const fake = (issues) => { const log = []; const ghc = async (a) => { log.push(a); if (a[1] === "list") return JSON.stringify(issues.filter((i) => i.body)); if (a[1] === "create") { issues.push({ number: 90, state: "OPEN", createdAt: new Date().toISOString(), body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/90\n"; } return ""; }; return { log, ghc }; };
|
|
74
|
+
const args = (ghc, extra = {}) => ({ ghc, repo: "o/r", base: "staging", att: null, baseSha: "a".repeat(40), laneIssue: 5, commands: ["g"], outputs: { g: "boom ENDTAIL" }, ...extra });
|
|
75
|
+
|
|
76
|
+
it("two lanes with the same base+sha give one create then a comment; body holds the base output", async () => {
|
|
77
|
+
const { log, ghc } = fake([]);
|
|
78
|
+
assert.equal(await reportBaseRed(args(ghc)), 90);
|
|
79
|
+
assert.equal(await reportBaseRed(args(ghc, { laneIssue: 6 })), 90);
|
|
80
|
+
assert.equal(log.filter((a) => a[1] === "create").length, 1);
|
|
81
|
+
assert.equal(log.filter((a) => a[1] === "comment").length, 1);
|
|
82
|
+
const body = log.find((a) => a[1] === "create")[log.find((a) => a[1] === "create").indexOf("--body") + 1];
|
|
83
|
+
assert.match(body, /boom ENDTAIL/); assert.ok(body.includes(`staging@${SHA12}`));
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it("a closed match is reopened only when closed after the commit; within 24h it is commented, not duplicated", async () => {
|
|
87
|
+
const key = `<!-- FORGE:BASE_RED_KEY staging@${SHA12} -->`;
|
|
88
|
+
const old = new Date(Date.now() - 3 * 86400000).toISOString(), recent = new Date(Date.now() - 3600000).toISOString();
|
|
89
|
+
let f = fake([{ number: 7, state: "CLOSED", createdAt: old, closedAt: old, body: key }]);
|
|
90
|
+
await reportBaseRed(args(f.ghc, { commitDate: new Date(Date.now() - 86400000).toISOString() }));
|
|
91
|
+
assert.ok(!f.log.some((a) => a[1] === "reopen"), "closed before the commit: not reopened");
|
|
92
|
+
assert.ok(f.log.some((a) => a[1] === "create"), "older than a day: a new issue");
|
|
93
|
+
f = fake([{ number: 7, state: "CLOSED", createdAt: old, closedAt: recent, body: key }]);
|
|
94
|
+
assert.equal(await reportBaseRed(args(f.ghc, { commitDate: new Date(Date.now() - 86400000).toISOString() })), 7);
|
|
95
|
+
assert.ok(f.log.some((a) => a[1] === "reopen"));
|
|
96
|
+
f = fake([{ number: 8, state: "CLOSED", createdAt: recent, closedAt: recent, body: key }]);
|
|
97
|
+
assert.equal(await reportBaseRed(args(f.ghc)), 8, "rate limit: one issue per base+sha per day");
|
|
98
|
+
assert.ok(!f.log.some((a) => a[1] === "create" || a[1] === "reopen"));
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("classifyBaseRed: env signatures in the base output are env, not base red (and a clean red stays base red)", () => {
|
|
102
|
+
const failed = ["a", "b", "c", "d"].map((command) => ({ command, rc: 1 }));
|
|
103
|
+
const baseRuns = [{ command: "a", rc: 1, output: "ModuleNotFoundError: No module named x" }, { command: "b", rc: 1, output: "gh: fail closed" }, { command: "c", rc: 1, output: "fatal: bad revision 'origin/staging...HEAD'" }, { command: "d", rc: 1, output: "AssertionError: real" }];
|
|
104
|
+
const r = classifyBaseRed({ failed, baseRuns });
|
|
105
|
+
assert.deepEqual(r.env.map((f) => f.command), ["a", "b", "c"]); assert.deepEqual(r.baseRed.map((f) => f.command), ["d"]); assert.deepEqual(r.laneOwn, []);
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
describe("reportTrainBaseRed (#5838)", () => {
|
|
110
|
+
it("files a base-red issue naming the checks, the base tip and the batch, without a lane", async () => {
|
|
111
|
+
const calls = []; const ghc = async (a) => { calls.push(a); return "https://github.com/o/r/issues/77\n"; };
|
|
112
|
+
const { reportTrainBaseRed } = await import("./basered.mjs");
|
|
113
|
+
assert.equal(await reportTrainBaseRed({ ghc, repo: "o/r", base: "staging", baseSha: "c".repeat(40), checks: [{ name: "build", url: "https://ci/1" }], batch: "b1" }), 77);
|
|
114
|
+
const cr = calls.find((a) => a[1] === "create");
|
|
115
|
+
const body = cr[cr.indexOf("--body") + 1];
|
|
116
|
+
assert.match(body, /FORGE:BASE_RED/); assert.match(body, /`build` https:\/\/ci\/1/); assert.match(body, /batch b1/); assert.doesNotMatch(body, /Lane #/);
|
|
117
|
+
assert.match(cr[cr.indexOf("--title") + 1], /staging is red on required check build/);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -217,6 +217,13 @@ export function batchStatusLines(root, id, { now = Date.now() } = {}) {
|
|
|
217
217
|
const due = checkpointsOf(created, DEFAULT_HEALTH.checksMin).filter((c) => !h?.checks?.[c.label]);
|
|
218
218
|
if (due.length && !b.readReport()) out.push(` next checks: ${due.map((c) => `${c.label} ${new Date(c.at).toISOString().slice(11, 16)}Z${c.at < now ? " (due)" : ""}`).join(", ")}`);
|
|
219
219
|
}
|
|
220
|
+
// #5859: an agent/VM restart is one batch event (its lanes were requeued as sandbox.lost), not a health cause
|
|
221
|
+
let st = null;
|
|
222
|
+
try { st = b.store.load(); } catch { st = null; }
|
|
223
|
+
for (const g of Array.isArray(st?.agentRestarts) ? st.agentRestarts : []) {
|
|
224
|
+
const k = Array.isArray(g?.lanes) ? g.lanes.length : Number(g?.requeued) || 0;
|
|
225
|
+
if (g?.agent) out.push(` agent ${g.agent} restarted at ${g.at ?? "?"}; ${k} lane${k === 1 ? "" : "s"} requeued (sandbox.lost)${g.closed ? "" : ", waiting for the agent"}`);
|
|
226
|
+
}
|
|
220
227
|
return out;
|
|
221
228
|
}
|
|
222
229
|
|
|
@@ -306,24 +313,35 @@ export const DEFAULT_STALL_MIN = 3;
|
|
|
306
313
|
export const MAX_STALL_RECOVERIES = 3;
|
|
307
314
|
/** #5745: `; admission held by <code>: <detail>` for each failing preflight gate, "" when none. Pure. */
|
|
308
315
|
export const holdGateDetail = (gates) => (Array.isArray(gates) ? gates : []).filter((g) => g?.code).map((g) => `; admission held by ${g.code}: ${g.detail ?? "failing"}`).join("");
|
|
316
|
+
/** #5938: `{running, k, local, remote, text}`: the live lanes of a saved state against K; a run record with `remote` is a pool lane. Pure. */
|
|
317
|
+
export function runningSplit(state, parallel = null) {
|
|
318
|
+
const recs = Object.values(state?.running ?? {}), running = recs.length, remote = recs.filter((r) => r?.remote).length;
|
|
319
|
+
const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state?.parallel) && state.parallel > 0 ? state.parallel : 1;
|
|
320
|
+
return { running, k, local: running - remote, remote, text: `running ${running}/${k} (local ${running - remote}, remote ${remote})` };
|
|
321
|
+
}
|
|
322
|
+
|
|
309
323
|
/**
|
|
310
324
|
* #5314: dispatch stall. A batch with ready pending issues, free capacity and no progress for `windowMin` minutes. Ready: pending,
|
|
311
325
|
* not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
|
|
312
326
|
* schedd polls it. `hosted`: a runner is alive. `gates` (#5745): the failing preflight checks `[{code, detail}]` holding admission, named in the detail. @returns null (healthy) or `{code, ready, idleMin, hosted, detail[, gates]}`. Pure.
|
|
313
327
|
*/
|
|
314
|
-
export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [] } = {}) {
|
|
328
|
+
export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [], lanesAliveMs = null } = {}) {
|
|
315
329
|
if (!state || cancelled || reported || lastProgressMs === null) return null;
|
|
316
330
|
if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
|
|
317
331
|
const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
|
|
318
332
|
const running = Object.keys(state.running ?? {}).length;
|
|
319
333
|
const k = Number.isInteger(parallel) && parallel > 0 ? parallel : Number.isInteger(state.parallel) && state.parallel > 0 ? state.parallel : 1;
|
|
320
|
-
const
|
|
334
|
+
const live = new Set(Object.keys(state.running ?? {}).map(Number)); // #5938: a recovery lane keeps its issue in `pending`
|
|
335
|
+
const ready = (state.pending ?? []).map(Number).filter((n) => !live.has(n) && !heldSet.has(n) && results[n] === undefined && !(Number(state.notBefore?.[n]) > now)
|
|
321
336
|
&& (state.deps?.[n] ?? []).every((d) => !order.has(Number(d)) || Number(d) === n || GOOD_END.has(results[d]?.outcome)));
|
|
322
337
|
const idleMin = Math.floor((now - lastProgressMs) / 60000);
|
|
323
338
|
if (!ready.length || running >= k || idleMin < windowMin) return null;
|
|
324
339
|
const setup = state.phase === "setup" ? ` (stuck in setup, ${Number(state.setup?.read) || 0}/${Number(state.setup?.total) || ready.length} issues read)` : "";
|
|
325
340
|
const gated = (Array.isArray(gates) ? gates : []).filter((g) => g?.code);
|
|
326
|
-
|
|
341
|
+
const split = runningSplit(state, k), alive = Number.isFinite(lanesAliveMs) ? `; lanes alive ${Math.max(0, Math.floor((now - lanesAliveMs) / 60000))} min ago` : "";
|
|
342
|
+
const capReason = ready.every((n) => state.capReasons?.[n]) ? String(state.capReasons[ready[0]]) : null; // #5938: every ready issue is held by the pool
|
|
343
|
+
if (capReason) return { code: "pool-capacity", ready, idleMin, hosted, setup: !!setup, reason: capReason, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) waiting on pool capacity: ${capReason} (${split.text}); no dispatch for ${idleMin} min${alive}${holdGateDetail(gated)}` };
|
|
344
|
+
return { code: "dispatch-stalled", ready, idleMin, hosted, setup: !!setup, ...(gated.length ? { gates: gated.map((g) => g.code) } : {}), detail: `${ready.length} ready issue${ready.length === 1 ? "" : "s"} (${list(ready.slice(0, 8))}${ready.length > 8 ? ", …" : ""}) pending with ${k - running} free lane${k - running === 1 ? "" : "s"} (${split.text}) and no ${setup ? "progress" : "dispatch"} for ${idleMin} min${setup}${alive}; ${hosted ? "the runner is alive but not dispatching" : "no runner hosts the batch"}${holdGateDetail(gated)}` };
|
|
327
345
|
}
|
|
328
346
|
|
|
329
347
|
/**
|
|
@@ -390,6 +408,30 @@ export function recordStallAlert(batch, stall, { now = Date.now(), cause = null
|
|
|
390
408
|
return true;
|
|
391
409
|
}
|
|
392
410
|
|
|
411
|
+
/** #5938: drop a stored stall that no longer holds; logs `STALL CLEARED <t>` once. @returns true when one was cleared */
|
|
412
|
+
export function clearStaleStall(batch, { now = Date.now() } = {}) {
|
|
413
|
+
const prev = readHealth(batch.dir);
|
|
414
|
+
if (!prev?.stall) return false;
|
|
415
|
+
const { stall, ...rest } = prev, at = new Date(now).toISOString();
|
|
416
|
+
try { writeHealth(batch.dir, rest); } catch { return false; }
|
|
417
|
+
appendBatchLog(batch.dir, `${at} STALL CLEARED ${at}`);
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** #5938: the one watchdog line of a batch: healthy, stalled -> action taken, or stalled -> no action, and why. Pure. */
|
|
422
|
+
export function batchVerdict(id, stall, decision = null, { acted = false } = {}) {
|
|
423
|
+
if (!stall) return `batch ${id}: healthy`;
|
|
424
|
+
const why = `${stall.code}: ${stall.detail}`;
|
|
425
|
+
if (decision && decision.action !== "alert" && acted) return `batch ${id}: stalled -> action ${decision.action} (${why})`;
|
|
426
|
+
if (decision && decision.action !== "alert") return `batch ${id}: stalled -> no action yet (${decision.action} pending; ${why})`;
|
|
427
|
+
return `batch ${id}: stalled -> no action, needs you (${decision?.cause ? `${decision.cause}; ` : ""}${why})`;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** #5938: whether the batch still has ready issues with a free lane (the idle window was already met when the stall was stored). */
|
|
431
|
+
const stallStillHolds = (b, now) => {
|
|
432
|
+
try { const state = b.store.peek(); if (!state) return true; return evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: true, lastProgressMs: b.lastProgressMs() ?? now, now, windowMin: 0 }) !== null; } catch { return true; }
|
|
433
|
+
};
|
|
434
|
+
|
|
393
435
|
/** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
|
|
394
436
|
export function summaryLines(root, { now = Date.now() } = {}) {
|
|
395
437
|
const out = [];
|
|
@@ -399,7 +441,7 @@ export function summaryLines(root, { now = Date.now() } = {}) {
|
|
|
399
441
|
if (b.readReport() || b.readCancel()) continue;
|
|
400
442
|
const fh = readFirstHour(b.dir), h = readHealth(b.dir);
|
|
401
443
|
if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
|
|
402
|
-
if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
|
|
444
|
+
if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000 && stallStillHolds(b, now)) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
|
|
403
445
|
} catch { /* an unreadable batch has no line */ }
|
|
404
446
|
}
|
|
405
447
|
return out;
|
|
@@ -9,7 +9,7 @@ import { openBatch } from "./batch.mjs";
|
|
|
9
9
|
import { DEFAULT_HEALTH, parseHealthConfig, rootsOf, evaluateHealth, formatAlert, runCheck, scheduleChecks, scheduleLine, runNotify, deliverAlert,
|
|
10
10
|
resolvedOnGithub, recordRefusal, readRefusals, statusLines, REFUSAL_KEEP,
|
|
11
11
|
evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines, statelessNeedsHuman, statelessOnGithub,
|
|
12
|
-
DEFAULT_STALL_MIN, MAX_STALL_RECOVERIES, decideStallAction, recordStallRecovery, readHealth } from "./batch-health.mjs";
|
|
12
|
+
DEFAULT_STALL_MIN, MAX_STALL_RECOVERIES, decideStallAction, recordStallRecovery, readHealth, runningSplit, clearStaleStall, batchVerdict } from "./batch-health.mjs";
|
|
13
13
|
|
|
14
14
|
// #1 and #3 are roots; #2 depends on #1, #4 on #3.
|
|
15
15
|
const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
|
|
@@ -102,6 +102,15 @@ describe("#5167 checkpoints, alert-once and persistence", () => {
|
|
|
102
102
|
assert.match(one, /forgedock orchestrate --cancel b20260101-000000-1/);
|
|
103
103
|
});
|
|
104
104
|
|
|
105
|
+
it("#5859 agent restart event is shown by status --batch with its requeued count, not as a health cause", () => {
|
|
106
|
+
const { root, b } = mkBatch(base({ 1: { outcome: "merged" } }, { agentRestarts: [{ agent: "legion", at: "2026-01-01T00:05:00.000Z", last: 0, lanes: [1, 2, 3], requeued: 3, closed: true }] }));
|
|
107
|
+
const lines = statusLines(root, { batch: b.id });
|
|
108
|
+
assert.ok(lines.includes(" agent legion restarted at 2026-01-01T00:05:00.000Z; 3 lanes requeued (sandbox.lost)"), lines.join("\n"));
|
|
109
|
+
assert.equal(statusLines(root).length, 0, "not an unhealthy batch");
|
|
110
|
+
const { root: r2, b: b2 } = mkBatch(base({ 1: { outcome: "merged" } }));
|
|
111
|
+
assert.ok(!statusLines(r2, { batch: b2.id }).some((l) => /restarted/.test(l)), "older state without the field");
|
|
112
|
+
});
|
|
113
|
+
|
|
105
114
|
it("a healthy check records no alert, and a throwing channel never escapes", async () => {
|
|
106
115
|
const { b, root } = mkBatch(base({ 1: { outcome: "merged" } }, { running: { 3: {} }, pending: [2, 4] }));
|
|
107
116
|
const r = await runCheck({ batch: b, checkpoint: "T+15", alert: async () => { throw new Error("x"); } });
|
|
@@ -352,3 +361,48 @@ describe("#5469: holds in health and the first-hour report", () => {
|
|
|
352
361
|
assert.match(rep.summary, /#3 held \(op@h, since 2026-11-11T00:00:00.000Z\)/);
|
|
353
362
|
});
|
|
354
363
|
});
|
|
364
|
+
|
|
365
|
+
describe("#5938 stall verdict is re-evaluated: full K, recovery lanes, pool capacity, clear", () => {
|
|
366
|
+
const NOW = 10_000_000, MIN = 60000;
|
|
367
|
+
const st = (extra = {}) => ({ order: [1, 2, 3], deps: {}, results: {}, running: {}, pending: [1, 2, 3], parallel: 2, ...extra });
|
|
368
|
+
const stall = (state, o = {}) => evaluateDispatchStall(state, { lastProgressMs: NOW - 12 * MIN, now: NOW, windowMin: 10, ...o });
|
|
369
|
+
|
|
370
|
+
it("running == K with ready pending issues is healthy", () => {
|
|
371
|
+
assert.equal(stall(st({ running: { 1: { remote: true }, 2: {} } })), null);
|
|
372
|
+
});
|
|
373
|
+
it("a pending issue with a running record (recovery lane) is not ready", () => {
|
|
374
|
+
const r = stall(st({ running: { 1: {} }, pending: [1, 2] }));
|
|
375
|
+
assert.deepEqual(r.ready, [2]);
|
|
376
|
+
assert.equal(stall(st({ running: { 1: {} }, pending: [1], parallel: 2 })), null);
|
|
377
|
+
});
|
|
378
|
+
it("the detail names running/K with the local/remote split", () => {
|
|
379
|
+
const r = stall(st({ running: { 1: { remote: true } }, pending: [2, 3] }));
|
|
380
|
+
assert.match(r.detail, /running 1\/2 \(local 0, remote 1\)/);
|
|
381
|
+
assert.deepEqual(runningSplit(st({ running: { 1: {}, 2: { remote: true } } })), { running: 2, k: 2, local: 1, remote: 1, text: "running 2/2 (local 1, remote 1)" });
|
|
382
|
+
});
|
|
383
|
+
it("pool capacity deferrals report pool-capacity naming the pool's reason", () => {
|
|
384
|
+
const reason = "host_disk_free 10.8 GB < floor 25 + 3.5/sandbox";
|
|
385
|
+
const r = stall(st({ pending: [2, 3], capReasons: { 2: reason, 3: reason } }));
|
|
386
|
+
assert.equal(r.code, "pool-capacity");
|
|
387
|
+
assert.ok(r.detail.includes(reason));
|
|
388
|
+
assert.equal(stall(st({ pending: [2, 3], capReasons: { 2: reason } })).code, "dispatch-stalled", "one unblocked ready issue keeps the stall");
|
|
389
|
+
});
|
|
390
|
+
it("clearStaleStall removes the stored stall and logs STALL CLEARED; summaryLines skips a stall that no longer holds", () => {
|
|
391
|
+
const root = tmpDir("stall-clear-"), b = openBatch(root, "b1");
|
|
392
|
+
b.writePlan({ daemon: true, repo: "o/r" });
|
|
393
|
+
recordStallAlert(b, stall(st()), { now: NOW });
|
|
394
|
+
assert.equal(clearStaleStall(b, { now: NOW }), true);
|
|
395
|
+
assert.equal(readHealth(b.dir).stall, undefined);
|
|
396
|
+
assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /STALL CLEARED/);
|
|
397
|
+
assert.equal(clearStaleStall(b, { now: NOW }), false);
|
|
398
|
+
recordStallAlert(b, stall(st()), { now: NOW });
|
|
399
|
+
b.store.save(st({ running: { 1: {}, 2: {} } }));
|
|
400
|
+
assert.ok(!summaryLines(root, { now: NOW }).some((l) => /DISPATCH STALLED/.test(l)));
|
|
401
|
+
});
|
|
402
|
+
it("batchVerdict: healthy, stalled -> action, stalled -> no action", () => {
|
|
403
|
+
const s = stall(st());
|
|
404
|
+
assert.equal(batchVerdict("b1", null), "batch b1: healthy");
|
|
405
|
+
assert.match(batchVerdict("b1", s, { action: "resume" }, { acted: true }), /stalled -> action resume/);
|
|
406
|
+
assert.match(batchVerdict("b1", s, { action: "alert", cause: "no gh" }), /stalled -> no action, needs you \(no gh;/);
|
|
407
|
+
});
|
|
408
|
+
});
|
package/bin/lean/batch.mjs
CHANGED
|
@@ -110,8 +110,11 @@ const readAdded = (file) => {
|
|
|
110
110
|
};
|
|
111
111
|
|
|
112
112
|
/** `outcome`s `--requeue` may move back to pending (#4550); #5168: a final `engine-error` too (the runner clears its engine-error count); #5162: `held` rows too. */
|
|
113
|
-
export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
|
|
113
|
+
export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "pr-ready", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
|
|
114
114
|
/** Key of one requeue entry; the runner records the applied keys in state.json `requeueApplied`. */
|
|
115
|
+
/** #5832: the `{dependency, branch, sha}` a stacked build of `issue` was admitted on (batch state `stacked`), or null. Rows carry `stacked`/`stackedOn`. */
|
|
116
|
+
export const stackedOnOf = (state, issue) => state?.stacked?.[issue] ?? null;
|
|
117
|
+
|
|
115
118
|
export const requeueKey = (e) => `${e.issue}@${e.at}`;
|
|
116
119
|
|
|
117
120
|
const readRequeueFile = (file) => {
|
|
@@ -220,6 +223,11 @@ export function openBatch(root, id) {
|
|
|
220
223
|
if (!Number.isInteger(k) || k < 1) throw new Error("parallel must be a positive integer");
|
|
221
224
|
put(f("parallel"), `${k}\n`);
|
|
222
225
|
},
|
|
226
|
+
/** #5947: `--clear-breaker` for a hosted runner: the request file (a timestamp) is consumed by the runner, which answers in `clear-breaker.ack`. */
|
|
227
|
+
requestClearBreaker: () => { try { rmSync(f("clear-breaker.ack"), { force: true }); } catch { /* best effort */ } const at = Date.now(); put(f("clear-breaker"), `${at}\n`); return at; },
|
|
228
|
+
readClearBreaker: () => { try { readFileSync(f("clear-breaker"), "utf8"); rmSync(f("clear-breaker"), { force: true }); return true; } catch { return false; } },
|
|
229
|
+
ackClearBreaker: (info = {}) => put(f("clear-breaker.ack"), JSON.stringify({ at: Date.now(), ...info }) + "\n"),
|
|
230
|
+
readClearBreakerAck: () => readJson(f("clear-breaker.ack")),
|
|
223
231
|
/** Live execution override (#5138): the `execution` file `{maxRemote?, mode?, provider?}`, read on every admission; null when missing or invalid. */
|
|
224
232
|
readExecution: () => sanitizeOverride(readJson(f("execution"))),
|
|
225
233
|
/** Merge a validated patch into the `execution` file. @returns the stored override. */
|
package/bin/lean/batch.test.mjs
CHANGED
|
@@ -8,10 +8,14 @@ import { join } from "node:path";
|
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
9
|
import { resolveLane, makeLaneCache } from "./lane.mjs";
|
|
10
10
|
import { orchestrate, deferPolicy, DEFER_BACKOFF_S, formatOutcomeLists, CAPACITY_FALLBACK_AFTER, isTransientEngineError, transientRetryDelayMs, DEFAULT_TRANSIENT_RETRIES } from "./orchestrate.mjs";
|
|
11
|
-
import { openBatch, fsTypeOf, assertDiskPath, isLaneAlive, writeAtomic, launchLane, detachedLanes } from "./batch.mjs";
|
|
11
|
+
import { openBatch, fsTypeOf, assertDiskPath, isLaneAlive, writeAtomic, launchLane, detachedLanes, stackedOnOf } from "./batch.mjs";
|
|
12
12
|
import { makeLedger } from "./ledger.mjs";
|
|
13
|
+
import { placeLane } from "./execution.mjs";
|
|
14
|
+
import { liveRemote } from "./live-execution.mjs";
|
|
13
15
|
import { providerLanes } from "./execution.mjs";
|
|
14
16
|
import { orchestrateFromCli, runFromCli, readOrchestration, makeRelabelNeedsHuman, makeMarkRecovering, makeDispatchCheck } from "../engine-cli.mjs";
|
|
17
|
+
// Windows hosts: these tests exercise POSIX-only behaviour (file modes, tmpfs, systemd units, sh/bash scripts, file-URL paths); Linux CI runs them.
|
|
18
|
+
const POSIX_ONLY = process.platform === "win32" && "POSIX-only behaviour";
|
|
15
19
|
|
|
16
20
|
// orchestrateFromCli opens the host lane registry (#4191): keep it in a temp dir, also for spawned dispatchers.
|
|
17
21
|
process.env.FORGEDOCK_SCHED_DIR = tmpDir("batch-sched-");
|
|
@@ -241,7 +245,7 @@ await orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--
|
|
|
241
245
|
assert.equal(rows.length, 7);
|
|
242
246
|
});
|
|
243
247
|
|
|
244
|
-
it("batch files: atomic writes, live K via --set-parallel, tmpfs refused, pid reuse not adopted", async () => {
|
|
248
|
+
it("batch files: atomic writes, live K via --set-parallel, tmpfs refused, pid reuse not adopted", { skip: POSIX_ONLY }, async () => {
|
|
245
249
|
const root = tmpDir("batch-files-");
|
|
246
250
|
const b = openBatch(root, "b1");
|
|
247
251
|
b.writePlan({ argv: ["1"] });
|
|
@@ -267,9 +271,11 @@ await orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--
|
|
|
267
271
|
assert.equal(isLaneAlive(42, "lane", { kill: () => true, procDir: proc }), true);
|
|
268
272
|
writeFileSync(join(pd, "stat"), "42 (no) de) Z 1 42 42 0 -1\n");
|
|
269
273
|
assert.equal(isLaneAlive(42, "lane", { kill: () => true, procDir: proc }), false);
|
|
270
|
-
assert.deepEqual(
|
|
274
|
+
assert.deepEqual(stackedOnOf({ stacked: { 7: { dependency: 6, branch: "b", sha: "abcdef1" } } }, 7), { dependency: 6, branch: "b", sha: "abcdef1" }, "#5832: stackedOn read from batch state");
|
|
275
|
+
assert.equal(stackedOnOf({}, 7), null);
|
|
276
|
+
assert.deepEqual(readOrchestration(root), { breaker: { errors: 3, window_min: 30 }, maxDeferrals: 3, transientRetries: 4, blockedLabel: "blocked", globalParallel: null, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
|
|
271
277
|
writeFileSync(join(root, "forge.yaml"), "orchestration:\n breaker:\n errors: 5\n window_min: 10\n max_deferrals: 2\n global_parallel: 4\n transient_retries: 2\n");
|
|
272
|
-
assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] } });
|
|
278
|
+
assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
|
|
273
279
|
});
|
|
274
280
|
|
|
275
281
|
it("run-issue --result-file writes the lane result, also when the run throws", async () => {
|
|
@@ -384,6 +390,31 @@ describe("#4318: the batch dispatcher's signal relabel and the needs-human relab
|
|
|
384
390
|
assert.deepEqual(h.calls, ["view"]);
|
|
385
391
|
}
|
|
386
392
|
});
|
|
393
|
+
it("relabel skips an open issue whose fix PR merged on a non-lean head", async () => {
|
|
394
|
+
const calls = [];
|
|
395
|
+
const gh = async (a) => {
|
|
396
|
+
calls.push(a.slice(0, 2).join(" "));
|
|
397
|
+
if (a[1] === "view" && a[0] === "issue") return JSON.stringify({ state: "OPEN", body: "", labels: [], closedByPullRequestsReferences: [{ number: 41 }] });
|
|
398
|
+
if (a[0] === "pr") return JSON.stringify({ state: "MERGED", mergedAt: "2026-11-17T15:43:35Z" });
|
|
399
|
+
return "";
|
|
400
|
+
};
|
|
401
|
+
for (const parked of [null, { code: "env.validate_timeout" }]) assert.equal(await makeRelabelNeedsHuman({ gh, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why", parked }), "skipped");
|
|
402
|
+
assert.ok(!calls.includes("issue edit"));
|
|
403
|
+
const labelled = async (a) => (a[0] === "issue" && a[1] === "view" ? JSON.stringify({ state: "OPEN", body: "", labels: [{ name: "workflow:merged" }] }) : "");
|
|
404
|
+
assert.equal(await makeRelabelNeedsHuman({ gh: labelled, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why" }), "skipped");
|
|
405
|
+
});
|
|
406
|
+
it("relabel still parks an issue reopened after merge", async () => {
|
|
407
|
+
const calls = [];
|
|
408
|
+
const gh = async (a) => {
|
|
409
|
+
calls.push(a.slice(0, 2).join(" "));
|
|
410
|
+
if (a[0] === "issue" && a[1] === "view") return JSON.stringify({ state: "OPEN", body: "", labels: [], closedByPullRequestsReferences: [{ number: 41 }] });
|
|
411
|
+
if (a[0] === "pr") return JSON.stringify({ state: "MERGED", mergedAt: "2026-11-17T15:43:35Z" });
|
|
412
|
+
if (a[0] === "api" && a[1].endsWith("/events")) return "reopened\t2026-11-18T00:00:00.000Z\t";
|
|
413
|
+
return "";
|
|
414
|
+
};
|
|
415
|
+
assert.equal(await makeRelabelNeedsHuman({ gh, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "why" }), true);
|
|
416
|
+
assert.ok(calls.includes("issue edit"));
|
|
417
|
+
});
|
|
387
418
|
it("an expired lease relabels: the label first, then the comment", async () => {
|
|
388
419
|
const h = hook({ state: "OPEN", body: LIVE(500) });
|
|
389
420
|
assert.equal(await h.run(), true);
|
|
@@ -1454,7 +1485,7 @@ describe("#4592: forgedock orchestrate --hold / --release", () => {
|
|
|
1454
1485
|
});
|
|
1455
1486
|
|
|
1456
1487
|
describe("#4751: batch state is private", () => {
|
|
1457
|
-
it("batch state files are private", () => {
|
|
1488
|
+
it("batch state files are private", { skip: POSIX_ONLY }, () => {
|
|
1458
1489
|
const root = tmpDir("batch-private");
|
|
1459
1490
|
const old = process.umask(0o022);
|
|
1460
1491
|
try {
|
|
@@ -1475,7 +1506,7 @@ describe("#4751: batch state is private", () => {
|
|
|
1475
1506
|
});
|
|
1476
1507
|
|
|
1477
1508
|
describe("batch plan secrets (#4787)", () => {
|
|
1478
|
-
it("writePlan never writes secret env values and keeps the plan 0600", () => {
|
|
1509
|
+
it("writePlan never writes secret env values and keeps the plan 0600", { skip: POSIX_ONLY }, () => {
|
|
1479
1510
|
const b = openBatch(join(tmpDir("batch-sec-"), "batches"), "b20260101-000000-1");
|
|
1480
1511
|
b.writePlan({ v: 1, env: { PATH: "/bin", COMPUTESHARE_TOKEN: "tok-123", AWS_ACCESS_KEY: "k-456" } });
|
|
1481
1512
|
const raw = readFileSync(join(b.dir, "plan.json"), "utf8");
|
|
@@ -1484,7 +1515,7 @@ describe("batch plan secrets (#4787)", () => {
|
|
|
1484
1515
|
assert.deepEqual(b.readPlan().envSecrets, ["AWS_ACCESS_KEY", "COMPUTESHARE_TOKEN"]);
|
|
1485
1516
|
assert.equal(statSync(join(b.dir, "plan.json")).mode & 0o777, 0o600);
|
|
1486
1517
|
});
|
|
1487
|
-
it("scrubPlan rewrites a pre-fix 0644 plan and is a no-op otherwise", () => {
|
|
1518
|
+
it("scrubPlan rewrites a pre-fix 0644 plan and is a no-op otherwise", { skip: POSIX_ONLY }, () => {
|
|
1488
1519
|
const b = openBatch(join(tmpDir("batch-sec-"), "batches"), "b20260101-000000-2");
|
|
1489
1520
|
mkdirSync(b.dir, { recursive: true });
|
|
1490
1521
|
writeFileSync(join(b.dir, "plan.json"), JSON.stringify({ v: 1, env: { PATH: "/bin", COMPUTESHARE_TOKEN: "tok-123" } }), { mode: 0o644 });
|
|
@@ -1590,6 +1621,42 @@ describe("#5138: live max_remote and placement of a running batch", () => {
|
|
|
1590
1621
|
assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged", "merged"]);
|
|
1591
1622
|
assert.deepEqual(seen.find(([n]) => n === 3)[1], [3]);
|
|
1592
1623
|
});
|
|
1624
|
+
const liveDrain = (state) => liveRemote({ isRemote: () => true, capacity: () => null }, { exec: { mode: "remote", maxRemote: 2 }, readOverride: () => ({ maxRemote: state.m }), place: (e) => placeLane({ exec: e }) });
|
|
1625
|
+
it("#5933 remote batch at max_remote 0 holds lanes pending", async () => {
|
|
1626
|
+
const st = { m: 0 }, seen = [];
|
|
1627
|
+
const done = orchestrate({ issues: [1], parallel: 2, pollMs: 1, readBody: async () => "", sleep: tick, remote: liveDrain(st),
|
|
1628
|
+
runOne: async (n, _ln, ctx = {}) => { seen.push([n, ctx.placement?.where]); return { terminalReason: "merged", pr: 100 + n }; } });
|
|
1629
|
+
for (let i = 0; i < 20; i++) await tick();
|
|
1630
|
+
assert.deepEqual(seen, [], "nothing runs, locally or remotely, at max_remote 0");
|
|
1631
|
+
st.m = 1;
|
|
1632
|
+
await done;
|
|
1633
|
+
assert.deepEqual(seen, [[1, "remote"]]);
|
|
1634
|
+
});
|
|
1635
|
+
it("#5933 lowering max_remote to 0 leaves a running lane running", async () => {
|
|
1636
|
+
const st = { m: 2 }, seen = [];
|
|
1637
|
+
let open, running = false;
|
|
1638
|
+
const gate = new Promise((r) => { open = r; });
|
|
1639
|
+
const done = orchestrate({ issues: [1, 2], parallel: 2, pollMs: 1, readBody: async () => "", sleep: tick, remote: liveDrain(st),
|
|
1640
|
+
runOne: async (n, _ln, ctx = {}) => { seen.push([n, ctx.placement?.where]); if (n === 1) { running = true; await gate; } return { terminalReason: "merged", pr: 100 + n }; } });
|
|
1641
|
+
await until(() => running);
|
|
1642
|
+
st.m = 0;
|
|
1643
|
+
for (let i = 0; i < 20; i++) await tick();
|
|
1644
|
+
assert.ok(!seen.some(([n, w]) => w === "local"), "no lane lands on the host");
|
|
1645
|
+
open();
|
|
1646
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
1647
|
+
st.m = 2;
|
|
1648
|
+
const rows = await done;
|
|
1649
|
+
assert.deepEqual(rows.map((r) => r.outcome), ["merged", "merged"]);
|
|
1650
|
+
});
|
|
1651
|
+
it("#5933 --set-max-remote 0 prints drain semantics", async () => {
|
|
1652
|
+
const root = tmpDir("batch-drain-");
|
|
1653
|
+
const b = openBatch(root, "b1");
|
|
1654
|
+
b.writePlan({ argv: ["1"] });
|
|
1655
|
+
const lines = [], l = console.log;
|
|
1656
|
+
console.log = (...x) => { lines.push(x.join(" ")); };
|
|
1657
|
+
try { await orchestrateFromCli(["--set-max-remote", "b1", "0"], { batchRoot: root }); } finally { console.log = l; }
|
|
1658
|
+
assert.match(lines.join("\n"), /remote starts paused; nothing runs locally/);
|
|
1659
|
+
});
|
|
1593
1660
|
it("--set-max-remote / --set-placement write the batch's execution file; bad values and provider-less remote refused", async () => {
|
|
1594
1661
|
const root = tmpDir("batch-live-exec-");
|
|
1595
1662
|
const b = openBatch(root, "b1");
|
package/bin/lean/ceiling.mjs
CHANGED
|
@@ -25,10 +25,54 @@ export function parseCeilingBySize(engine) {
|
|
|
25
25
|
return Object.keys(out).length ? out : null;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
/** The ceiling
|
|
29
|
-
export
|
|
28
|
+
/** The ceiling a model without a known window keeps (#4390). */
|
|
29
|
+
export const DEFAULT_CEILING = 120000;
|
|
30
|
+
/** #5829: the share of a model's input window used as its default ceiling. */
|
|
31
|
+
export const WINDOW_SHARE = 0.5;
|
|
32
|
+
/** #5829: a session at this share of the window always restarts (digest), whatever continuing costs. */
|
|
33
|
+
export const REAL_LIMIT_SHARE = 0.9;
|
|
34
|
+
/** #5829: cache-read USD per token and an estimated restart cost, used when a model has no entry or the engine sets none. */
|
|
35
|
+
export const RESTART_COST_USD = 0.5;
|
|
36
|
+
export const CACHE_READ_USD = 0.5 / 1e6;
|
|
37
|
+
/** #5829: static input windows (tokens) and cache-read prices (USD per token), first match wins; no model-API lookup (this module is pure). */
|
|
38
|
+
export const MODEL_WINDOWS = [
|
|
39
|
+
{ match: /1m/i, window: 1000000, cacheRead: 0.5 / 1e6 },
|
|
40
|
+
{ match: /opus/i, window: 200000, cacheRead: 0.5 / 1e6 },
|
|
41
|
+
{ match: /sonnet/i, window: 200000, cacheRead: 0.3 / 1e6 },
|
|
42
|
+
{ match: /haiku/i, window: 200000, cacheRead: 0.1 / 1e6 },
|
|
43
|
+
];
|
|
44
|
+
/** The static entry for a routed model id; null when unknown. */
|
|
45
|
+
export function modelInfo(model) {
|
|
46
|
+
const m = String(model ?? "");
|
|
47
|
+
return m ? MODEL_WINDOWS.find((e) => e.match.test(m)) ?? null : null;
|
|
48
|
+
}
|
|
49
|
+
/** The default ceiling for `model`: `share` of its window; DEFAULT_CEILING for an unknown model. */
|
|
50
|
+
export function modelCeiling(model, share = WINDOW_SHARE) {
|
|
51
|
+
const e = modelInfo(model);
|
|
52
|
+
const sh = Number.isFinite(share) && share > 0 && share <= 1 ? share : WINDOW_SHARE;
|
|
53
|
+
return e ? Math.floor(e.window * sh) : DEFAULT_CEILING;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The ceiling for a lane of `size`: its per-size entry, else the global explicit one, else (#5829) the routed model's default
|
|
58
|
+
* (DEFAULT_CEILING for a null or unknown model) when the global one was not set explicitly (`tokens` null), else `tokens`.
|
|
59
|
+
*/
|
|
60
|
+
export function ceilingFor(size, { tokens = 0, bySize = null, model = null, share = WINDOW_SHARE } = {}) {
|
|
30
61
|
const v = bySize && SIZES.includes(size) ? bySize[size] : undefined;
|
|
31
|
-
|
|
62
|
+
if (Number.isFinite(v) && v >= 0) return v;
|
|
63
|
+
if (tokens == null) return modelCeiling(model, share); // no explicit ceiling: the model default, DEFAULT_CEILING for a null or unknown model
|
|
64
|
+
return tokens ?? 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* #5829: at a context stop, continue the session or restart it from the digest. Continuing costs `turnsLeft x context x cachePrice`;
|
|
69
|
+
* restarting costs `restartCost`. A session at REAL_LIMIT_SHARE of a known `window` always restarts; an unknown window never continues.
|
|
70
|
+
*/
|
|
71
|
+
export function restartDecision({ context = 0, turnsLeft = 0, cachePrice = CACHE_READ_USD, restartCost = RESTART_COST_USD, window = 0 } = {}) {
|
|
72
|
+
const continueCost = Math.max(0, turnsLeft) * Math.max(0, context) * cachePrice;
|
|
73
|
+
if (!(window > 0)) return { action: "restart", reason: "unknown_window", continueCost, restartCost };
|
|
74
|
+
if (context >= window * REAL_LIMIT_SHARE) return { action: "restart", reason: "real_limit", continueCost, restartCost };
|
|
75
|
+
return continueCost > restartCost ? { action: "restart", reason: "cost", continueCost, restartCost } : { action: "continue", reason: "cost", continueCost, restartCost };
|
|
32
76
|
}
|
|
33
77
|
|
|
34
78
|
/**
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX, routeHandoff, buildReadsOf, ROUTE_DIGEST_MAX_BYTES } from "./ceiling.mjs";
|
|
5
|
+
import { parseCeilingBySize, ceilingFor, predictRestart, handoffFacts, firstEditTurn, HANDOFF_FILES_MAX, routeHandoff, buildReadsOf, ROUTE_DIGEST_MAX_BYTES, modelCeiling, restartDecision, DEFAULT_CEILING, REAL_LIMIT_SHARE } from "./ceiling.mjs";
|
|
6
6
|
import { contextRestartPrompt, routeDigestPrompt } from "./prompts.mjs";
|
|
7
7
|
import { toolStats } from "./toolstats.mjs";
|
|
8
8
|
|
|
@@ -83,3 +83,34 @@ describe("route hand-off (#5812)", () => {
|
|
|
83
83
|
assert.match(huge, /<\/route_digest>$/);
|
|
84
84
|
});
|
|
85
85
|
});
|
|
86
|
+
|
|
87
|
+
describe("model-aware ceiling and cost gate (#5829)", () => {
|
|
88
|
+
it("modelCeiling 1M model gets about 500000", () => {
|
|
89
|
+
assert.equal(modelCeiling("claude-opus-5-5[1m]"), 500000);
|
|
90
|
+
assert.equal(modelCeiling("claude-sonnet-5-5"), 100000);
|
|
91
|
+
assert.equal(modelCeiling("claude-opus-5-5[1m]", 0.6), 600000);
|
|
92
|
+
});
|
|
93
|
+
it("an unknown or missing model keeps 120000", () => {
|
|
94
|
+
assert.equal(modelCeiling("some-local-model"), DEFAULT_CEILING); assert.equal(modelCeiling(null), 120000);
|
|
95
|
+
});
|
|
96
|
+
it("explicit context_ceiling_tokens wins over model default", () => {
|
|
97
|
+
const m = "claude-opus-5-5[1m]";
|
|
98
|
+
assert.equal(ceilingFor("M", { tokens: 90000, model: m }), 90000);
|
|
99
|
+
assert.equal(ceilingFor("M", { tokens: 0, model: m }), 0, "0 = off");
|
|
100
|
+
assert.equal(ceilingFor("M", { tokens: null, bySize: { M: 80000 }, model: m }), 80000);
|
|
101
|
+
assert.equal(ceilingFor("L", { tokens: null, bySize: { M: 80000 }, model: m }), 500000);
|
|
102
|
+
assert.equal(ceilingFor("M", { tokens: null }), DEFAULT_CEILING, "no model, nothing set: the 120000 default, not off");
|
|
103
|
+
assert.equal(ceilingFor("M", { tokens: null, model: "mystery-1" }), DEFAULT_CEILING);
|
|
104
|
+
assert.equal(ceilingFor("L", { tokens: null, bySize: { M: 80000 } }), DEFAULT_CEILING, "a size without an entry keeps the default");
|
|
105
|
+
});
|
|
106
|
+
it("restartDecision continues when restart costs more", () => {
|
|
107
|
+
const d = restartDecision({ context: 200000, turnsLeft: 2, cachePrice: 0.5e-6, restartCost: 0.5, window: 1000000 });
|
|
108
|
+
assert.equal(d.action, "continue"); assert.ok(d.continueCost < d.restartCost);
|
|
109
|
+
assert.equal(restartDecision({ context: 200000, turnsLeft: 50, cachePrice: 0.5e-6, restartCost: 0.5, window: 1000000 }).action, "restart");
|
|
110
|
+
});
|
|
111
|
+
it("restartDecision restarts at the model real limit", () => {
|
|
112
|
+
const d = restartDecision({ context: 1000000 * REAL_LIMIT_SHARE, turnsLeft: 0, restartCost: 100, window: 1000000 });
|
|
113
|
+
assert.equal(d.action, "restart"); assert.equal(d.reason, "real_limit");
|
|
114
|
+
assert.equal(restartDecision({ context: 1000, turnsLeft: 0, restartCost: 100 }).action, "restart", "unknown window never continues");
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -67,7 +67,7 @@ function makeWorld(dir, script) {
|
|
|
67
67
|
git(["add", "-A"], repo); git(["commit", "-q", "-m", "base"], repo);
|
|
68
68
|
git(["push", "-q", "origin", "main"], repo); git(["push", "-q", "origin", "main:staging"], repo); git(["fetch", "-q", "origin"], repo);
|
|
69
69
|
git(["clone", "-q", origin, merger], dir);
|
|
70
|
-
const gh = { issues: { 101: { ...ISSUE, state: "OPEN", reason: null, labels: new Set(), comments: [] } }, next: 200, prs: [] };
|
|
70
|
+
const gh = { issues: { 101: { ...(script.issue ?? ISSUE), state: "OPEN", reason: null, labels: new Set(), comments: [] } }, next: 200, prs: [] };
|
|
71
71
|
const counts = { builder: 0, reviewer: 0 };
|
|
72
72
|
const tools = (wt) => ({
|
|
73
73
|
write: (files) => writeAll(wt, files),
|
|
@@ -144,7 +144,7 @@ function builderScript(cs) {
|
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
146
|
/** A diligent reviewer made deterministic: every row comes from the worktree the engine handed it. */
|
|
147
|
-
function oracle(c) {
|
|
147
|
+
function oracle(c, quotes = Q) {
|
|
148
148
|
const between = (tag) => c.prompt.split(`<${tag}>\n`)[1].split(`\n</${tag}>`)[0];
|
|
149
149
|
const k = JSON.parse(between("contract")), files = between("changed_files").split("\n").filter(Boolean);
|
|
150
150
|
const read = (p) => { try { return fs.readFileSync(path.join(c.cwd, p), "utf8"); } catch { return ""; } };
|
|
@@ -158,9 +158,11 @@ function oracle(c) {
|
|
|
158
158
|
});
|
|
159
159
|
const covered = (q) => k.requirements.some((r) => r.quote === q) || k.preserve.some((p) => p.what.includes(q));
|
|
160
160
|
const billing = git(["diff", "--name-only", "origin/staging...HEAD", "--", "src/billing.js"], c.cwd).trim() !== "";
|
|
161
|
-
const rv = { issue_coverage: Object.values(
|
|
161
|
+
const rv = { issue_coverage: Object.values(quotes).map((q) => ({ quote: q, status: covered(q) ? "covered" : "missing" })), requirements: rows,
|
|
162
162
|
scope: files.map((f) => ({ file: f, authorized_by: k.deliverables.find((d) => d.path === f)?.id ?? (f.startsWith("test/") ? "test" : "none") })),
|
|
163
|
-
preserve: [{ id: "P1", status: billing ? "violated" : "intact", evidence: "src/billing.js:1" }, { id: "P2", status: "intact", evidence: "test/routes.test.js:1" }
|
|
163
|
+
preserve: [{ id: "P1", status: billing ? "violated" : "intact", evidence: "src/billing.js:1" }, { id: "P2", status: "intact", evidence: "test/routes.test.js:1" },
|
|
164
|
+
// history rows (H#) come from the host-wide ~/.forge/guards cache other test files write to; this repo has no such history
|
|
165
|
+
...k.preserve.filter((p) => /^H\d+$/.test(p.id)).map((p) => ({ id: p.id, status: "intact", evidence: "src/billing.js:1" }))], regressions: [] };
|
|
164
166
|
const bad = rv.issue_coverage.some((x) => x.status !== "covered") || rows.some((r) => ["missing", "partial"].includes(r.status)) || rv.scope.some((s) => s.authorized_by === "none") || billing;
|
|
165
167
|
return "```json\n" + JSON.stringify({ ...rv, verdict: bad ? "NONCONFORMING" : "CONFORMS", summary: "oracle" }) + "\n```";
|
|
166
168
|
}
|
|
@@ -168,7 +170,7 @@ const generic = () => "```json\n" + JSON.stringify({ verdict: "PASS", fixes_issu
|
|
|
168
170
|
|
|
169
171
|
async function runCase(cs, conformance = "enforce", extra = {}) {
|
|
170
172
|
const dir = tmpDir("conf-e2e-");
|
|
171
|
-
const w = makeWorld(dir, { builder: builderScript(cs), reviewer: (n, c) => (cs.generic ? generic() : oracle(c)) });
|
|
173
|
+
const w = makeWorld(dir, { builder: builderScript(cs), reviewer: (n, c) => (cs.generic ? generic() : oracle(c, cs.quotes)), issue: cs.issue });
|
|
172
174
|
if (extra.runCommand) w.io.runCommand = extra.runCommand;
|
|
173
175
|
const ret = await runCore({ issue: 101, repo: "o/r", lane: "staging", cwd: w.repo, worktreeRoot: path.join(dir, "wt"), dir: path.join(dir, "runs"), io: w.io, random: () => 0.5, stableMs: 0, livePollMs: 20, conformance, ...(extra.opts ?? {}) });
|
|
174
176
|
return { ...w.observe(ret), log: readLog(path.join(dir, "runs"), 101, { repo: "o/r" }) }; // #4432: keyed by repo
|
|
@@ -262,7 +264,7 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
|
|
|
262
264
|
it("#5087 a declared topology.route_reachability that rejects the new route blocks before merge (#38241 fixture)", async () => {
|
|
263
265
|
const ingress = path.join(tmpDir("ingress-"), "check-ingress.sh");
|
|
264
266
|
fs.writeFileSync(ingress, "for p in \"$@\"; do case \"$p\" in /api/v1/batch*) ;; /api/v1/*) echo \"unreachable: $p -> api\" >&2; exit 1 ;; esac; done\n");
|
|
265
|
-
const o = await runCase({ contract: ROUTED, impl: addRoute }, "enforce", { runCommand: runCheckCommand, opts: { routeReachability: `bash ${ingress}`, verify: { maxRounds: 0 } } });
|
|
267
|
+
const o = await runCase({ contract: ROUTED, impl: addRoute }, "enforce", { runCommand: runCheckCommand, opts: { routeReachability: `bash ${ingress.replace(/\\/g, "/")}`, verify: { maxRounds: 0 } } });
|
|
266
268
|
assert.equal(o.staging.search, false, "staging untouched");
|
|
267
269
|
assert.equal(o.ret.terminalReason, "needs-human"); assert.equal(o.pr, undefined, "no PR");
|
|
268
270
|
assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
|
|
@@ -275,6 +277,30 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
|
|
|
275
277
|
assert.ok(o.log.some((e) => e.event === "PRECHECK" && e.failures.includes("conformance.unimplemented")));
|
|
276
278
|
assert.match(o.ret.detail, /topology\.prod_parity/);
|
|
277
279
|
});
|
|
280
|
+
// #5750: a symptom plus a prescribed fix: the outcome rows bind, the prescription is guidance
|
|
281
|
+
const GQ = { R1: "Outstanding reservations return to 0 after a 429 on the scrape route.", R2: "Catch the rate limiter error in the scrape route and return an empty result.", AC3: Q.AC3 };
|
|
282
|
+
const GISSUE = { ...ISSUE, title: "429 leaks the scrape spend reservation", body: `## Problem\nWhen the rate limiter rejects a request with 429, the scrape route never releases the spend reservation.\n\n## Proposed fix\n${GQ.R2}\n\n## Acceptance\n- ${GQ.R1}\n- ${GQ.AC3}` };
|
|
283
|
+
const GUIDED = () => ({ requirements: [{ id: "R1", quote: GQ.R1, disposition: "deliver" }, { id: "R2", quote: GQ.R2, disposition: "guidance", why: "adapt: release the reservation and re-throw the 429 instead; an empty result hides the limit from the caller" }],
|
|
284
|
+
deliverables: [D.R1, D.R5], preserve: [{ id: "P1", what: `${Q.AC3} (src/billing.js price())` }, { id: "P2", what: `${Q.AC2} (test/routes.test.js)` }], validate: [{ id: "V1", command: V1 }] });
|
|
285
|
+
const prescribed = route("scrape", false).replace(" check(req.user, limits);", " try {\n check(req.user, limits);\n } catch (e) {\n if (e.status === 429) return { ok: false, scrape: [] };\n throw e;\n }");
|
|
286
|
+
it("#5750 the frozen contract binds the outcome and records the prescription as guidance", async () => {
|
|
287
|
+
const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => fix(t, ["scrape"]) });
|
|
288
|
+
const posted = o.issue.comments.find((x) => x.includes("FORGE:CONTRACT")) ?? "";
|
|
289
|
+
assert.match(posted, /guidance/);
|
|
290
|
+
merged(o); assert.equal(o.ret.terminalReason, "merged");
|
|
291
|
+
});
|
|
292
|
+
it("#5750 a lane meeting the outcome with a different fix passes", async () => {
|
|
293
|
+
const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => fix(t, ["scrape"]) });
|
|
294
|
+
merged(o);
|
|
295
|
+
const review = o.issue.comments.find((x) => x.includes("FORGE:REVIEW")) ?? "";
|
|
296
|
+
assert.ok(review.includes("| R2 | guidance (non-binding): adapt: release the reservation"), "the guidance row shows its stance and reason");
|
|
297
|
+
assert.ok(review.includes("**Issue coverage:** 2/2 "), "the guidance row is not counted as an issue requirement");
|
|
298
|
+
});
|
|
299
|
+
it("#5750 a lane following the prescription but missing the outcome fails", async () => {
|
|
300
|
+
const o = await runCase({ issue: GISSUE, quotes: GQ, contract: GUIDED, impl: (t) => t.write({ "src/routes/scrape.js": prescribed, "test/leak.test.js": leakTest([]) }) });
|
|
301
|
+
assert.equal(o.ret.terminalReason, "needs-human"); assert.equal(o.pr, undefined, "no PR"); assert.equal(o.issue.state, "OPEN");
|
|
302
|
+
assert.equal(o.ret.code, "conformance.unimplemented");
|
|
303
|
+
});
|
|
278
304
|
it("6 a generic PASS over an incomplete implementation never merges (review.incomplete)", async () => {
|
|
279
305
|
const o = await runCase({ contract: FULL, impl: (t) => fix(t, ["scrape", "export"]), generic: true });
|
|
280
306
|
blocked(o, "review.incomplete"); assert.deepEqual([o.counts.builder, o.counts.reviewer], [2, 2]);
|