forgedock 1.54.1 → 1.55.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +12 -0
- package/bin/engine/events.mjs +1 -0
- package/bin/engine/events.test.mjs +5 -1
- package/bin/engine/outcome-codes.mjs +3 -0
- package/bin/engine-cli.mjs +126 -34
- package/bin/forge-utils.mjs +37 -5
- package/bin/forgedock.mjs +54 -2
- package/bin/gc-schedule.mjs +83 -0
- package/bin/gc.mjs +66 -10
- package/bin/help-text.mjs +1 -1
- package/bin/hooks/pre-tool-use.mjs +1 -0
- package/bin/init-detect.mjs +73 -2
- package/bin/labels.json +5 -0
- package/bin/lean/admission.mjs +21 -1
- package/bin/lean/baselines.mjs +43 -0
- package/bin/lean/baselines.test.mjs +33 -0
- package/bin/lean/batch-health.mjs +43 -6
- package/bin/lean/batch-health.test.mjs +41 -1
- package/bin/lean/batch.mjs +41 -4
- package/bin/lean/batch.test.mjs +106 -3
- package/bin/lean/conformance.mjs +131 -12
- package/bin/lean/conformance.test.mjs +172 -3
- package/bin/lean/depcache.mjs +23 -2
- package/bin/lean/depcache.test.mjs +22 -0
- package/bin/lean/docsgate.mjs +137 -0
- package/bin/lean/docsgate.test.mjs +78 -0
- package/bin/lean/effects.mjs +31 -2
- package/bin/lean/enumerating.mjs +39 -13
- package/bin/lean/enumerating.test.mjs +20 -0
- package/bin/lean/execution.test.mjs +3 -3
- package/bin/lean/fastforward.mjs +93 -0
- package/bin/lean/fastforward.test.mjs +73 -0
- package/bin/lean/guardgate.mjs +38 -7
- package/bin/lean/guardgate.test.mjs +39 -0
- package/bin/lean/issuewatch-install.mjs +92 -0
- package/bin/lean/issuewatch-install.test.mjs +31 -0
- package/bin/lean/issuewatch-parity.mjs +33 -3
- package/bin/lean/issuewatch-parity.test.mjs +30 -5
- package/bin/lean/issuewatch-reconcile.mjs +123 -0
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/issuewatch-verify.mjs +51 -9
- package/bin/lean/issuewatch.mjs +153 -33
- package/bin/lean/issuewatch.test.mjs +243 -22
- package/bin/lean/lean.mjs +381 -75
- package/bin/lean/lean.test.mjs +437 -20
- package/bin/lean/light.mjs +11 -3
- package/bin/lean/light.test.mjs +27 -0
- package/bin/lean/lightlane.mjs +8 -3
- package/bin/lean/lightlane.test.mjs +20 -0
- package/bin/lean/mechfix.mjs +21 -2
- package/bin/lean/mechfix.test.mjs +28 -1
- package/bin/lean/orchestrate-children.test.mjs +10 -0
- package/bin/lean/orchestrate-owned.test.mjs +73 -0
- package/bin/lean/orchestrate.mjs +28 -4
- package/bin/lean/overlap.mjs +20 -0
- package/bin/lean/overlap.test.mjs +49 -0
- package/bin/lean/pagegate.mjs +152 -0
- package/bin/lean/pagegate.test.mjs +77 -0
- package/bin/lean/parked-relabel.mjs +32 -0
- package/bin/lean/parked-relabel.test.mjs +45 -0
- package/bin/lean/phaseledger.mjs +17 -2
- package/bin/lean/postdeploy-check.mjs +27 -0
- package/bin/lean/postdeploy-check.test.mjs +13 -1
- package/bin/lean/postrun.mjs +32 -0
- package/bin/lean/postrun.test.mjs +41 -0
- package/bin/lean/preflight.mjs +46 -0
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/prompts.mjs +36 -6
- package/bin/lean/recovery.test.mjs +16 -0
- package/bin/lean/release-review.mjs +12 -1
- package/bin/lean/release-review.test.mjs +14 -0
- package/bin/lean/release.mjs +23 -2
- package/bin/lean/release.test.mjs +28 -1
- package/bin/lean/render.mjs +17 -6
- package/bin/lean/reproquality.mjs +116 -0
- package/bin/lean/reproquality.test.mjs +85 -0
- package/bin/lean/review-trigger.mjs +8 -3
- package/bin/lean/sandbox-budget.test.mjs +27 -0
- package/bin/lean/schedd.mjs +40 -11
- package/bin/lean/schedd.test.mjs +12 -1
- package/bin/lean/testadequacy.mjs +97 -0
- package/bin/lean/testadequacy.test.mjs +92 -0
- package/bin/lean/testsandbox.mjs +202 -0
- package/bin/lean/testsandbox.test.mjs +157 -0
- package/bin/lean/toolplace.mjs +5 -2
- package/bin/lean/toolplace.test.mjs +6 -0
- package/bin/lean/verify.mjs +6 -1
- package/bin/lean/verify.test.mjs +18 -2
- package/bin/lean/warmtree.mjs +77 -0
- package/bin/lean/warmtree.test.mjs +81 -0
- package/bin/review-staging.mjs +51 -9
- package/bin/stats/conformance-outcomes.mjs +12 -2
- package/bin/stats/depth.mjs +24 -1
- package/bin/stats/depth.test.mjs +21 -1
- package/bin/stats/index.mjs +5 -2
- package/bin/stats/query.mjs +2 -1
- package/commands/cleanup.md +18 -0
- package/commands/fd-introspect.md +19 -0
- package/commands/milestone.md +5 -1
- package/commands/pipeline-health/phase-2-metrics.md +4 -0
- package/commands/recover-orphans.md +31 -1
- package/commands/review-pr-staging.md +9 -0
- package/commands/review-pr.md +2 -0
- package/docs/CONFIG.md +26 -1
- package/docs/EVENTS.md +1 -0
- package/docs/ISSUE-WATCH.md +12 -3
- package/docs/eval/adversarial-bench.md +1 -1
- package/docs/eval/published/adversarial-2026-11-11.md +58 -0
- package/package.json +1 -1
- package/scripts/bench-lightlane.mjs +3 -2
- package/scripts/hotspots.sh +7 -4
- package/scripts/hotspots.test.sh +12 -0
- package/scripts/recover-orphans-stateless.test.sh +79 -0
- package/scripts/transition-label.sh +2 -0
- package/templates/workflows/forgedock-reopen-clean.yml +33 -0
|
@@ -15,6 +15,8 @@ import { join } from "node:path";
|
|
|
15
15
|
import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
|
|
16
16
|
|
|
17
17
|
export const DEFAULT_HEALTH = Object.freeze({ rootFailed: true, terminalShare: 0.5, stalled: true, checksMin: Object.freeze([15, 60]), issue: null, notifyCommand: null });
|
|
18
|
+
/** #5469: a hold older than this many hours is flagged (`config.holdHours` overrides). */
|
|
19
|
+
export const DEFAULT_HOLD_HOURS = 4;
|
|
18
20
|
/** Outcomes that end a row well: never counted against the batch. */
|
|
19
21
|
export const GOOD_END = new Set(["merged", "invalid", "decomposed"]);
|
|
20
22
|
export const REFUSALS_FILE = "refusals.json";
|
|
@@ -48,7 +50,7 @@ export function rootsOf(state) {
|
|
|
48
50
|
* stall); `refused`: a refusal record (the launch never started); `resolved` (#5243): issues already
|
|
49
51
|
* resolved on GitHub (merged by hand), counted as good ends. Pure.
|
|
50
52
|
*/
|
|
51
|
-
export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null, resolved = [] } = {}) {
|
|
53
|
+
export function evaluateHealth(state, { held = [], refused = null, config = DEFAULT_HEALTH, batchId = "<id>", repo = null, resolved = [], stateless = [], holdInfo = null, now = Date.now() } = {}) {
|
|
52
54
|
const causes = [], recovery = [];
|
|
53
55
|
if (refused) {
|
|
54
56
|
causes.push({ code: "refused", issues: refused.issues ?? [], detail: refused.message ?? "launch refused" });
|
|
@@ -78,8 +80,14 @@ export function evaluateHealth(state, { held = [], refused = null, config = DEFA
|
|
|
78
80
|
if (config.stalled && !running.size && waiting.length && state?.phase !== "setup" && !state?.cancelled) {
|
|
79
81
|
causes.push({ code: "stalled", issues: waiting, detail: `0 lanes running while ${waiting.length} issue${waiting.length === 1 ? "" : "s"} pending${state?.breaker ? " (breaker tripped)" : ""}` });
|
|
80
82
|
}
|
|
83
|
+
// #5466: a finished lane with a needs-human comment but no state label looks untouched to a person and to issue-watch.
|
|
84
|
+
if (stateless.length) causes.push({ code: "stateless", issues: stateless, detail: `${stateless.map((n) => `#${n}`).join(", ")}: needs-human comment but no state label; re-add needs-human (or /recover-orphans)` });
|
|
85
|
+
// #5469: a hold older than `holdHours` is flagged (hold-info records its owner and since); the legacy plain hold has no age
|
|
86
|
+
const holdHours = Number(config.holdHours) > 0 ? Number(config.holdHours) : DEFAULT_HOLD_HOURS, holdMs = holdHours * 3600000;
|
|
87
|
+
const stale = Object.entries(holdInfo ?? {}).filter(([n, e]) => heldSet.has(Number(n)) && Date.parse(e?.since) <= now - holdMs);
|
|
88
|
+
if (stale.length) causes.push({ code: "stale-hold", issues: stale.map(([n]) => Number(n)), detail: `held by operator for over ${holdHours}h: ${stale.slice(0, 6).map(([n, e]) => `#${n} (${e.owner}, since ${e.since})`).join(", ")}; forgedock orchestrate --release ${batchId} <issue...>` });
|
|
81
89
|
if (!causes.length) return { healthy: true, causes, recovery };
|
|
82
|
-
const failed = [...new Set(causes.filter((c) => c.code !== "stalled").flatMap((c) => c.issues))];
|
|
90
|
+
const failed = [...new Set(causes.filter((c) => c.code !== "stalled" && c.code !== "stale-hold" && c.code !== "stateless").flatMap((c) => c.issues))];
|
|
83
91
|
const requeue = failed.filter((n) => REQUEUABLE(outcomeOf(n))), relaunch = failed.filter((n) => !REQUEUABLE(outcomeOf(n)));
|
|
84
92
|
if (requeue.length) recovery.push(`forgedock orchestrate --requeue ${batchId} ${requeue.join(" ")} --reason "batch unhealthy"`);
|
|
85
93
|
if (relaunch.length) recovery.push(`forgedock orchestrate ${relaunch.join(" ")}${repo ? ` --repo ${repo}` : ""} # after fixing the cause (see lanes/<n>.log)`);
|
|
@@ -111,7 +119,7 @@ export function scheduleLine(batchId, created, checksMin = DEFAULT_HEALTH.checks
|
|
|
111
119
|
* One checkpoint: evaluate the batch, persist it, and call `alert(text, health)` on the first unhealthy result only.
|
|
112
120
|
* @returns the evaluation, plus `alerted` when this call raised the alert
|
|
113
121
|
*/
|
|
114
|
-
export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {}, resolve = null }) {
|
|
122
|
+
export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, repo = null, now = () => Date.now(), alert = async () => {}, resolve = null, statelessOf = null }) {
|
|
115
123
|
const state = batch.store.load() ?? {};
|
|
116
124
|
let held = [];
|
|
117
125
|
try { held = batch.readHeld?.() ?? []; } catch { held = []; }
|
|
@@ -122,7 +130,11 @@ export async function runCheck({ batch, checkpoint, config = DEFAULT_HEALTH, rep
|
|
|
122
130
|
const cand = (state.order ?? []).map(Number).filter((n) => res[n]?.outcome !== undefined && !GOOD_END.has(res[n].outcome) && !run.has(n)).map((n) => ({ issue: n, outcome: res[n].outcome }));
|
|
123
131
|
try { if (cand.length) resolved = (await resolve(cand) ?? []).map(Number); } catch { resolved = []; }
|
|
124
132
|
}
|
|
125
|
-
|
|
133
|
+
let stateless = [];
|
|
134
|
+
try { if (statelessOf) stateless = (await statelessOf(state) ?? []).map(Number); } catch { stateless = []; }
|
|
135
|
+
let holdInfo = null;
|
|
136
|
+
try { holdInfo = batch.readHoldInfo?.() ?? null; } catch { holdInfo = null; }
|
|
137
|
+
const health = evaluateHealth(state, { held, config, batchId: batch.id, repo, resolved, stateless, holdInfo, now: now() });
|
|
126
138
|
const prev = readHealth(batch.dir) ?? {};
|
|
127
139
|
const at = new Date(now()).toISOString();
|
|
128
140
|
const next = { ...prev, checks: { ...(prev.checks ?? {}), [checkpoint]: at }, last: { at, checkpoint, healthy: health.healthy, ...(resolved.length ? { resolved } : {}), causes: health.causes, recovery: health.recovery } };
|
|
@@ -227,6 +239,31 @@ export function statusLines(root, { now = Date.now(), batch = null } = {}) {
|
|
|
227
239
|
return out;
|
|
228
240
|
}
|
|
229
241
|
|
|
242
|
+
/**
|
|
243
|
+
* #5466: open issues that carry a FORGE:NEEDS_HUMAN comment but no state label (needs-human, parked:*, remediation-queue,
|
|
244
|
+
* workflow:*): they look untouched to a person and to issue-watch. `issues` is `[{number, state, labels: [name], comments: [body]}]`.
|
|
245
|
+
* @returns issue numbers
|
|
246
|
+
*/
|
|
247
|
+
export function statelessNeedsHuman(issues) {
|
|
248
|
+
const stateLabel = (l) => l === "needs-human" || l.startsWith("needs-human:") || l.startsWith("parked:") || l === "remediation-queue" || l.startsWith("workflow:");
|
|
249
|
+
return (issues ?? []).filter((i) => String(i?.state ?? "OPEN").toUpperCase() === "OPEN"
|
|
250
|
+
&& (i.comments ?? []).some((c) => String(c).includes("<!-- FORGE:NEEDS_HUMAN"))
|
|
251
|
+
&& !(i.labels ?? []).some((l) => stateLabel(String(l)))).map((i) => i.number);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** #5466: the batch's open issues that GitHub shows stateless (see `statelessNeedsHuman`). A read failure skips the issue. */
|
|
255
|
+
export async function statelessOnGithub(state, gh, repo) {
|
|
256
|
+
const run = new Set(Object.keys(state?.running ?? {}).map(Number));
|
|
257
|
+
const rows = [];
|
|
258
|
+
for (const n of (state?.order ?? []).map(Number).filter((x) => !run.has(x))) {
|
|
259
|
+
try {
|
|
260
|
+
const v = JSON.parse(await gh(["issue", "view", String(n), "-R", repo, "--json", "number,state,labels,comments"]));
|
|
261
|
+
rows.push({ number: n, state: v.state, labels: (v.labels ?? []).map((l) => l.name), comments: (v.comments ?? []).map((c) => c.body) });
|
|
262
|
+
} catch { /* unreadable: not flagged */ }
|
|
263
|
+
}
|
|
264
|
+
return statelessNeedsHuman(rows);
|
|
265
|
+
}
|
|
266
|
+
|
|
230
267
|
/**
|
|
231
268
|
* #5243: which `[{issue, outcome}]` rows GitHub shows as resolved: the issue is CLOSED with a MERGED closing PR, or a
|
|
232
269
|
* `needs-human` row whose label was removed with a `FORGE:DECISION` comment. Any read failure leaves the row unresolved.
|
|
@@ -279,11 +316,11 @@ export const readFirstHour = (dir) => readJson(join(dir, FIRST_HOUR_FILE));
|
|
|
279
316
|
export const appendBatchLog = (dir, text) => { try { appendFileSync(join(dir, BATCH_LOG_FILE), `${text}\n`, { mode: 0o600 }); } catch { /* advisory */ } };
|
|
280
317
|
|
|
281
318
|
/** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
|
|
282
|
-
export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null } = {}) {
|
|
319
|
+
export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null } = {}) {
|
|
283
320
|
const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
|
|
284
321
|
const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
|
|
285
322
|
const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
|
|
286
|
-
const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
|
|
323
|
+
const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held${holdInfo?.[n] ? ` (${holdInfo[n].owner}, since ${holdInfo[n].since})` : ""}` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
|
|
287
324
|
const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
|
|
288
325
|
const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
|
|
289
326
|
const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
|
|
@@ -8,7 +8,7 @@ import { tmpDir } from "../tests/_tmp.mjs";
|
|
|
8
8
|
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
|
-
evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines } from "./batch-health.mjs";
|
|
11
|
+
evaluateDispatchStall, firstHourReport, writeFirstHour, readFirstHour, recordStallAlert, summaryLines, statelessNeedsHuman, statelessOnGithub } from "./batch-health.mjs";
|
|
12
12
|
|
|
13
13
|
// #1 and #3 are roots; #2 depends on #1, #4 on #3.
|
|
14
14
|
const base = (results, extra = {}) => ({ order: [1, 2, 3, 4], deps: { 2: [1], 4: [3] }, results, running: {}, pending: [], ...extra });
|
|
@@ -240,3 +240,43 @@ describe("#5314 dispatch stall and first-hour report", () => {
|
|
|
240
240
|
assert.ok(summaryLines(root, { now: Date.parse(new Date(NOW).toISOString()) }).some((l) => /DISPATCH STALLED/.test(l)));
|
|
241
241
|
});
|
|
242
242
|
});
|
|
243
|
+
|
|
244
|
+
describe("#5466 statelessNeedsHuman", () => {
|
|
245
|
+
const nh = ["<!-- FORGE:NEEDS_HUMAN -->\nx"];
|
|
246
|
+
it("flags an open issue with a NEEDS_HUMAN comment and no state label", () => {
|
|
247
|
+
assert.deepEqual(statelessNeedsHuman([
|
|
248
|
+
{ number: 1, state: "OPEN", labels: ["bug"], comments: nh },
|
|
249
|
+
{ number: 2, state: "OPEN", labels: ["parked:ci.red"], comments: nh },
|
|
250
|
+
{ number: 3, state: "OPEN", labels: ["needs-human"], comments: nh },
|
|
251
|
+
{ number: 4, state: "CLOSED", labels: [], comments: nh },
|
|
252
|
+
{ number: 5, state: "OPEN", labels: [], comments: ["hello"] },
|
|
253
|
+
]), [1]);
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
describe("#5466 stateless issues surface in the batch health check", () => {
|
|
258
|
+
it("evaluateHealth reports a stateless cause; statelessOnGithub reads labels and comments", async () => {
|
|
259
|
+
const h = evaluateHealth(base({ 1: { outcome: "merged" } }), { stateless: [2] });
|
|
260
|
+
assert.equal(h.healthy, false);
|
|
261
|
+
assert.equal(h.causes[0].code, "stateless");
|
|
262
|
+
const gh = async (a) => JSON.stringify(a[2] === "1" ? { state: "OPEN", labels: [], comments: [{ body: "<!-- FORGE:NEEDS_HUMAN -->" }] } : { state: "OPEN", labels: [{ name: "needs-human" }], comments: [{ body: "<!-- FORGE:NEEDS_HUMAN -->" }] });
|
|
263
|
+
assert.deepEqual(await statelessOnGithub({ order: [1, 2] }, gh, "o/r"), [1]);
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
describe("#5469: holds in health and the first-hour report", () => {
|
|
268
|
+
const since = (h) => new Date(Date.now() - h * 3600000).toISOString();
|
|
269
|
+
it("#5469: a hold older than holdHours is a stale-hold cause; a recent or legacy hold is not", () => {
|
|
270
|
+
const st = base({ 1: { outcome: "merged" } }, { pending: [3], running: { 4: {} } });
|
|
271
|
+
const stale = evaluateHealth(st, { held: [3], holdInfo: { 3: { owner: "op@h", since: since(5) } }, batchId: "b1" });
|
|
272
|
+
assert.equal(stale.healthy, false);
|
|
273
|
+
assert.deepEqual(stale.causes.map((c) => c.code), ["stale-hold"]);
|
|
274
|
+
assert.match(stale.causes[0].detail, /#3 \(op@h, since /);
|
|
275
|
+
assert.equal(evaluateHealth(st, { held: [3], holdInfo: { 3: { owner: "op@h", since: since(1) } } }).healthy, true);
|
|
276
|
+
assert.equal(evaluateHealth(st, { held: [3] }).healthy, true, "a legacy hold has no age");
|
|
277
|
+
});
|
|
278
|
+
it("the first-hour report lists a held issue as held (owner, since)", () => {
|
|
279
|
+
const rep = firstHourReport(base({}, { pending: [3] }), { batchId: "b1", held: [3], holdInfo: { 3: { owner: "op@h", since: "2026-11-11T00:00:00.000Z" } } });
|
|
280
|
+
assert.match(rep.summary, /#3 held \(op@h, since 2026-11-11T00:00:00.000Z\)/);
|
|
281
|
+
});
|
|
282
|
+
});
|
package/bin/lean/batch.mjs
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
*/
|
|
18
18
|
import { appendFileSync, chmodSync, closeSync, existsSync, fchmodSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
|
|
19
19
|
import { spawn } from "node:child_process";
|
|
20
|
-
import { homedir } from "node:os";
|
|
20
|
+
import { homedir, hostname } from "node:os";
|
|
21
21
|
import { dirname, join, resolve, sep } from "node:path";
|
|
22
22
|
import { sanitizeOverride, validateExecutionPatch } from "./live-execution.mjs";
|
|
23
23
|
|
|
@@ -97,6 +97,13 @@ const readRequeueFile = (file) => {
|
|
|
97
97
|
};
|
|
98
98
|
|
|
99
99
|
/** The positive integers among `list` (numbers, `7`, `#7`). */
|
|
100
|
+
/** #5469: the `hold-info` file as an object; {} when missing or invalid. */
|
|
101
|
+
const readHoldInfo = (file) => { try { const v = JSON.parse(readFileSync(file, "utf8")); return v && typeof v === "object" && !Array.isArray(v) ? v : {}; } catch { return {}; } };
|
|
102
|
+
/** #5469: the hold owner's session pid is known, on this host, and no longer alive. */
|
|
103
|
+
const ownerGone = (e) => {
|
|
104
|
+
if (!Number.isSafeInteger(e?.ownerPid) || e.ownerPid < 1 || (e.ownerHost && e.ownerHost !== hostname())) return false;
|
|
105
|
+
try { process.kill(e.ownerPid, 0); return false; } catch (err) { return err?.code === "ESRCH"; }
|
|
106
|
+
};
|
|
100
107
|
const ints = (list) => (Array.isArray(list) ? list : []).map((x) => (typeof x === "number" ? x : typeof x === "string" && /^#?\d+$/.test(x.trim()) ? parseInt(x.trim().replace("#", ""), 10) : NaN)).filter((n) => Number.isSafeInteger(n) && n > 0);
|
|
101
108
|
|
|
102
109
|
export function newBatchId(now = Date.now(), pid = process.pid) {
|
|
@@ -131,7 +138,7 @@ export function batchesOwning(root, repo, issue, { exceptId = null, now = Date.n
|
|
|
131
138
|
if (b.readCancel()) { out.push({ id, cancelled: true, running }); continue; }
|
|
132
139
|
const last = b.lastProgressMs();
|
|
133
140
|
const live = !b.readReport() && last !== null && now - last <= staleMs;
|
|
134
|
-
if (live && (running || (Array.isArray(st.pending) && st.pending.includes(issue)))) out.push({ id, cancelled: false, running });
|
|
141
|
+
if (live && (running || (Array.isArray(st.pending) && st.pending.includes(issue)) || b.readHeld().includes(issue))) out.push({ id, cancelled: false, running });
|
|
135
142
|
}
|
|
136
143
|
return out;
|
|
137
144
|
}
|
|
@@ -143,6 +150,14 @@ export const cancelledOwners = (root, repo, issue, exceptId = null, opts = {}) =
|
|
|
143
150
|
/** #5241: the id of an active (uncancelled) batch of `repo` already holding `issue`, else null. */
|
|
144
151
|
export const activeBatchOf = (root, repo, issue, opts = {}) => batchesOwning(root, repo, issue, opts).find((o) => !o.cancelled)?.id ?? null;
|
|
145
152
|
|
|
153
|
+
/** #5471: the id of another live batch of `repo` that has `issue` pending, running or held (`exceptId` = the asking batch), else null. */
|
|
154
|
+
export const ownerOf = (root, repo, issue, exceptId = null, opts = {}) => activeBatchOf(root, repo, issue, { ...opts, exceptId });
|
|
155
|
+
/** #5471: the batch that wins `issue` at dispatch: one running it, else one holding it pending/held with a lower id (so two batches never both defer). */
|
|
156
|
+
export const dispatchOwner = (root, repo, issue, exceptId, opts = {}) => {
|
|
157
|
+
const live = batchesOwning(root, repo, issue, { ...opts, exceptId }).filter((o) => !o.cancelled);
|
|
158
|
+
return (live.find((o) => o.running) ?? live.find((o) => o.id < exceptId))?.id ?? null;
|
|
159
|
+
};
|
|
160
|
+
|
|
146
161
|
/** Handle on one batch directory. */
|
|
147
162
|
export function openBatch(root, id) {
|
|
148
163
|
if (!ID_RE.test(String(id ?? ""))) throw new Error(`invalid batch id ${JSON.stringify(id)}`);
|
|
@@ -249,18 +264,40 @@ export function openBatch(root, id) {
|
|
|
249
264
|
readHeld: () => readAdded(f("hold")),
|
|
250
265
|
/** #4656: gates waiting on issues (`gates` file: [{ name, waitsOn: [n...], since? }], written by the ship/settle pre-flight); [] when missing or invalid. */
|
|
251
266
|
readGates: () => { const v = readJson(f("gates")); return Array.isArray(v) ? v.filter((g) => g && typeof g.name === "string" && Array.isArray(g.waitsOn)) : []; },
|
|
252
|
-
/**
|
|
253
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Merge the positive integers of `list` into the `hold` file. #5469: `meta` ({owner, ownerPid, ownerHost, forMs, reason}) is
|
|
269
|
+
* recorded per newly held issue in the `hold-info` file as {owner, since, expiresAt|null, reason, ownerPid, ownerHost}.
|
|
270
|
+
* @returns {number[]} the issues newly held
|
|
271
|
+
*/
|
|
272
|
+
holdIssues: (list, meta = null) => {
|
|
254
273
|
const have = new Set(readAdded(f("hold")));
|
|
255
274
|
const added = [...new Set(ints(list))].filter((n) => !have.has(n)).sort((a, b) => a - b);
|
|
256
275
|
if (added.length) put(f("hold"), JSON.stringify([...have, ...added].sort((a, b) => a - b)) + "\n");
|
|
276
|
+
if (added.length && meta) {
|
|
277
|
+
const now = Date.now(), info = readHoldInfo(f("hold-info"));
|
|
278
|
+
for (const n of added) info[n] = { owner: String(meta.owner ?? "operator"), since: new Date(now).toISOString(), expiresAt: Number(meta.forMs) > 0 ? new Date(now + Number(meta.forMs)).toISOString() : null, reason: meta.reason ? String(meta.reason) : null, ownerPid: Number.isSafeInteger(meta.ownerPid) ? meta.ownerPid : null, ownerHost: meta.ownerHost ?? null };
|
|
279
|
+
put(f("hold-info"), JSON.stringify(info) + "\n");
|
|
280
|
+
}
|
|
257
281
|
return added;
|
|
258
282
|
},
|
|
283
|
+
/** #5469: `{issue: {owner, since, expiresAt, reason, ownerPid, ownerHost}}` for held issues; {} when missing, invalid or a legacy hold. */
|
|
284
|
+
readHoldInfo: () => { const held = new Set(readAdded(f("hold"))), info = readHoldInfo(f("hold-info")); return Object.fromEntries(Object.entries(info).filter(([n]) => held.has(Number(n)))); },
|
|
285
|
+
/** #5469: release every hold whose `expiresAt` has passed. @returns {Array<{issue, owner, since, reason, ownerGone}>} (`ownerGone`: the owner's session pid is dead on this host) */
|
|
286
|
+
expireHolds: (now = Date.now()) => {
|
|
287
|
+
const info = readHoldInfo(f("hold-info")), held = new Set(readAdded(f("hold")));
|
|
288
|
+
const due = Object.entries(info).filter(([n, e]) => held.has(Number(n)) && e.expiresAt && Date.parse(e.expiresAt) <= now).map(([n, e]) => ({ issue: Number(n), ...e }));
|
|
289
|
+
if (!due.length) return [];
|
|
290
|
+
const out = due.map((e) => ({ issue: e.issue, owner: e.owner, since: e.since, reason: e.reason ?? null, ownerGone: ownerGone(e) }));
|
|
291
|
+
self.releaseIssues(due.map((e) => e.issue));
|
|
292
|
+
return out;
|
|
293
|
+
},
|
|
259
294
|
/** Remove `list` from the `hold` file. @returns {number[]} the issues that were held */
|
|
260
295
|
releaseIssues: (list) => {
|
|
261
296
|
const have = new Set(readAdded(f("hold")));
|
|
262
297
|
const freed = [...new Set(ints(list))].filter((n) => have.has(n)).sort((a, b) => a - b);
|
|
263
298
|
if (freed.length) put(f("hold"), JSON.stringify([...have].filter((n) => !freed.includes(n)).sort((a, b) => a - b)) + "\n");
|
|
299
|
+
const info = readHoldInfo(f("hold-info"));
|
|
300
|
+
if (freed.some((n) => info[n])) { for (const n of freed) delete info[n]; put(f("hold-info"), JSON.stringify(info) + "\n"); }
|
|
264
301
|
return freed;
|
|
265
302
|
},
|
|
266
303
|
/** `--cancel` (#4376): `{at, reason, stopRemote?}` in the `cancel` file; the runner re-reads it every pass. `stopRemote` (#4612) also asks remote lanes to stop at their checkpoint. */
|
package/bin/lean/batch.test.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { spawn } from "node:child_process";
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
9
|
import { resolveLane, makeLaneCache } from "./lane.mjs";
|
|
@@ -357,9 +357,9 @@ describe("#4318: the batch dispatcher's signal relabel and the needs-human relab
|
|
|
357
357
|
});
|
|
358
358
|
it("#4736: a mechanical park creates its parked:<code> label before the edit", async () => {
|
|
359
359
|
const calls = [];
|
|
360
|
-
const gh = async (a) => { calls.push(a.slice(0, 3).join(" ")); return a[1] === "view" ? JSON.stringify({ state: "OPEN", body: "" }) : ""; };
|
|
360
|
+
const gh = async (a) => { calls.push(a.slice(0, 3).join(" ")); return a[1] === "view" ? JSON.stringify({ state: "OPEN", body: "", labels: [{ name: "parked:ci.red" }, { name: "remediation-queue" }] }) : ""; };
|
|
361
361
|
assert.equal(await makeRelabelNeedsHuman({ gh, repo: "o/r", now: () => 1000 })({ issue: 7, evidence: "e", parked: { code: "ci.red", pr: 3 } }), true);
|
|
362
|
-
assert.deepEqual(calls.slice(0, 3), ["issue view 7", "label create parked:ci.red", "
|
|
362
|
+
assert.deepEqual(calls.slice(0, 3), ["issue view 7", "label create parked:ci.red", "label create remediation-queue"]);
|
|
363
363
|
});
|
|
364
364
|
});
|
|
365
365
|
|
|
@@ -376,6 +376,20 @@ describe("#4318: the batch dispatcher's signal relabel and the needs-human relab
|
|
|
376
376
|
} finally { console.log = l; }
|
|
377
377
|
assert.doesNotMatch(out.join("\n"), /remediation queue/);
|
|
378
378
|
});
|
|
379
|
+
it("#5466: a failed parked relabel is reported as a batch event", async () => {
|
|
380
|
+
const evs = [];
|
|
381
|
+
const leanIo = { gh: async (a) => (a.includes("milestone") ? JSON.stringify({ milestone: null }) : JSON.stringify({ body: "" })), git: async (a) => (a[0] === "ls-remote" ? "abc\trefs/heads/staging\n" : "") };
|
|
382
|
+
const l = console.log;
|
|
383
|
+
console.log = (...x) => evs.push(x.join(" "));
|
|
384
|
+
try {
|
|
385
|
+
await orchestrateFromCli(["1", "--parallel", "1", "--repo", "o/r", "--no-prefilter"], { dir: tmpDir("pf-"), batchRoot: tmpDir("pf-batch-"), allowTmpfs: true,
|
|
386
|
+
emitTelemetry: async () => {}, io: { gh: async () => "o/r\n" }, leanIo, sched: null, decide: () => {},
|
|
387
|
+
orchestration: { breaker: null, maxDeferrals: 3, globalParallel: null, recovery: { maxAttempts: 1 } },
|
|
388
|
+
relabelNeedsHuman: async (x) => (x.parked ? "failed" : true),
|
|
389
|
+
leanModule: { runCore: async () => ({ terminalReason: "needs-human", code: "ci.red", detail: "x", pr: 5 }) } });
|
|
390
|
+
} finally { console.log = l; }
|
|
391
|
+
assert.match(evs.join("\n"), /relabel\.failed|parked relabel failed/);
|
|
392
|
+
});
|
|
379
393
|
});
|
|
380
394
|
|
|
381
395
|
describe("#4354: the batch report ends with the fail-soft alerts of the batch's repo", () => {
|
|
@@ -1745,3 +1759,92 @@ describe("#5168: --requeue accepts engine-error; a claude login failure is held,
|
|
|
1745
1759
|
});
|
|
1746
1760
|
|
|
1747
1761
|
function readdirSyncSafe(d) { try { return readdirSync(d).filter((n) => !n.endsWith(".json")); } catch { return []; } }
|
|
1762
|
+
|
|
1763
|
+
describe("#5469: holds carry an owner and an expiry", () => {
|
|
1764
|
+
it("#5469: an expired hold is re-admitted", async () => {
|
|
1765
|
+
let saved = null, held = [2], free, expired = false;
|
|
1766
|
+
const gate = new Promise((r) => { free = r; });
|
|
1767
|
+
const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
|
|
1768
|
+
const started = [], log = [];
|
|
1769
|
+
const done = orchestrate({ issues: [1, 2], parallel: 2, pollMs: 5, readBody: async () => "", store, getHeld: () => held, onUpdate: (r) => log.push(r),
|
|
1770
|
+
expireHolds: () => { if (!expired) return []; expired = false; held = []; return [{ issue: 2, owner: "op@h", since: "2026-11-11T00:00:00.000Z", reason: "hand-build", ownerGone: true }]; },
|
|
1771
|
+
runOne: async (n) => { started.push(n); if (n === 1) await gate; return { terminalReason: "merged" }; } });
|
|
1772
|
+
await until(() => started.includes(1));
|
|
1773
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
1774
|
+
assert.deepEqual(started, [1], "held until it expires");
|
|
1775
|
+
expired = true;
|
|
1776
|
+
try { await until(() => started.includes(2), 3000); } finally { free(); } // a failure frees the gate so the run ends instead of hanging
|
|
1777
|
+
assert.deepEqual((await done).map((r) => [r.issue, r.outcome]), [[1, "merged"], [2, "merged"]]);
|
|
1778
|
+
assert.ok(log.some((r) => r.outcome === "hold-expired" && /#2 \(op@h/.test(r.detail)));
|
|
1779
|
+
assert.ok(log.some((r) => r.outcome === "hold-alert" && /owner session \(op@h\) is gone/.test(r.detail)), "a dead owner session raises an alert row");
|
|
1780
|
+
});
|
|
1781
|
+
|
|
1782
|
+
it("#5469: a finished batch with only a held issue waits for the expiry, re-admits it, and alerts when the owner is gone", async () => {
|
|
1783
|
+
let saved = null, held = [2], due = false;
|
|
1784
|
+
const store = { load: () => saved, save: (st) => { saved = st; }, log: () => {} };
|
|
1785
|
+
const started = [], log = [];
|
|
1786
|
+
const info = { 2: { owner: "op@h", since: "2026-11-11T00:00:00.000Z", expiresAt: "2026-11-11T04:00:00.000Z" } };
|
|
1787
|
+
const done = orchestrate({ issues: [1, 2], parallel: 2, pollMs: 5, readBody: async () => "", store, getHeld: () => held, getHoldInfo: () => (held.length ? info : {}), onUpdate: (r) => log.push(r),
|
|
1788
|
+
expireHolds: () => { if (!due) return []; due = false; held = []; return [{ issue: 2, owner: "op@h", since: info[2].since, reason: null, ownerGone: true }]; },
|
|
1789
|
+
runOne: async (n) => { started.push(n); return { terminalReason: "merged" }; } });
|
|
1790
|
+
try {
|
|
1791
|
+
await until(() => started.includes(1), 3000);
|
|
1792
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
1793
|
+
assert.deepEqual(started, [1], "the batch stays open while the hold has not expired");
|
|
1794
|
+
due = true;
|
|
1795
|
+
await until(() => started.includes(2), 3000);
|
|
1796
|
+
} finally { due = true; held = []; }
|
|
1797
|
+
assert.deepEqual((await done).map((r) => [r.issue, r.outcome]), [[1, "merged"], [2, "merged"]]);
|
|
1798
|
+
assert.ok(log.some((r) => r.outcome === "hold-alert"));
|
|
1799
|
+
});
|
|
1800
|
+
|
|
1801
|
+
it("a batch that ends with a held issue names its owner and since; a legacy hold keeps the plain detail", async () => {
|
|
1802
|
+
let saved = null;
|
|
1803
|
+
const store = { load: () => saved, save: (s) => { saved = s; }, log: () => {} };
|
|
1804
|
+
const run = (info) => orchestrate({ issues: [1, 2], parallel: 2, pollMs: 5, readBody: async () => "", store: { ...store, load: () => null }, getHeld: () => [2], getHoldInfo: () => info,
|
|
1805
|
+
runOne: async () => ({ terminalReason: "merged" }) });
|
|
1806
|
+
const rows = await run({ 2: { owner: "op@h", since: "2026-11-11T00:00:00.000Z" } });
|
|
1807
|
+
assert.equal(rows.find((r) => r.issue === 2).detail, "held by operator (op@h, since 2026-11-11T00:00:00.000Z)");
|
|
1808
|
+
assert.equal((await run({})).find((r) => r.issue === 2).detail, "held by operator");
|
|
1809
|
+
});
|
|
1810
|
+
|
|
1811
|
+
it("the batch API: hold metadata, expireHolds releases only the due ones, release drops the metadata", () => {
|
|
1812
|
+
const b = openBatch(tmpDir("batch-hold5469-"), "b1");
|
|
1813
|
+
b.writePlan({ argv: ["1"], repo: "o/r" });
|
|
1814
|
+
b.holdIssues([2, 3], { owner: "op@h", forMs: 3600000, reason: "hand-build", ownerPid: 2147483646, ownerHost: null });
|
|
1815
|
+
b.holdIssues([4]);
|
|
1816
|
+
const info = b.readHoldInfo();
|
|
1817
|
+
assert.deepEqual(Object.keys(info), ["2", "3"]);
|
|
1818
|
+
assert.equal(info[2].reason, "hand-build");
|
|
1819
|
+
assert.deepEqual(b.expireHolds(Date.now()), []);
|
|
1820
|
+
const due = b.expireHolds(Date.now() + 2 * 3600000);
|
|
1821
|
+
assert.deepEqual(due.map((d) => [d.issue, d.owner, d.ownerGone]), [[2, "op@h", true], [3, "op@h", true]], "a pid that does not exist is a gone owner");
|
|
1822
|
+
assert.deepEqual(b.readHeld(), [4], "a legacy hold has no expiry");
|
|
1823
|
+
b.holdIssues([5], { owner: "x", forMs: 0 });
|
|
1824
|
+
b.releaseIssues([5]);
|
|
1825
|
+
assert.deepEqual(b.readHoldInfo(), {});
|
|
1826
|
+
});
|
|
1827
|
+
|
|
1828
|
+
it("through the CLI: --hold --for --reason records owner and expiry; a malformed --for rejects", async () => {
|
|
1829
|
+
const root = tmpDir("batch-hold5469-cli-");
|
|
1830
|
+
const b = openBatch(root, "b1");
|
|
1831
|
+
b.writePlan({ argv: [], repo: "o/r" });
|
|
1832
|
+
b.store.save({ order: [1, 2] });
|
|
1833
|
+
const io = { gh: async () => JSON.stringify({ state: "OPEN" }) };
|
|
1834
|
+
const res = await quiet(() => orchestrateFromCli(["--hold", "b1", "1", "--for", "4h", "--reason", "hand build"], { batchRoot: root, io }));
|
|
1835
|
+
assert.deepEqual(res.changed, [1]);
|
|
1836
|
+
const e = b.readHoldInfo()[1];
|
|
1837
|
+
assert.equal(e.reason, "hand build");
|
|
1838
|
+
assert.ok(Date.parse(e.expiresAt) - Date.parse(e.since) === 4 * 3600000);
|
|
1839
|
+
await assert.rejects(orchestrateFromCli(["--hold", "b1", "2", "--for", "soon"], { batchRoot: root, io }), /--for expects/);
|
|
1840
|
+
});
|
|
1841
|
+
|
|
1842
|
+
it("--gc-orphans cancels unhosted batches idle past the threshold and leaves recent ones", async () => {
|
|
1843
|
+
const root = tmpDir("batch-gc5469-");
|
|
1844
|
+
const mk = (id, ageMs) => { const b = openBatch(root, id); b.writePlan({ argv: [], repo: "o/r" }); b.store.save({ order: [1], pending: [1], results: {} }); const t = new Date(Date.now() - ageMs); utimesSync(join(b.dir, "state.json"), t, t); return b; };
|
|
1845
|
+
const old = mk("old", 9 * 86400000), fresh = mk("fresh", 60000);
|
|
1846
|
+
const res = await quiet(() => orchestrateFromCli(["--gc-orphans"], { batchRoot: root, io: { gh: async () => "" } }));
|
|
1847
|
+
assert.deepEqual(res.cancelled, ["old"]);
|
|
1848
|
+
assert.ok(old.readCancel()); assert.equal(fresh.readCancel(), null);
|
|
1849
|
+
});
|
|
1850
|
+
});
|