forgedock 1.65.0 → 1.66.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.
@@ -1396,7 +1396,7 @@ async function envBatch({ argv, root, print = (l) => console.log(l) }) {
1396
1396
  return { ok: true, batch: id };
1397
1397
  }
1398
1398
 
1399
- const ORCH_USAGE = "usage: forgedock orchestrate <issue...> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
1399
+ const ORCH_USAGE = "usage: forgedock orchestrate <issue...> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> --all [--for 2h] [--reason T] (sugar for --pause) | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --pause <id> [--for <4h|30m|1d>] --reason <text> | --unpause <id> | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
1400
1400
  const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for"];
1401
1401
  const issuesOf = (argv) => {
1402
1402
  const issues = [];
@@ -1534,6 +1534,12 @@ function holdMeta(argv) {
1534
1534
  return { owner: process.env.FORGE_HOLD_OWNER || `${process.env.USER || process.env.USERNAME || "operator"}@${hostname()}`, ownerPid: process.ppid, ownerHost: hostname(), forMs: parseHoldFor(forLabel), forLabel, reason: reason && !reason.startsWith("--") ? reason : null };
1535
1535
  }
1536
1536
 
1537
+ /** #5975: `--hold --all` pauses the batch without a `--reason`: the reason defaults to the flag that asked. */
1538
+ function holdMetaAll(argv) {
1539
+ const m = holdMeta(argv);
1540
+ return argv.includes("--hold") && !m.reason ? { ...m, reason: "--hold --all" } : m;
1541
+ }
1542
+
1537
1543
  /** #5469: `--gc-orphans`: cancel every orphaned batch (unhosted, pending issues, idle for a week) through the daemon or the batch files. */
1538
1544
  async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l) }) {
1539
1545
  let res = viaDaemon ? await viaDaemon() : null;
@@ -1547,6 +1553,25 @@ async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l)
1547
1553
  return { ok: true, cancelled: res.cancelled ?? [] };
1548
1554
  }
1549
1555
 
1556
+ /**
1557
+ * `--pause <id> [--for 2h] --reason T` / `--unpause <id>` (#5975): the batch's `pause` file, through the daemon (`viaDaemon(op, meta)`,
1558
+ * null when none runs) or directly. Admission stops for every issue, later re-admissions, requeues and adds included; running lanes
1559
+ * are untouched. @returns {{ok, batch, pause}}
1560
+ */
1561
+ async function pauseBatch({ op, id, root, viaDaemon = null, meta = null, print = (l) => console.log(l) }) {
1562
+ if (!id || String(id).startsWith("--")) throw new Error(ORCH_USAGE);
1563
+ if (op === "pause" && !meta?.reason) throw new Error("--pause needs --reason <text>");
1564
+ let res = viaDaemon ? await viaDaemon(op, meta) : null;
1565
+ if (!res) {
1566
+ const b = (await import("./lean/batch.mjs")).openBatch(root, id);
1567
+ if (!b.exists()) throw new Error(`no batch ${id} in ${root}`);
1568
+ res = op === "pause" ? { pause: b.setPause(meta) } : { changed: b.clearPause() };
1569
+ }
1570
+ print(op === "pause" ? `batch ${id}: paused (${meta.reason}, until ${res.pause?.expiresAt ?? "unpause"}); running lanes continue; forgedock orchestrate --unpause ${id} re-admits`
1571
+ : res.changed === false ? `batch ${id}: not paused` : `batch ${id}: unpaused`);
1572
+ return { ok: true, batch: id, pause: res.pause ?? null };
1573
+ }
1574
+
1550
1575
  /**
1551
1576
  * `--hold <id> N...` / `--release <id> N...` (#4592): the batch's `hold` file, through the daemon (`viaDaemon(op, issues)`, null
1552
1577
  * when none runs) or directly. A held issue is not admitted (a running lane is not stopped); `--release` (or a `--resume` that
@@ -1692,6 +1717,11 @@ async function orchestrateClient(argv, deps = {}) {
1692
1717
  try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
1693
1718
  return sock ? schedd.request(sock, { op, id, issues, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
1694
1719
  };
1720
+ const viaPause = async (id, op, meta) => {
1721
+ let sock = null;
1722
+ try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
1723
+ return sock ? schedd.request(sock, { op, id, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
1724
+ };
1695
1725
  const batchRootOf = async () => (await import("./lean/batch.mjs")).batchRoot();
1696
1726
  if (["--show-env", "--set-env", "--unset-env"].some((f) => argv.includes(f))) return envBatch({ argv, root: await batchRootOf() });
1697
1727
  if (argv.includes("--clear-breaker")) return runBatch({ argv, deps, sink: consoleSink() });
@@ -1712,6 +1742,10 @@ async function orchestrateClient(argv, deps = {}) {
1712
1742
  try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
1713
1743
  return sock ? schedd.request(sock, { op: "gc-orphans" }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
1714
1744
  } });
1745
+ for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
1746
+ const id = flag(argv, flagName), pv = (_o, meta) => viaPause(id, op, meta);
1747
+ return pauseBatch({ op, id, root: await batchRootOf(), viaDaemon: pv, meta: op === "pause" ? holdMetaAll(argv) : null });
1748
+ }
1715
1749
  for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
1716
1750
  const id = flag(argv, `--${op}`);
1717
1751
  const root = await batchRootOf(), io = deps.io ?? makeIo();
@@ -1836,6 +1870,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
1836
1870
  return requeueBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root, io: deps.io ?? makeIo(), requireHost: true, force: forceOf(argv), print: (l) => sink.line(l) });
1837
1871
  }
1838
1872
  if (argv.includes("--gc-orphans")) return gcOrphans({ root, print: (l) => sink.line(l) });
1873
+ for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
1874
+ return pauseBatch({ op, id: flag(argv, flagName), root, meta: op === "pause" ? holdMetaAll(argv) : null, print: (l) => sink.line(l) });
1875
+ }
1839
1876
  for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
1840
1877
  const hid = flag(argv, `--${op}`);
1841
1878
  return holdBatch({ op, id: hid, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, meta: op === "hold" ? holdMeta(argv) : null, print: (l) => sink.line(l),
@@ -2309,7 +2346,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
2309
2346
  trusted: (n) => trustedOf.get(n) === true,
2310
2347
  autoChildren,
2311
2348
  ...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
2312
- issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2349
+ issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getPause: batch.readPause, expirePause: batch.expirePause, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
2313
2350
  breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
2314
2351
  ...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
2315
2352
  // #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
@@ -2700,13 +2737,14 @@ export async function scheddFromCli(argv, deps = {}) {
2700
2737
  const bm = await import("./lean/batch.mjs");
2701
2738
  const unfinished = () => { const root = bm.batchRoot(); return bm.listBatches(root).filter((id) => { try { const b = bm.openBatch(root, id); const br = b.store.peek()?.breaker; return !!b.readPlan()?.daemon && !b.isTerminal() && b.pendingIssues().length > 0 && !(br && !br.transport); } catch { return false; } }); };
2702
2739
  const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
2740
+ const unit = deps.unitState ?? schedd.unitState; // #5966: active unit but no daemon is alerted and the unit restarted
2703
2741
  const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
2704
- return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts });
2742
+ return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts, unit });
2705
2743
  }
2706
2744
  if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
2707
2745
  (deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
2708
2746
  process.title = "forgedock-schedd"; // distinctive name for OOM-killer avoid lists and ps (#4673)
2709
- const d = await schedd.startDaemon({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
2747
+ const d = await schedd.startDaemon({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), exit: deps.exit ?? ((c) => process.exit(c)), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
2710
2748
  ...(deps.daemonPreflight !== undefined ? { preflight: deps.daemonPreflight } : deps.batchDeps ? {} : { preflight: async () => { const lc = await import("./lean/lanecheck.mjs"); return (await lc.runLaneChecks({ exec: readExecution(process.cwd()), io: await lc.hostLaneIo() })).filter((c) => !c.ok); } }) });
2711
2749
  if (!d.running) {
2712
2750
  // #4775: under systemd, exiting here (code 0) makes `Restart=always` loop while another daemon holds the lock: stand by, take over when it dies
@@ -2718,7 +2756,14 @@ export async function scheddFromCli(argv, deps = {}) {
2718
2756
  // #4454: a signal stops the hosted batch loops, then releases the lock and socket, then exits 128+signo
2719
2757
  schedd.exitOnSignals(d, { ...(deps.processOn ? { on: deps.processOn } : {}), ...(deps.exit ? { exit: deps.exit } : {}) });
2720
2758
  await d.closed;
2721
- return { running: false };
2759
+ await d.settled?.(); // #5984: a self-stop keeps spawning/probing the successor after `closed`; exiting now would leave no daemon
2760
+ // #5966 R1: a handover whose successor never listened re-hosted the batches in a new daemon; follow it to its end
2761
+ let cur = d;
2762
+ while (cur.rehosted?.()) { cur = cur.rehosted(); await cur.closed; await cur.settled?.(); }
2763
+ // #5966: a self-initiated stop (handover, stall recovery, lost socket) exits non-zero so systemd restarts the unit instead of leaving a zombie
2764
+ const code = cur.stopCode?.();
2765
+ if (code) (deps.exit ?? ((c) => process.exit(c)))(code);
2766
+ return { running: false, ...(code ? { exitCode: code } : {}) };
2722
2767
  }
2723
2768
 
2724
2769
  /**
@@ -325,8 +325,9 @@ export function runningSplit(state, parallel = null) {
325
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
326
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.
327
327
  */
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 } = {}) {
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, paused = null } = {}) {
329
329
  if (!state || cancelled || reported || lastProgressMs === null) return null;
330
+ if (paused) return null; // #5975: an operator pause is an intended wait, not a dispatch stall
330
331
  if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
331
332
  const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
332
333
  const running = Object.keys(state.running ?? {}).length;
@@ -373,15 +374,18 @@ export function recordStallRecovery(batch, stall, { action, sig = stall.ready.jo
373
374
  return text;
374
375
  }
375
376
 
377
+ /** #5975: `paused (reason, until …)`, the text every surface shows for a batch pause. */
378
+ export const pausedText = (p) => `paused (${p?.reason ?? "no reason given"}, until ${p?.expiresAt ?? "unpause"})`;
379
+
376
380
  /** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
377
- export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null } = {}) {
381
+ export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null, paused = null } = {}) {
378
382
  const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
379
383
  const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
380
384
  const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
381
385
  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`;
382
386
  const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
383
387
  const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
384
- const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
388
+ const reasons = [...(paused ? [pausedText(paused)] : []), ...stuck.map(why), ...(stall ? [stall.detail] : [])];
385
389
  const summary = `first hour: ${dispatched}/${order.length} dispatched, ${running.length} running, ${merged.length} merged, ${stuck.length} stuck${reasons.length ? ` (${reasons.slice(0, 6).join("; ")})` : ""}`;
386
390
  return { batch: batchId, at: new Date(now).toISOString(), counts, summary, lines: [`batch ${batchId}: ${summary}`, ...reasons.slice(0, 12).map((r) => ` ${r}`)] };
387
391
  }
@@ -429,7 +433,7 @@ export function batchVerdict(id, stall, decision = null, { acted = false } = {})
429
433
 
430
434
  /** #5938: whether the batch still has ready issues with a free lane (the idle window was already met when the stall was stored). */
431
435
  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; }
436
+ try { const state = b.store.peek(); if (!state) return true; return evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: true, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs() ?? now, now, windowMin: 0 }) !== null; } catch { return true; }
433
437
  };
434
438
 
435
439
  /** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
@@ -439,7 +443,8 @@ export function summaryLines(root, { now = Date.now() } = {}) {
439
443
  try {
440
444
  const b = openBatch(root, id);
441
445
  if (b.readReport() || b.readCancel()) continue;
442
- const fh = readFirstHour(b.dir), h = readHealth(b.dir);
446
+ const fh = readFirstHour(b.dir), h = readHealth(b.dir), pz = b.readPause?.() ?? null;
447
+ if (pz) out.push(` batch ${id}: ${pausedText(pz)}`);
443
448
  if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
444
449
  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})` : ""}`);
445
450
  } catch { /* an unreadable batch has no line */ }
@@ -331,6 +331,23 @@ export function openBatch(root, id) {
331
331
  self.releaseIssues(due.map((e) => e.issue));
332
332
  return out;
333
333
  },
334
+ /** #5975: batch-level pause (`pause` file): `{owner, since, expiresAt|null, reason, ownerPid, ownerHost}`; admission stops for every issue, present and future. */
335
+ setPause: ({ owner = "operator", reason = null, forMs = null, ownerPid = null, ownerHost = null } = {}) => {
336
+ const now = Date.now(), rec = { owner: String(owner), since: new Date(now).toISOString(), expiresAt: Number(forMs) > 0 ? new Date(now + Number(forMs)).toISOString() : null, reason: reason ? String(reason) : null, ownerPid: Number.isSafeInteger(ownerPid) ? ownerPid : null, ownerHost: ownerHost ?? null };
337
+ put(f("pause"), JSON.stringify(rec) + "\n");
338
+ return rec;
339
+ },
340
+ /** #5975: the pause record, or null when missing or invalid. */
341
+ readPause: () => { const v = readJson(f("pause")); return v && typeof v === "object" && !Array.isArray(v) && typeof v.since === "string" ? v : null; },
342
+ /** #5975: lift the pause. @returns {boolean} whether one was set */
343
+ clearPause: () => { const had = !!self.readPause(); try { rmSync(f("pause"), { force: true }); } catch { /* already gone */ } return had; },
344
+ /** #5975: lift the pause when its `expiresAt` has passed. @returns {object|null} the expired record (with `ownerGone`) */
345
+ expirePause: (now = Date.now()) => {
346
+ const p = self.readPause();
347
+ if (!p?.expiresAt || !(Date.parse(p.expiresAt) <= now)) return null;
348
+ self.clearPause();
349
+ return { ...p, ownerGone: ownerGone(p) };
350
+ },
334
351
  /** Remove `list` from the `hold` file. @returns {number[]} the issues that were held */
335
352
  releaseIssues: (list) => {
336
353
  const have = new Set(readAdded(f("hold")));
@@ -2080,3 +2080,68 @@ describe("#5669: an upgrade handover adopts live lanes instead of requeueing the
2080
2080
  assert.deepEqual(rows.map((r) => [r.issue, r.outcome]), [[4, "merged"]]);
2081
2081
  });
2082
2082
  });
2083
+
2084
+ describe("#5975: batch pause", () => {
2085
+ it("pause file: set, read, clear, expiry and invalid content", () => {
2086
+ const b = openBatch(tmpDir("batch-pause5975-"), "b1");
2087
+ b.writePlan({ argv: [], repo: "o/r" });
2088
+ assert.equal(b.readPause(), null);
2089
+ const rec = b.setPause({ owner: "op@h", reason: "release cut", forMs: 7200000 });
2090
+ assert.equal(rec.reason, "release cut");
2091
+ assert.equal(Date.parse(b.readPause().expiresAt) - Date.parse(b.readPause().since), 7200000);
2092
+ assert.equal(b.expirePause(Date.now()), null, "not due yet");
2093
+ const gone = b.expirePause(Date.now() + 7300000);
2094
+ assert.equal(gone.owner, "op@h");
2095
+ assert.equal(b.readPause(), null, "expiry lifts it");
2096
+ b.setPause({ owner: "op@h", reason: "x" });
2097
+ assert.equal(b.expirePause(Date.now() + 1e12), null, "no expiry never expires");
2098
+ assert.equal(b.clearPause(), true);
2099
+ assert.equal(b.clearPause(), false);
2100
+ writeFileSync(join(b.dir, "pause"), "not json");
2101
+ assert.equal(b.readPause(), null);
2102
+ writeFileSync(join(b.dir, "pause"), "[1]");
2103
+ assert.equal(b.readPause(), null);
2104
+ });
2105
+
2106
+ it("through the CLI: --pause needs --reason, records the expiry, --unpause lifts it; sched show lists it", async () => {
2107
+ const root = tmpDir("batch-pause5975-cli-");
2108
+ const b = openBatch(root, "b1");
2109
+ b.writePlan({ argv: [], repo: "o/r" });
2110
+ b.store.save({ order: [1, 2], pending: [1, 2] });
2111
+ const io = { gh: async () => JSON.stringify({ state: "OPEN" }) };
2112
+ await assert.rejects(orchestrateFromCli(["--pause", "b1"], { batchRoot: root, io }), /--reason/);
2113
+ await assert.rejects(orchestrateFromCli(["--pause", "b1", "--reason", "x", "--for", "soon"], { batchRoot: root, io }), /--for expects/);
2114
+ await assert.rejects(orchestrateFromCli(["--pause", "nope", "--reason", "x"], { batchRoot: root, io }), /no batch nope/);
2115
+ const res = await quiet(() => orchestrateFromCli(["--pause", "b1", "--for", "2h", "--reason", "release cut"], { batchRoot: root, io }));
2116
+ assert.equal(res.pause.reason, "release cut");
2117
+ assert.ok(Date.parse(b.readPause().expiresAt) - Date.parse(b.readPause().since) === 2 * 3600000);
2118
+ const { summaryLines } = await import("./batch-health.mjs");
2119
+ assert.ok(summaryLines(root).some((l) => /batch b1: paused \(release cut, until \d{4}-/.test(l)));
2120
+ await quiet(() => orchestrateFromCli(["--unpause", "b1"], { batchRoot: root, io }));
2121
+ assert.equal(b.readPause(), null);
2122
+ assert.ok(!summaryLines(root).some((l) => /paused/.test(l)));
2123
+ });
2124
+
2125
+ it("--hold <id> --all is sugar for --pause; --hold <id> N still holds one issue (#5975)", async () => {
2126
+ const root = tmpDir("batch-pause5975-all-");
2127
+ const b = openBatch(root, "b1");
2128
+ b.writePlan({ argv: [], repo: "o/r" });
2129
+ b.store.save({ order: [1, 2], pending: [1, 2] });
2130
+ const io = { gh: async () => JSON.stringify({ state: "OPEN" }) };
2131
+ await quiet(() => orchestrateFromCli(["--hold", "b1", "1"], { batchRoot: root, io }));
2132
+ assert.equal(b.readPause(), null, "a per-issue hold does not pause the batch");
2133
+ await quiet(() => orchestrateFromCli(["--hold", "b1", "--all", "--for", "2h"], { batchRoot: root, io }));
2134
+ assert.equal(b.readPause().reason, "--hold --all");
2135
+ assert.ok(Date.parse(b.readPause().expiresAt) > Date.parse(b.readPause().since));
2136
+ await quiet(() => orchestrateFromCli(["--unpause", "b1"], { batchRoot: root, io }));
2137
+ assert.equal(b.readPause(), null);
2138
+ });
2139
+
2140
+ it("a paused batch is not a dispatch stall", async () => {
2141
+ const { evaluateDispatchStall } = await import("./batch-health.mjs");
2142
+ const state = { order: [1], pending: [1], results: {}, running: {}, parallel: 1 };
2143
+ const opts = { hosted: true, lastProgressMs: 0, now: 3600000 * 5, windowMin: 10 };
2144
+ assert.ok(evaluateDispatchStall(state, opts), "unpaused: a stall");
2145
+ assert.equal(evaluateDispatchStall(state, { ...opts, paused: { reason: "x" } }), null);
2146
+ });
2147
+ });
@@ -26,6 +26,15 @@ import { join, dirname, basename, relative, resolve, isAbsolute } from "node:pat
26
26
  import { safeSegment } from "./ledger.mjs";
27
27
 
28
28
  export const depcacheRoot = (env = process.env) => String(env.FORGE_DEPCACHE_ROOT ?? "").trim() || join(homedir(), ".forge", "depcache");
29
+ /**
30
+ * #5901: the per-repo directory under the cache root. A pool lane's checkout is `/cache/work/<sandbox-id>`, so a key made
31
+ * from the checkout path is new for every lane and every lane installs its own copy. The repo slug (`owner/repo`) is the
32
+ * same for all of them; `fallback` (the path-based key) is used only when no repo is known.
33
+ */
34
+ export const depcacheNamespace = ({ repo, fallback } = {}) => {
35
+ const slug = String(repo ?? "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "_").replace(/^[._]+|[._]+$/g, "");
36
+ return slug || fallback;
37
+ };
29
38
  export const DEPCACHE_INSTALL_TIMEOUT_MS = 15 * 60000;
30
39
  export const DEPCACHE_MAX_AGE_MS = 7 * 24 * 3600 * 1000;
31
40
  const STORES = "stores";
package/bin/lean/lean.mjs CHANGED
@@ -41,6 +41,7 @@ import { ceilingFor, modelInfo, restartDecision, DEFAULT_CEILING, WINDOW_SHARE,
41
41
  import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
42
42
  import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
43
43
  import { repoKey, estimateCostUsd } from "../runner.mjs";
44
+ import { depcacheNamespace } from "./depcache.mjs";
44
45
  import { prepareToolchain } from "./toolchain.mjs";
45
46
  import { toolStats } from "./toolstats.mjs";
46
47
  import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
@@ -1819,7 +1820,7 @@ export async function runCore(o) {
1819
1820
  if (io.deps?.prepare) {
1820
1821
  const tD = now();
1821
1822
  let res;
1822
- try { res = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); } catch (e) { res = [{ status: "failed", eco: null, key: null, ms: 0, reason: String(e?.message ?? e).slice(0, 300) }]; }
1823
+ try { res = await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); } catch (e) { res = [{ status: "failed", eco: null, key: null, ms: 0, reason: String(e?.message ?? e).slice(0, 300) }]; }
1823
1824
  depResults = Array.isArray(res) ? res : []; // #5447: classified against the changed files at the gate
1824
1825
  setupStep("deps", tD);
1825
1826
  for (const r of Array.isArray(res) ? res : []) {
@@ -2642,10 +2643,10 @@ export async function runCore(o) {
2642
2643
  const projDeps = declaredEnv(frozen).filter((t) => deps5683.owner(t) !== null); // #5683: a sub-project's declared dependency is prepared and resolved through its bin dirs, never a host tool
2643
2644
  const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { if (deps5683.owner(t) !== null) continue; const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: projEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
2644
2645
  let envMiss = await probeEnv();
2645
- if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
2646
+ if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
2646
2647
  if (envMiss.length) {
2647
2648
  try {
2648
- if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
2649
+ if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined });
2649
2650
  if (envMiss.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
2650
2651
  envMiss = await probeEnv();
2651
2652
  ev({ event: "TESTPLAN_ENV_PROVISIONED", remaining: envMiss });
@@ -2671,10 +2672,10 @@ export async function runCore(o) {
2671
2672
  const remoteDeps = await depOwnerOf(); // #5683: a tool that is a tracked manifest dependency is prepared in the sandbox, never a lane_tools recipe or a host tool
2672
2673
  const ownedDep = (t) => t === "forgedock" || remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
2673
2674
  let tm0 = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => [])), tm = notOwned(tm0);
2674
- if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
2675
+ if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
2675
2676
  if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
2676
2677
  try {
2677
- if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
2678
+ if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined });
2678
2679
  if (tm.tools.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
2679
2680
  tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
2680
2681
  ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
@@ -3602,7 +3603,7 @@ export async function runCore(o) {
3602
3603
  if (unrun.length && !gateProvisioned && (io.deps?.prepare || (wantsPytest && io.runCommand))) {
3603
3604
  gateProvisioned = true;
3604
3605
  try {
3605
- if (io.deps?.prepare) { const rp = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : []; }
3606
+ if (io.deps?.prepare) { const rp = await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : []; }
3606
3607
  if (wantsPytest && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
3607
3608
  } catch { /* the rerun below reports what is still missing */ }
3608
3609
  ev({ event: "GATE_PROVISIONED", kinds: [...new Set(unrun.map((f) => f.kind))] });
@@ -6715,7 +6715,7 @@ describe("shared dependency cache wiring (#4220)", () => {
6715
6715
  assert.equal((await run(w, { dir })).terminalReason, "merged");
6716
6716
  assert.equal(d.calls.length, 1);
6717
6717
  assert.equal(d.calls[0].wt, "/wt/lean-7");
6718
- assert.match(d.calls[0].repoKey, /^[A-Za-z0-9._-]+-[0-9a-f]{8}$/);
6718
+ assert.equal(d.calls[0].repoKey, "o_r"); // #5901: the repo slug, not the checkout path
6719
6719
  assert.equal(d.calls[0].worktreeAdded, true);
6720
6720
  const ev = readLog(dir, 7).filter((e) => e.event === "DEPS_PREPARED");
6721
6721
  assert.deepEqual(ev.map((e) => [e.status, e.eco, e.key]), [["hit", "pnpm", "0123456789abcdef"]]);
@@ -275,6 +275,23 @@ describe("#5859 agent restart: correlated sandbox loss is sandbox.lost, not engi
275
275
  assert.ok(probes >= 3, "admission waited for the agent's healthy probe");
276
276
  });
277
277
 
278
+ // #5967 R5/R8: a host-memory OOM restart of the agent VM ends N sandboxes together; the VM-restart class is sandbox.lost (not a second pool.vm_restart code).
279
+ it("N sandboxes ending together on an agent VM restart are sandbox.lost deferrals, no breaker trip (#5967)", async () => {
280
+ const issues = [1, 2, 3, 4, 5];
281
+ const script = Object.fromEntries(issues.map((n) => [n, [LOST(n), MERGED]]));
282
+ const store = memStore();
283
+ let probes = 0;
284
+ const r = await harness({ script, issues, parallel: 5, store, envHold: undefined,
285
+ extra: { envHold: null, breaker: BREAKER, remote: { agentHealthy: async () => ++probes > 1 } } });
286
+ assert.ok(!r.updates.some((u) => u.outcome === "breaker"));
287
+ assert.deepEqual([...new Set(r.updates.filter((u) => u.code === "sandbox.lost").map((u) => u.issue))].sort((x, y) => x - y), issues);
288
+ assert.ok(!r.updates.some((u) => u.code === "engine-error"));
289
+ const st = store.load();
290
+ assert.deepEqual(st.errorTimes, []);
291
+ assert.equal(st.breaker, null);
292
+ for (const n of issues) assert.equal(r.byIssue[n].outcome, "merged");
293
+ });
294
+
278
295
  it("agent restart: failure after healthy is an ordinary engine-error", async () => {
279
296
  const store = memStore();
280
297
  const r = await harness({ script: { 1: [LOST(1), LOST(1), MERGED], 2: [LOST(2), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #5975: a batch-level pause stops admission for every issue (dependency merge, engine/env re-admit, expiry), never a running lane.
4
+ import { describe, it } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { orchestrate } from "./orchestrate.mjs";
7
+
8
+ const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {} }; };
9
+ const EE = (detail) => ({ terminalReason: "engine-error", detail });
10
+ const MERGED = { terminalReason: "merged", pr: 9 };
11
+ const REC = { owner: "op@h", since: "2026-01-01T00:00:00.000Z", expiresAt: null, reason: "release cut", ownerPid: null, ownerHost: null };
12
+
13
+ // A fake clock: every sleep advances it, so polls and expiry run instantly.
14
+ const run = ({ script, issues, store = memStore(), pause = { v: null }, extra = {}, onStart = () => {}, onRow = () => {}, clock = { t: 1_000_000 } }) => {
15
+ const calls = [], updates = [], decisions = [];
16
+ const p = orchestrate({ issues, parallel: 1, pollMs: 1000, readBody: async (n) => (n === 2 ? "Blocked by #1" : ""), trusted: () => true, now: () => clock.t, store,
17
+ sleep: async (ms) => { clock.t += Math.max(1, Number(ms) || 0); },
18
+ getPause: () => pause.v, recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 },
19
+ runOne: async (n) => { calls.push(n); clock.t += 1000; onStart(n); const l = script[n] ?? [MERGED]; return l[Math.min(calls.filter((c) => c === n).length - 1, l.length - 1)]; },
20
+ decide: (d) => decisions.push(d), onUpdate: (r) => { updates.push(r); onRow(r); }, ...extra });
21
+ return p.then((rows) => ({ rows, calls, updates, decisions, byIssue: Object.fromEntries(rows.map((r) => [r.issue, r])) }));
22
+ };
23
+
24
+ describe("#5975: batch pause", () => {
25
+ it("paused batch: a dependency merge does not dispatch the re-admitted dependent; after --unpause it does; the running lane completes", async () => {
26
+ const store = memStore(), pause = { v: null };
27
+ const a = await run({ script: {}, issues: [2, 1], store, pause, onStart: (n) => { if (n === 1) pause.v = REC; } });
28
+ assert.deepEqual(a.calls, [1], "the lane already running finishes through the pause; its dependent is not admitted");
29
+ assert.equal(a.byIssue[1].outcome, "merged");
30
+ assert.equal(a.byIssue[2].outcome, "held");
31
+ assert.match(a.byIssue[2].detail, /paused \(release cut, until unpause\)/);
32
+ assert.ok(a.updates.some((r) => r.outcome === "pause"), "a pause row");
33
+ pause.v = null; // --unpause, then --resume
34
+ const b = await run({ script: {}, issues: [2, 1], store, pause });
35
+ assert.deepEqual(b.calls, [2]);
36
+ assert.equal(b.byIssue[2].outcome, "merged");
37
+ });
38
+
39
+ it("an engine upgrade re-admit of a held (engine/env) issue in a paused batch stays pending", async () => {
40
+ let v = "1.0.0"; const pause = { v: null };
41
+ const r = await run({ script: { 1: [EE("boom"), EE("boom"), MERGED] }, issues: [1], pause,
42
+ extra: { envHold: { maxMs: 120_000, watchMs: 30_000, version: () => v } },
43
+ onRow: (row) => { if (row.issue === 1 && row.outcome === "held") { v = "1.0.1"; pause.v = REC; } } });
44
+ assert.deepEqual(r.calls, [1, 1], "the upgrade would re-admit it, the pause keeps it pending");
45
+ assert.equal(r.byIssue[1].outcome, "held");
46
+ });
47
+
48
+ it("a timed pause expires on its own (injected clock) and admission resumes", async () => {
49
+ const pause = { v: { ...REC, expiresAt: new Date(1_000_000 + 600_000).toISOString() } };
50
+ const clock = { t: 1_000_000 };
51
+ const r = await run({ script: {}, issues: [2, 1], pause, clock, extra: { expirePause: () => { const p = pause.v; if (p && Date.parse(p.expiresAt) <= clock.t) { pause.v = null; return { ...p, ownerGone: false }; } return null; } } });
52
+ assert.deepEqual(r.calls, [1, 2]);
53
+ assert.ok(r.updates.some((x) => x.outcome === "pause-expired"));
54
+ assert.ok(r.decisions.some((d) => /pause expired/.test(d.what)));
55
+ });
56
+
57
+ it("without getPause (or with no pause set) admission is unchanged", async () => {
58
+ const r = await run({ script: {}, issues: [2, 1], extra: { getPause: null } });
59
+ assert.deepEqual(r.calls, [1, 2]);
60
+ });
61
+ });
@@ -338,7 +338,7 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
338
338
  export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
339
339
  store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, consumeClearBreaker = null, ackClearBreaker = null,
340
340
  classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
341
- recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
341
+ recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getPause = null, expirePause = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
342
342
  estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
343
343
  getChildren = null, autoChildren = null, baseWait = null, rotator = null, stacking = "off", readPrReady = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null,
344
344
  train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS }) {
@@ -407,6 +407,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
407
407
  let pfAll = false, pfRemote = false, pfNoted = new Set(); // #4866: lane preflight holds
408
408
  let opHeld = new Set(); // #4592: operator-held issues this pass (the batch `hold` file is the authority)
409
409
  const opHeldHit = new Set(); // held issues that were pending this pass
410
+ let opPause = null, pauseHit = false; // #5975: the batch-level pause (the `pause` file is the authority); pauseHit: an issue was pending behind it this pass
410
411
  // #4376: operator cancel (the batch `cancel` file through `getCancelled`); persisted, but the file stays the authority.
411
412
  let cancelled = getCancelled ? (saved?.cancelled ?? null) : null;
412
413
  const budget = maintenance && Number(maintenance.share) > 0 ? { share: Number(maintenance.share), whenIdle: !!maintenance.whenIdle } : null;
@@ -1311,7 +1312,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1311
1312
  if (!["merged", "invalid", "deferred"].includes(gone?.outcome)) gone = null; // #4920: deferred = another lane owns the issue (lease or open PR on GitHub)
1312
1313
  }
1313
1314
  // #5526: a hold placed since the pass read is honoured at launch: the issue goes back to pending, no lane
1314
- if (!cancelled && !halted) { refreshHeld(); if (opHeld.has(n)) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
1315
+ if (!cancelled && !halted) { refreshHeld(); refreshPause(); if (opHeld.has(n) || opPause) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
1315
1316
  if (halted) return; // #4454: stopped before launch; no pid, so a resume queues it again
1316
1317
  let r;
1317
1318
  if (cancelled) r = { terminalReason: "deferred", code: "run.interrupted", cost_usd: 0, detail: "cancelled before launch" }; // #4376
@@ -1396,7 +1397,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1396
1397
 
1397
1398
  // #5469: a final held row names the owner and since when the hold recorded them (`forgedock orchestrate --hold ... --for`)
1398
1399
  const heldByOperator = (n) => { let e = null; try { e = getHoldInfo?.()?.[n] ?? null; } catch { e = null; } return e ? `held by operator (${e.owner}, since ${e.since})` : "held by operator"; };
1399
- const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? heldByOperator(n) : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
1400
+ const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? heldByOperator(n) : opPause ? pauseText() : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
1400
1401
  // #4315: a recovery queued but never launched (the batch stopped: breaker, budget, hold; or a resume that did not relaunch a
1401
1402
  // lost run) left the issue without needs-human, since a non-final attempt does not relabel. Relabel it once, with the full reason.
1402
1403
  // #4318: also on a throw out of the loop and on a signal (`onExit`); `cause` overrides the held reason. Runs once per process.
@@ -1549,6 +1550,29 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1549
1550
  s.at = t;
1550
1551
  try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
1551
1552
  }
1553
+ // #5975: the batch pause. `paused (reason, until …)`, the one text every surface shows.
1554
+ function pauseText(p = opPause) { return `paused (${p?.reason ?? "no reason given"}, until ${p?.expiresAt ?? "unpause"})`; }
1555
+ function refreshPause() {
1556
+ if (!getPause) return;
1557
+ if (expirePause) { // like #5469 holds: a pause past its expiry is lifted here, with a row and a decision
1558
+ let e = null; try { e = expirePause() ?? null; } catch { e = null; }
1559
+ if (e) {
1560
+ decided({ issue: null, what: `pause expired (paused by ${e.owner} since ${e.since}${e.reason ? `: ${e.reason}` : ""}); admission resumed`, why: "pause expiry (--pause --for)", alternative: "pause it again" });
1561
+ update({ issue: null, outcome: "pause-expired", detail: `${e.owner}, since ${e.since}` });
1562
+ if (e.ownerGone) update({ issue: null, outcome: "hold-alert", detail: `the pause owner session (${e.owner}) is gone; the pause expired and admission resumed` });
1563
+ }
1564
+ }
1565
+ let got = null; try { got = getPause() ?? null; } catch { got = opPause; }
1566
+ const next = got && typeof got === "object" ? got : null;
1567
+ if (next && !opPause) {
1568
+ decided({ issue: null, what: `batch ${pauseText(next)} (forgedock orchestrate --pause); running lanes continue`, why: "operator request", alternative: "cancel the batch" });
1569
+ update({ issue: null, outcome: "pause", detail: pauseText(next) });
1570
+ } else if (!next && opPause) {
1571
+ decided({ issue: null, what: "batch unpaused (forgedock orchestrate --unpause); admission resumed", why: "operator request", alternative: "resume the batch" });
1572
+ update({ issue: null, outcome: "unpause", detail: "admission resumed" });
1573
+ }
1574
+ opPause = next;
1575
+ }
1552
1576
  // #4592: re-read the hold set; one decision and one row when it changes.
1553
1577
  const holdExpiring = (list) => { let info = null; try { info = getHoldInfo?.() ?? null; } catch { info = null; } return !!expireHolds && list.some((n) => Number.isFinite(Date.parse(info?.[n]?.expiresAt))); }; // #5469
1554
1578
  // #5632: a function declaration (hoisted): finish/recovery callbacks of a resumed batch can call it before this line runs
@@ -1858,9 +1882,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1858
1882
  driftHeld.clear();
1859
1883
  integHeld.clear();
1860
1884
  opHeldHit.clear();
1885
+ pauseHit = false;
1861
1886
  blockedHit.clear();
1862
1887
  baseHit.clear();
1863
1888
  refreshHeld();
1889
+ refreshPause();
1864
1890
  await refreshBlocked();
1865
1891
  await refreshBaseWaits();
1866
1892
  checkGates();
@@ -1880,6 +1906,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
1880
1906
  await gateEnvSigs(); // #5755
1881
1907
  const isReady = (n) => {
1882
1908
  if (pfAll || (pfRemote && isRemote(n))) return false;
1909
+ if (opPause) { pauseHit = true; return false; } // #5975: every admission path (dependency merge, env/engine re-admit, requeue, add, recovery) ends here
1883
1910
  if (opHeld.has(n)) { opHeldHit.add(n); return false; }
1884
1911
  if (blocked.has(n)) { blockedHit.add(n); return false; } // #4773
1885
1912
  if (baseHeld.has(n)) { baseHit.add(n); return false; } // #5031
@@ -2017,6 +2044,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2017
2044
  if (holdUntil) waits.push(holdUntil);
2018
2045
  let wake = waits.length ? Math.max(0, Math.min(...waits) - t) : null;
2019
2046
  if (holdUntil && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4446: a cleared hold (forgedock limits clear) admits on the next poll
2047
+ if (getPause && pending.length && (opPause || running.size)) wake = Math.min(wake ?? pollMs, pollMs); // #5975: an --unpause or expiry
2020
2048
  if ((getParallel || getHeld) && pending.length) wake = Math.min(wake ?? pollMs, pollMs);
2021
2049
  if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
2022
2050
  if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
@@ -2043,6 +2071,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
2043
2071
  else if (pending.length && baseHit.size) await nap(wake ?? pollMs); // #5031: only issues waiting for a base commit: poll for it
2044
2072
  else if (pending.length && waits.length) await nap(Math.min(wake, getCancelled ? pollMs : Infinity)); // wake is poll-capped by a hold or a live K; #4454: nap wakes on a stop
2045
2073
  else if (pending.length && budgetHeld) { if (await drainAdds()) continue; break; } // maintenance the budget does not admit now: held for a later batch
2074
+ else if (pending.length && opPause && pauseHit && Number.isFinite(Date.parse(opPause.expiresAt)) && !cancelled) await nap(wake ?? pollMs); // #5975: a timed pause keeps the batch open until it expires, not finalised silently
2075
+ else if (pending.length && opPause && pauseHit) { if (await drainAdds()) continue; break; } // #5975: paused with no expiry: pending for a --resume after --unpause
2046
2076
  else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n)) && holdExpiring([...opHeldHit]) && !cancelled) await nap(wake ?? pollMs); // #5469: a hold with an expiry keeps the batch open until it expires (re-admit or alert), not finalised silently
2047
2077
  else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n))) { if (await drainAdds()) continue; break; } // #4592: held by the operator: pending for a --resume
2048
2078
  else if (pending.length && (driftHeld.size || integHeld.size)) { if (await drainAdds()) continue; break; } // held by a drift flag (block_dispatch) or a red integration streak (#4667): pending for a later batch
@@ -55,9 +55,16 @@ export function tickText(c) {
55
55
  * @returns the check, plus `killed` (and `started` when it started one)
56
56
  */
57
57
  export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
58
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null } = {}) {
58
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null, unit = null, emit = null } = {}) {
59
59
  const c = stallCheck({ dir, stallMs, now, alive });
60
60
  if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
61
+ // #5966: the unit says active but no daemon answers (no live pid/heartbeat): alert and restart it, whether or not batches are unfinished
62
+ if (c.status === "down" && start && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
63
+ log(`schedd watchdog: ALERT unit is active but no daemon answers (schedd status: not running); restarting the unit`);
64
+ try { emit?.({ type: "schedd.unit-no-daemon", at: now() }); } catch { /* advisory */ }
65
+ try { await start(); } catch (e) { log(`schedd watchdog: start failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false }; }
66
+ return { ...c, killed: null, alerted: true, started: true };
67
+ }
61
68
  if (c.status === "down" && start) {
62
69
  let ids = [];
63
70
  try { ids = unfinished() ?? []; } catch { ids = []; }
@@ -68,4 +68,19 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
68
68
  assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
69
69
  assert.equal(bestEffortRenice(() => {}), true);
70
70
  });
71
+
72
+ it("#5966: a down daemon while the unit is active alerts, emits an event and restarts the unit, even with no unfinished batches", async () => {
73
+ const dir = tmpDir("schedd-wd-unit-"), lines = [], events = [];
74
+ let starts = 0;
75
+ const run = (unit) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
76
+ const r = await run(() => "active");
77
+ assert.equal(r.started, true);
78
+ assert.equal(r.alerted, true);
79
+ assert.equal(starts, 1);
80
+ assert.equal(events[0].type, "schedd.unit-no-daemon");
81
+ assert.ok(lines.some((l) => l.includes("ALERT")));
82
+ await run(() => "inactive");
83
+ await run(() => null);
84
+ assert.equal(starts, 1, "an inactive or absent unit with nothing unfinished is left down");
85
+ });
71
86
  });