forgedock 1.71.0 → 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +5 -4
  3. package/bin/init-detect.mjs +35 -2
  4. package/bin/lean/admit.mjs +118 -0
  5. package/bin/lean/admit.test.mjs +78 -0
  6. package/bin/lean/attempts.mjs +1 -1
  7. package/bin/lean/batch.mjs +8 -0
  8. package/bin/lean/batch.test.mjs +17 -0
  9. package/bin/lean/concurrency.mjs +7 -2
  10. package/bin/lean/concurrency.test.mjs +16 -3
  11. package/bin/lean/conformance.mjs +2 -0
  12. package/bin/lean/conformance.test.mjs +9 -0
  13. package/bin/lean/effects.mjs +8 -0
  14. package/bin/lean/failure-census.mjs +1 -1
  15. package/bin/lean/lean.mjs +93 -4
  16. package/bin/lean/lean.test.mjs +38 -0
  17. package/bin/lean/orchestrate-envhold.test.mjs +14 -0
  18. package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
  19. package/bin/lean/orchestrate.mjs +33 -11
  20. package/bin/lean/queuecause.mjs +42 -0
  21. package/bin/lean/release-cigreen.mjs +18 -4
  22. package/bin/lean/release-cigreen.test.mjs +23 -0
  23. package/bin/lean/release-review.mjs +24 -10
  24. package/bin/lean/release-review.test.mjs +65 -0
  25. package/bin/lean/release.mjs +1 -1
  26. package/bin/lean/release.test.mjs +19 -0
  27. package/bin/lean/schedd.mjs +24 -1
  28. package/bin/lean/schedd.test.mjs +38 -0
  29. package/bin/pool/agent.mjs +32 -14
  30. package/bin/pool/docker-dns.mjs +23 -0
  31. package/bin/pool/docker.mjs +5 -3
  32. package/bin/pool/engine-placement.test.mjs +2 -2
  33. package/bin/pool/image-manifest.test.mjs +13 -0
  34. package/bin/pool/lane-image.mjs +56 -15
  35. package/bin/pool/lane-tools.mjs +26 -12
  36. package/bin/pool/lane-tools.test.mjs +63 -1
  37. package/bin/pool/project-layer.mjs +2 -2
  38. package/bin/pool/router.mjs +2 -1
  39. package/bin/review-staging.mjs +14 -11
  40. package/bin/review-staging.test.mjs +20 -1
  41. package/bin/stats/escapes.mjs +124 -0
  42. package/bin/stats/index.mjs +5 -1
  43. package/bin/stats/quality-ledger.mjs +49 -0
  44. package/bin/stats/quality-ledger.test.mjs +84 -0
  45. package/bin/stats/weekly.mjs +230 -0
  46. package/docs/OUTCOME-CODES.md +2 -1
  47. package/package.json +1 -1
  48. package/pool/README.md +2 -0
  49. package/pool/image/Dockerfile +4 -1
  50. package/pool/image/lane-tools-sets.json +6 -0
  51. package/scripts/lane-variants.mjs +51 -0
@@ -337,7 +337,7 @@ export async function fixStep(ctx) {
337
337
  if (s.err) return blocked(s.err);
338
338
  res = s.r;
339
339
  }
340
- if (res.marker === "FORGE:GATE_PASS") return { verdict: res.verdict, head: res.head };
340
+ if (res.marker === "FORGE:GATE_PASS" && !res.blocking?.length && !res.guards?.length) return { verdict: res.verdict, head: res.head };
341
341
  if (res.blocking?.length || res.guards?.length) {
342
342
  const names = res.blocking?.length ? res.blocking.map((n) => `#${n}`).join(" ") : (res.guards ?? []).map((g) => g.name).join(", ");
343
343
  const queued = res.blocking?.length ? await seam.queueBlockers?.({ pr: res.pr, blockers: res.blocking }) : null;
@@ -347,8 +347,16 @@ export async function fixStep(ctx) {
347
347
  ctx.save();
348
348
  return { blocked: true, held: true, reason };
349
349
  }
350
- if (res.ciFailing > 0) return blocked(`required checks of #${res.pr} are not green at ${String(res.head).slice(0, 7)} (${res.ciPendingOnly ? "pending" : "red"}); re-run the release: ci-green waits and fixes CI once, then one review pass`);
351
- return blocked(`${res.verdict} (${res.marker}) on #${res.pr} at ${String(res.head).slice(0, 7)} with no blocking finding and no red CI: the gate summary names the blocker; read it and re-run the release`);
350
+ if (res.ciFailing > 0) return blockedForRerun(ctx, `required checks of #${res.pr} are not green at ${String(res.head).slice(0, 7)} (${res.ciPendingOnly ? "pending" : "red"}); re-run the release: ci-green waits and fixes CI once, then one review pass`);
351
+ return blockedForRerun(ctx, `${res.verdict} (${res.marker}) on #${res.pr} at ${String(res.head).slice(0, 7)} with no blocking finding and no red CI: the gate summary names the blocker; read it and re-run the release`);
352
+ }
353
+
354
+ /** #6175: a block that tells the operator to re-run must leave ci-green and review undone, else the resume re-reads the same stale review result. */
355
+ function blockedForRerun(ctx, reason) {
356
+ delete ctx.state.steps["ci-green"];
357
+ delete ctx.state.steps.review;
358
+ ctx.save();
359
+ return blocked(reason);
352
360
  }
353
361
 
354
362
  /**
@@ -375,11 +383,11 @@ async function legacyFixStep(ctx) {
375
383
  if (s.err) return blocked(s.err);
376
384
  r = s.r;
377
385
  if (r.marker === "FORGE:GATE_PASS") break;
378
- if (r.ciCancelOnly) return blocked(`required checks of #${r.pr} still cancelled after a rerun, with no failure to fix`);
386
+ if (r.ciCancelOnly) return blockedForRerun(ctx, `required checks of #${r.pr} still cancelled after a rerun, with no failure to fix`);
379
387
  continue;
380
388
  }
381
389
  // Required checks that are only still pending (#5519) have not failed: no CI issue or lane, the release re-runs once CI finishes.
382
- if (!r.blocking?.length && r.ciFailing > 0 && r.ciPendingOnly) return blocked(`required checks of #${r.pr} still pending, with no failure to fix; re-run the release once CI finishes`);
390
+ if (!r.blocking?.length && r.ciFailing > 0 && r.ciPendingOnly) return blockedForRerun(ctx, `required checks of #${r.pr} still pending, with no failure to fix; re-run the release once CI finishes`);
383
391
  if (roundsAt(ctx.state, r.head) >= cfg.maxRounds) {
384
392
  const s = await secondRound(ctx, seam, r, cfg);
385
393
  if (s.blocked) return s;
@@ -477,15 +485,21 @@ export function realSeam({ repo, def, env = process.env, laneStrip = [], cwd = p
477
485
  queueBlockers: async ({ blockers }) => {
478
486
  try {
479
487
  const batches = (await io?.batches?.(repo)) ?? [];
480
- if (!batches.length) return { batch: null };
481
- const add = io?.addToBatch ?? (async (id, nums) => { const { orchestrateFromCli } = await import("../engine-cli.mjs"); await orchestrateFromCli(["--add", id, ...nums.map(String)]); });
482
- await add(batches[0].id, blockers);
483
- return { batch: batches[0].id };
488
+ const open = batches.find((b) => !b.paused && !b.cancelled); // #6178: a paused or cancelled batch admits nothing
489
+ if (!open) return { batch: null, ...(batches.length ? { error: "every batch is paused or cancelled" } : {}) };
490
+ const add = io?.addToBatch ?? (async (id, nums) => { const { orchestrateFromCli } = await import("../engine-cli.mjs"); return orchestrateFromCli(["--add", id, ...nums.map(String)]); });
491
+ const res = await add(open.id, blockers);
492
+ // #6178: queued only when the add scheduled something; skipped ones (owned elsewhere, closed, unreadable) are not queued
493
+ if (res && !(res.added?.length || res.requeued?.length)) return { batch: null, error: `batch ${open.id} took none of ${blockers.map((n) => `#${n}`).join(" ")}: ${(res.skipped ?? []).map((x) => `#${x.issue} ${x.reason}`).join(", ") || "nothing added"}` };
494
+ return { batch: open.id };
484
495
  } catch (e) { return { batch: null, error: String(e?.message ?? e).split("\n")[0] }; }
485
496
  },
486
497
  holdReleasePr: async ({ pr, blockers, guards, queued, verdict }) => {
487
498
  const what = blockers.length ? `confirmed CRITICAL/HIGH finding(s) ${blockers.map((n) => `#${n}`).join(" ")}` : `failed guard(s) ${guards.map((g) => g.name).join(", ")}`;
488
- const body = `Release stopped: ${verdict ?? "BLOCK DEPLOY"}. ${what} block this release. ${queued?.batch ? `They are queued in orchestrate batch ${queued.batch}.` : "No orchestrate batch is open: start one with `forgedock orchestrate " + blockers.join(" ") + "`."} Nothing found by the review is fixed inside the release PR; the next release starts fresh after they merge (the open-finding gate enforces it).`;
499
+ // #6178: with nothing queued the PR stays open with a status; closing it would drop the blockers
500
+ const queuedLine = queued?.batch ? `They are queued in orchestrate batch ${queued.batch}.` : `No open orchestrate batch took them${queued?.error ? ` (${queued.error})` : ""}: start one with \`forgedock orchestrate ${blockers.join(" ")}\`. This release PR stays open.`;
501
+ const body = `Release stopped: ${verdict ?? "BLOCK DEPLOY"}. ${what} block this release. ${queuedLine} Nothing found by the review is fixed inside the release PR; the next release starts fresh after they merge (the open-finding gate enforces it).`;
502
+ if (!queued?.batch && blockers.length) { try { gh(["pr", "comment", String(pr), "-R", repo, "--body", body]); } catch { /* the blocked result still stops the job */ } return { closed: false }; }
489
503
  try { gh(["pr", "close", String(pr), "-R", repo, "--comment", body]); return { closed: true }; } catch { try { gh(["pr", "comment", String(pr), "-R", repo, "--body", body]); } catch { /* the blocked result still stops the job */ } return { closed: false }; }
490
504
  },
491
505
  async fileDeferred({ pr, items }) {
@@ -663,6 +663,12 @@ describe("default flow (v1.0 contract, dcfb86bf): one review pass, nothing found
663
663
  assert.equal((await fixStep(c)).verdict, "APPROVE FOR DEPLOY");
664
664
  assert.equal(s.log.filter((e) => e[0] === "lane" || e[0] === "fix-issue").length, 0);
665
665
  });
666
+ it("a blocker is never passed on GATE_PASS (#6174: block_severity medium)", async () => {
667
+ const s = fakeSeam();
668
+ const c = def(s, { review: { done: true, result: { pr: 7, head: H1, verdict: "APPROVE FOR DEPLOY", marker: "FORGE:GATE_PASS", blocking: [101], filed: [101], ciFailing: 0 } } });
669
+ const r = await fixStep(c);
670
+ assert.equal(r.blocked, true); assert.equal(r.held, true);
671
+ });
666
672
  it("a confirmed blocker stops the release: no fix lane, blockers queued into the open batch, release PR closed, status names the blockers", async () => {
667
673
  const s = fakeSeam({ fins: [blockFin], summary: bad });
668
674
  const calls = [];
@@ -682,11 +688,70 @@ describe("default flow (v1.0 contract, dcfb86bf): one review pass, nothing found
682
688
  const c = def(s); c.state.steps.review = { done: true, result: await reviewStep(c) };
683
689
  assert.match((await fixStep(c)).reason, /^review blockers #100; release PR #7 held/);
684
690
  });
691
+ describe("#6178 queueBlockers picks an open batch and checks the add", () => {
692
+ const mk = (batches, add, calls = []) => realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp", gh: (a) => { calls.push(a); return ""; }, io: { batches: async () => batches, addToBatch: add } });
693
+ it("skips paused and cancelled batches", async () => {
694
+ const added = [];
695
+ const r = await mk([{ id: "p", paused: true }, { id: "c", cancelled: true }, { id: "ok" }], async (id) => { added.push(id); return { added: [100], skipped: [] }; }).queueBlockers({ blockers: [100] });
696
+ assert.deepEqual(added, ["ok"]); assert.equal(r.batch, "ok");
697
+ });
698
+ it("no open batch: nothing is added", async () => {
699
+ let called = false;
700
+ const r = await mk([{ id: "p", paused: true }], async () => { called = true; return {}; }).queueBlockers({ blockers: [100] });
701
+ assert.equal(r.batch, null); assert.equal(called, false);
702
+ });
703
+ it("a skipped-only add is not reported as queued", async () => {
704
+ const r = await mk([{ id: "b" }], async () => ({ added: [], requeued: [], skipped: [{ issue: 100, reason: "owned by x" }] })).queueBlockers({ blockers: [100] });
705
+ assert.equal(r.batch, null); assert.match(r.error, /#100 owned by x/);
706
+ });
707
+ it("holdReleasePr leaves the PR open with a status when nothing was queued", async () => {
708
+ const calls = [];
709
+ const r = await mk([], async () => ({}), calls).holdReleasePr({ pr: 7, blockers: [100], guards: [], queued: { batch: null } });
710
+ assert.equal(r.closed, false); assert.equal(calls[0][1], "comment"); assert.match(calls[0].join(" "), /stays open/);
711
+ });
712
+ it("a guard-only hold (no blockers) still closes the PR", async () => {
713
+ const calls = [];
714
+ const r = await mk([], async () => ({}), calls).holdReleasePr({ pr: 7, blockers: [], guards: [{ name: "g" }], queued: { batch: null } });
715
+ assert.equal(r.closed, true); assert.equal(calls[0][1], "close");
716
+ });
717
+ });
685
718
  it("MEDIUM, LOW and unconfirmed findings never block: GATE_PASS stays a pass", async () => {
686
719
  const s = fakeSeam({ fins: [fin({ toFile: [{ id: "u", title: "maybe", severity: "HIGH" }, { id: "m", title: "med", severity: "MEDIUM" }], confirmedIds: ["m"] })] });
687
720
  const r = await reviewStep(def(s));
688
721
  assert.deepEqual(r.blocking, []);
689
722
  });
723
+ it("#6175: a red or pending CI block clears ci-green and review, so a resume re-runs both instead of re-reading the stale result", async () => {
724
+ for (const pend of [false, true]) {
725
+ const s = fakeSeam({ heads: [H1] });
726
+ s.summary = async () => ({ code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 2, ciPendingOnly: pend }, lines: [] });
727
+ const c = def(s, { "ci-green": { done: true }, review: { done: true, result: { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [], guards: [], ciFailing: 2, ciPendingOnly: pend } } });
728
+ let saved = 0; c.save = () => { saved++; };
729
+ const r = await fixStep(c);
730
+ assert.equal(r.blocked, true);
731
+ assert.equal(c.state.steps["ci-green"], undefined, "ci-green is re-run on resume");
732
+ assert.equal(c.state.steps.review, undefined, "review is re-run on resume");
733
+ assert.ok(saved > 0, "the cleared ledger is saved");
734
+ }
735
+ });
736
+ it("#6175: a review blocker keeps ci-green and review done (the stop is sticky)", async () => {
737
+ const s = fakeSeam({ fins: [blockFin], summary: bad });
738
+ s.queueBlockers = async () => ({ batch: "b-1" }); s.holdReleasePr = async () => ({ closed: true });
739
+ const c = def(s, { "ci-green": { done: true } }); c.state.steps.review = { done: true, result: await reviewStep(c) };
740
+ await fixStep(c);
741
+ assert.ok(c.state.steps["ci-green"].done && c.state.steps.review.done);
742
+ });
743
+ it("#6175: the legacy pending-only block clears ci-green and review so a resume re-runs them", async () => {
744
+ const s = fakeSeam({ heads: [H1] });
745
+ const res = { pr: 7, head: H1, verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", blocking: [], guards: [], ciFailing: 1, ciPendingOnly: true };
746
+ const c = ctx(s, { "ci-green": { done: true }, review: { done: true, result: res } });
747
+ s.summary = async () => ({ code: 0, data: res, lines: [] });
748
+ let saved = 0; c.save = () => { saved++; };
749
+ const r = await fixStep(c);
750
+ assert.equal(r.blocked, true);
751
+ assert.equal(c.state.steps["ci-green"], undefined);
752
+ assert.equal(c.state.steps.review, undefined);
753
+ assert.ok(saved > 0);
754
+ });
690
755
  it("coStartCi is not run in the default flow", async () => {
691
756
  const s = fakeSeam(); const c = def(s); c.config.fix = { coStart: true };
692
757
  const gh = []; c.io.gh = async (a) => { gh.push(a); return "{}"; };
@@ -501,7 +501,7 @@ export function realReleaseIo({ env = process.env, exec = execFileSync, print =
501
501
  runningLanes: (repo) => unfinished(repo).flatMap((b) => Object.entries(b.store.load()?.lanes ?? {})
502
502
  .filter(([n, rec]) => rec?.pid && isLaneAlive(rec.pid, b.resultFile(n)) && !existsSync(b.resultFile(n)))
503
503
  .map(([n]) => ({ batch: b.id, issue: n }))),
504
- batches: (repo) => unfinished(repo).map((b) => ({ id: b.id, k: b.readParallel() ?? 1 })),
504
+ batches: (repo) => unfinished(repo).map((b) => ({ id: b.id, k: b.readParallel() ?? 1, paused: !!b.readPause(), cancelled: !!b.readCancel() })),
505
505
  setParallel: async (id, k) => {
506
506
  const { orchestrateFromCli } = await import("../engine-cli.mjs");
507
507
  await orchestrateFromCli(["--set-parallel", id, String(k)]);
@@ -647,3 +647,22 @@ describe("default ci-green flow in the conductor (#6164)", () => {
647
647
  assert.equal(readReleaseConfig("release:\n review_fixes: true\n").reviewFixes, true);
648
648
  });
649
649
  });
650
+
651
+ describe("realReleaseIo.batches reports paused/cancelled (#6178)", () => {
652
+ it("flags a paused and a cancelled batch, leaves an open one unflagged", async () => {
653
+ const { mkdirSync, writeFileSync } = await import("node:fs");
654
+ const { realReleaseIo } = await import("./release.mjs");
655
+ const root = tmpDir("release-6178");
656
+ const seed = (id, files = {}) => {
657
+ const d = join(root, id); mkdirSync(join(d, "lanes"), { recursive: true });
658
+ writeFileSync(join(d, "plan.json"), JSON.stringify({ repo: REPO })); writeFileSync(join(d, "state.json"), JSON.stringify({ lanes: {} }));
659
+ for (const [n, v] of Object.entries(files)) writeFileSync(join(d, n), JSON.stringify(v));
660
+ };
661
+ seed("b20261110-000000-1"); seed("b20261110-000000-2", { pause: { since: "2026-11-10T00:00:00Z" } }); seed("b20261110-000000-3", { cancel: { at: "2026-11-10T00:00:00Z" } });
662
+ const io = realReleaseIo({ env: { ...process.env, FORGEDOCK_BATCH_DIR: root }, print: () => {} });
663
+ const by = Object.fromEntries((await io.batches(REPO)).map((b) => [b.id.slice(-1), b]));
664
+ assert.deepEqual([by[1].paused, by[1].cancelled], [false, false]);
665
+ assert.deepEqual([by[2].paused, by[2].cancelled], [true, false]);
666
+ assert.deepEqual([by[3].paused, by[3].cancelled], [false, true]);
667
+ });
668
+ });
@@ -65,6 +65,8 @@ import { applySetExecution } from "./live-execution.mjs";
65
65
  import { liveOverload } from "./hostload.mjs";
66
66
 
67
67
  /** #5938: epoch ms of the newest lane log of a running issue (a lane heartbeat), or null. */
68
+ /** #6197: an add/requeue unconsumed this long (ms) re-hosts or flags its batch. */
69
+ export const UNRUN_STALE_MS = 60_000;
68
70
  export function lanesAlive(b, state) {
69
71
  let best = null;
70
72
  for (const n of Object.keys(state?.running ?? {})) { try { const m = statSync(b.logFile(n)).mtimeMs; if (best === null || m > best) best = m; } catch { /* no lane log yet */ } }
@@ -224,7 +226,7 @@ function takeLock(lock, pid, alive) {
224
226
  */
225
227
  export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
226
228
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
227
- lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
229
+ lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, unrunStaleMs = UNRUN_STALE_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
228
230
  abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
229
231
  hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
230
232
  exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined, sloGh = undefined, introspect = undefined } = {}) {
@@ -308,6 +310,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
308
310
  // dispatched by re-hosting the batch once the run has ended. Once per distinct set of unrun entries, so an add that cannot
309
311
  // drain (a cancel, a tripped breaker) never loops.
310
312
  const rehostedUnrun = new Map();
313
+ const unrunRehostAt = new Map(); // #6197: last stale-input re-host per batch (rate limit)
311
314
  function rehostUnrun(id) {
312
315
  if (closing || hosted.has(id) || starting.has(id)) return;
313
316
  let sig;
@@ -657,6 +660,26 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
657
660
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
658
661
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
659
662
  await efficiencyTick(b, plan, state, { now, reported, cancelled }); // #5987: advisory; never throws, never changes dispatch
663
+ // #6197: an add/requeue left unconsumed past UNRUN_STALE_MS is a stall of its own: re-host an unhosted batch (reported ones too,
664
+ // even when rehostUnrun's one-shot signature already fired; at most once per window), alert on a hosted one that is not draining.
665
+ const unrunAge = !cancelled ? b.unrunInputAgeMs(now) : null;
666
+ if (unrunAge !== null && unrunAge > unrunStaleMs) {
667
+ const st = b.store.load();
668
+ if (!(st?.breaker && !st.breaker.transport && !st.breaker.environmental)) {
669
+ const adds = b.unrunAdds(), reqs = b.unrunRequeues().map((e) => e.issue ?? e), what = [...adds, ...reqs].map((n) => `#${n}`).join(", ");
670
+ if (!isHosted) {
671
+ if (now - (unrunRehostAt.get(id) ?? 0) >= unrunStaleMs) {
672
+ unrunRehostAt.set(id, now);
673
+ log(`schedd: re-hosting batch ${id} (unconsumed add/requeue ${what} for ${Math.round(unrunAge / 1000)}s)`);
674
+ const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
675
+ starting.set(id, started);
676
+ started.catch((e) => log(`schedd: re-host ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
677
+ }
678
+ continue;
679
+ }
680
+ if (recordStallAlert(b, { ready: [...adds, ...reqs], code: "unconsumed-input", detail: `add/requeue ${what} unconsumed for ${Math.round(unrunAge / 1000)}s` })) log(`schedd: batch ${id} needs you: unconsumed add/requeue ${what}`);
681
+ }
682
+ }
660
683
  const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastDispatchClockMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
661
684
  let stall = evaluateDispatchStall(state, stallOpts);
662
685
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
@@ -640,6 +640,44 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
640
640
  } finally { await d.close(); }
641
641
  });
642
642
 
643
+ // #6197: an add that no resume consumed is retried by the watchdog once it is older than unrunStaleMs.
644
+ const staleAddRun = async ({ tag, staleMs, ageMs, cancel = false, waitMs }) => {
645
+ const dir = tmpDir(`schedd-stale-${tag}-`), root = join(dir, "batches"), id = `b20261031-000000-619${tag}`;
646
+ const calls = [];
647
+ const runBatch = async ({ argv, sink }) => {
648
+ calls.push(argv);
649
+ const b = openBatch(root, id);
650
+ if (argv[0] !== "--resume") {
651
+ b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString() });
652
+ b.store.save({ v: 1, order: [1], results: { 1: { terminalReason: "merged" } }, running: {}, pending: [] });
653
+ b.writeReport({ done: true });
654
+ writeFileSync(join(b.dir, "add"), "[2]\n");
655
+ const old = new Date(Date.now() - ageMs);
656
+ utimesSync(join(b.dir, "add"), old, old);
657
+ if (cancel) b.requestCancel({ reason: "operator" });
658
+ }
659
+ sink.batch({ id, dir: b.dir });
660
+ return {};
661
+ };
662
+ const d = await startDaemon({ dir, root, runBatch, log: () => {}, resumeOnStart: false, stallCheckMs: 50, unrunStaleMs: staleMs });
663
+ try {
664
+ await request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["1"], cwd: dir, env: {} });
665
+ await new Promise((r) => setTimeout(r, waitMs));
666
+ return calls.length;
667
+ } finally { await d.close(); }
668
+ };
669
+ it("#6197: a reported batch whose add stayed unconsumed past the stale window is re-hosted again after the one-shot re-host", async () => {
670
+ const n = await staleAddRun({ tag: "1", staleMs: 300, ageMs: 10_000, waitMs: 1500 });
671
+ assert.ok(n >= 3, `initial + one-shot re-host + stale re-host; got ${n}`);
672
+ assert.ok(n <= 10, `rate limited, not a loop; got ${n}`);
673
+ });
674
+ it("#6197: an add younger than the stale window gets only the one-shot re-host", async () => {
675
+ assert.equal(await staleAddRun({ tag: "2", staleMs: 60_000, ageMs: 0, waitMs: 1000 }), 2);
676
+ });
677
+ it("#6197: a cancelled batch is never re-hosted for a stale add", async () => {
678
+ assert.equal(await staleAddRun({ tag: "3", staleMs: 300, ageMs: 10_000, cancel: true, waitMs: 1000 }), 1);
679
+ });
680
+
643
681
  it("#4917: a batch whose breaker tripped (not transport) is not re-hosted by the timer", async () => {
644
682
  const dir = tmpDir("schedd-rehost-brk-"), root = join(dir, "batches"), id = "b20261031-000000-4919";
645
683
  const calls = [];
@@ -11,7 +11,8 @@ import { basename, dirname, join } from "node:path";
11
11
  import { cpus, hostname } from "node:os";
12
12
  import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
13
13
  import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
14
- import { provideLaneImage } from "./lane-image.mjs";
14
+ import { provideLaneImage, pullVariantImage, withIpv4Fallback, fetchLaneDigest } from "./lane-image.mjs";
15
+ import { ensureDaemonDns } from "./docker-dns.mjs";
15
16
  import { jsonStore } from "./store.mjs";
16
17
  import { makeWarm } from "./warm.mjs";
17
18
  import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
@@ -149,7 +150,7 @@ export function readLaneFile(path) {
149
150
  if (fd === null) return "";
150
151
  try { return readFileSync(fd, "utf8"); } catch { return ""; } finally { try { closeSync(fd); } catch { /* closed */ } }
151
152
  }
152
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
153
+ export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null, fetchDigest = fetchLaneDigest } = {}) {
153
154
  const stateDir = cfg.state_dir;
154
155
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
155
156
  const sb = () => store.data.sandboxes;
@@ -172,6 +173,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
172
173
  const running = versionOf(cfg.code_root ?? repoRoot);
173
174
  // The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
174
175
  const image = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(running.version);
176
+ // #6187: lane_tools variants of the published default tag are pulled from ghcr first; every build runs under the IPv4 fallback
177
+ const variantDocker = (base) => (base === laneImageTag(running.version) && docker.pull && docker.tag
178
+ ? Object.assign(Object.create(docker), { withFallback: (op) => withIpv4Fallback(op, { log }), pullVariant: (tag) => pullVariantImage({ docker, tag, version: running.version, log }) })
179
+ : Object.assign(Object.create(docker), { withFallback: (op) => withIpv4Fallback(op, { log }) }));
175
180
  const upgrade = { state: "idle", error: null };
176
181
  const prepull = { error: null };
177
182
  const dindImage = cfg.dind_image ?? "docker:27.5.1-dind";
@@ -179,10 +184,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
179
184
  const agentId = String(cfg.agent_id ?? cfg.name ?? hostname()).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
180
185
  const AGENT = agentLabel(agentId);
181
186
  const OWN = [LABEL, AGENT];
187
+ // #6195: a dockerd DNS failure triggers a daemon.json dns repair; docker restarts only while no sandbox is active.
188
+ const pinOpts = { ensureDns: () => ensureDaemonDns({ idle: () => activeRecs().length === 0, restart: () => run("systemctl", ["restart", "docker"], { timeout: 120000 }), log }) };
182
189
  /** Images a sandbox may need are pulled ahead of time, never inside a launch request (which has a short timeout). */
183
190
  async function prepullImages() {
184
191
  if (await docker.hasImage?.(dindImage)) { prepull.error = null; return; }
185
- try { await docker.pull(dindImage); prepull.error = null; return; }
192
+ try { await withIpv4Fallback(() => docker.pull(dindImage), { ...pinOpts, log }); prepull.error = null; return; }
186
193
  catch (e) { log.warn?.(`pull ${dindImage} failed (${String(e.stderr || e.message).slice(0, 160)}); fetching it from the router`); }
187
194
  // Fallback: the router host pulls the image and streams it (some hosts' daemons cannot reach the registry).
188
195
  const file = join(stateDir, "image.tar");
@@ -319,10 +326,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
319
326
  const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
320
327
  const prioOf = (r) => r.priority ?? "normal";
321
328
  const peakUse = () => activeRecs().reduce((a, r) => { const e = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }); return { cpus: a.cpus + Math.max(r.cpus, e.cpus), mem: a.mem + Math.max(r.mem_gb, e.mem) }; }, { cpus: 0, mem: 0 });
322
- // #6047: heavy tokens (cfg.elastic_lanes, default off). A lane is admitted on its base reservation; each heavy step leases a token
329
+ // #6047: heavy tokens (cfg.elastic_lanes, default on since #6204). A lane is admitted on its base reservation; each heavy step leases a token
323
330
  // (weight = max(default, p90 history - base)) from this host's pool. Tokens live in store.data.heavy and expire with their lease,
324
331
  // when the sandbox exits or when it is destroyed.
325
- const elastic = () => cfg.elastic_lanes === true;
332
+ const elastic = () => cfg.elastic_lanes !== false; // #6204: on by default; `elastic_lanes: false` restores worst-case accounting
326
333
  const heavyTtlMs = () => (cfg.heavy_ttl_s ?? 300) * 1000;
327
334
  const heavyDefault = () => ({ cpus: cfg.heavy_weight?.cpus ?? 1, mem: cfg.heavy_weight?.mem_gb ?? 2 });
328
335
  const heavyTokens = () => (store.data.heavy ??= {});
@@ -332,7 +339,16 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
332
339
  if (dropped) store.save();
333
340
  return Object.values(heavyTokens()).reduce((a, t) => ({ cpus: a.cpus + t.cpus, mem: a.mem + t.mem, n: a.n + 1 }), { cpus: 0, mem: 0, n: 0 });
334
341
  }
335
- const baseUse = () => activeRecs().reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
342
+ /** #6204: elastic admission charges a lane its measured footprint (cfg.elastic_base floor, raised to the mean live usage of the running lanes), never above what it asked for. */
343
+ function elasticBase() {
344
+ const fl = { cpus: cfg.elastic_base?.cpus ?? 0.4, mem: cfg.elastic_base?.mem_gb ?? 0.3 };
345
+ const us = activeRecs().map((r) => r.usage).filter((u) => u?.samples >= 3);
346
+ if (!us.length) return fl;
347
+ const mean = (k) => us.reduce((a, u) => a + u[k] / u.samples, 0) / us.length;
348
+ return { cpus: Math.max(fl.cpus, mean("cpu_sum")), mem: Math.max(fl.mem, mean("mem_sum")) };
349
+ }
350
+ const charge = (cpus, mem, base = elastic() ? elasticBase() : null) => (base ? { cpus: Math.min(cpus, base.cpus), mem: Math.min(mem, base.mem) } : { cpus, mem });
351
+ const baseUse = () => { const b = elastic() ? elasticBase() : null; return activeRecs().reduce((a, r) => { const c = charge(r.cpus, r.mem_gb, b); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); };
336
352
  /** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
337
353
  const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
338
354
  /** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
@@ -365,9 +381,9 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
365
381
  function heavyView() {
366
382
  if (!elastic()) return {};
367
383
  const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
368
- return { elastic_lanes: true, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
384
+ return { elastic_lanes: true, elastic_base: { cpus: r2(elasticBase().cpus), mem_gb: r2(elasticBase().mem) }, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
369
385
  }
370
- const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
386
+ const sumRecs = (rs) => { const b = elastic() ? elasticBase() : null; return rs.reduce((a, s) => { const c = charge(s.cpus, s.mem_gb, b); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); }; // #6204: elastic lanes are charged their measured base
371
387
  const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
372
388
  const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
373
389
  /** Admission headroom per class: free = physical, unreserved_free = space outside every reservation, borrowable = what `borrow` may take. */
@@ -554,7 +570,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
554
570
  const reservation = prio === "reserved" ? (spec.reservation ?? (reservations().length === 1 ? reservations()[0].name : null)) : null;
555
571
  const c = capacity();
556
572
  const h = live(cfg);
557
- const adm = admit({ prio, cpus, mem_gb, reservation, h });
573
+ const adm = admit({ prio, cpus: charge(cpus, mem_gb).cpus, mem_gb: charge(cpus, mem_gb).mem, reservation, h }); // #6204
558
574
  if (c.draining && !c.paused) return { status: 503, body: { error: `draining: ${c.draining_reason}`, code: "pool.draining", capacity: c }, retryAfter: 60 }; // #6061: finish running lanes, accept none
559
575
  if (laneTargetOn() && !c.paused && c.active >= laneNow()) return { status: 503, body: { error: `lane target ${laneNow()} reached (${c.active} running)`, code: "pool.lane_target", lane_target: laneNow(), capacity: c }, retryAfter: 60 };
560
576
  if (c.paused || adm.refuse) {
@@ -565,7 +581,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
565
581
  // Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
566
582
  // A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
567
583
  if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
568
- const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
584
+ const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), ch = charge(cpus, mem_gb), nm = elastic() ? ch.mem : Math.max(mem_gb, est.mem), nc = elastic() ? ch.cpus : Math.max(cpus, est.cpus);
569
585
  const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
570
586
  if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
571
587
  }
@@ -585,7 +601,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
585
601
  }
586
602
  if (spec.lane_tools?.length) { // #5650 follow-up: never build inside the launch request (router timeout); 503 + retry while it builds
587
603
  let st;
588
- try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
604
+ try { st = await laneImageNow({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker: variantDocker(spec.image ?? image) }); } catch (e) { return { status: 422, body: { error: e.message, code: e.code ?? "lane_tools.invalid" } }; }
589
605
  if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
590
606
  if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
591
607
  }
@@ -627,7 +643,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
627
643
  const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
628
644
  try {
629
645
  // #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
630
- const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
646
+ const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker: variantDocker(spec.image ?? image) }) : (spec.image ?? image);
631
647
  const laneImage = projectImage ?? toolsImage; // #6038: the project layer sits on the tools image, or is skipped (base) while building
632
648
  if (withDocker) {
633
649
  // Private Docker daemon per sandbox (never the host socket). The lane joins its network namespace, so ports the
@@ -1062,7 +1078,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
1062
1078
  const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
1063
1079
  log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
1064
1080
  // #6166: present (pre-seeded) -> pull the published image -> local build only as the fallback
1065
- const how = await provideLaneImage({ docker, image: nextImage, version: want.version, recipe: want.image, publishable: nextImage === laneImageTag(want.version), log,
1081
+ const pub = nextImage === laneImageTag(want.version) ? await fetchDigest(want.version) : null; // #6185: pull by the publisher-recorded digest
1082
+ const how = await provideLaneImage({ docker, image: nextImage, version: want.version, recipe: want.image, digest: pub?.digest, publishable: nextImage === laneImageTag(want.version), log, pinOpts,
1066
1083
  build: () => buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version, want.image)), { log }) }); // #5919
1067
1084
  log.info?.(`${nextImage}: ${how}`);
1068
1085
  }
@@ -1233,7 +1250,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
1233
1250
 
1234
1251
  /** Build the lane image for the running ForgeDock version when this host does not have it yet. */
1235
1252
  async function ensureImage() {
1236
- await provideLaneImage({ docker, image, version: running.version, recipe: running.image, publishable: image === laneImageTag(running.version), log,
1253
+ const pub = image === laneImageTag(running.version) && !(await docker.hasImage?.(image)) ? await fetchDigest(running.version) : null; // #6185
1254
+ await provideLaneImage({ docker, image, version: running.version, recipe: running.image, digest: pub?.digest, publishable: image === laneImageTag(running.version), log, pinOpts,
1237
1255
  build: () => docker.build(join(cfg.code_root ?? repoRoot, "pool", "image"), image, laneBuildArgs(running.version, running.image)) });
1238
1256
  await pruneLaneImages();
1239
1257
  }
@@ -0,0 +1,23 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6195: on WSL2 mirrored networking dockerd's resolver (the WSL proxy, 10.255.255.254) can fail while the host resolver works.
4
+ import { readFileSync, writeFileSync } from "node:fs";
5
+
6
+ /** dockerd's own resolver failing: "lookup ghcr.io on 10.255.255.254:53: no such host" / "server misbehaving". */
7
+ export const DNS_FAIL_RE = /lookup \S+ on [0-9a-f.:]+:53: (no such host|server misbehaving)/i;
8
+
9
+ /**
10
+ * Write public resolvers into daemon.json `dns` (other keys kept; a `dns` already set is left alone), then restart docker
11
+ * only while the agent is idle. Returns {changed, restarted}. Never throws on an unreadable/unwritable file: reports no change.
12
+ */
13
+ export async function ensureDaemonDns({ file = "/etc/docker/daemon.json", dns = ["1.1.1.1", "8.8.8.8"], restart = async () => {}, idle = () => false, log = null } = {}) {
14
+ let cfg = {};
15
+ try { cfg = JSON.parse(readFileSync(file, "utf8") || "{}"); } catch (e) { if (e?.code !== "ENOENT") { log?.warn?.(`daemon.json unreadable: ${e.message}`); return { changed: false, restarted: false }; } }
16
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) return { changed: false, restarted: false };
17
+ if (Array.isArray(cfg.dns) && cfg.dns.length) return { changed: false, restarted: false };
18
+ try { writeFileSync(file, `${JSON.stringify({ ...cfg, dns }, null, 2)}\n`); } catch (e) { log?.warn?.(`cannot write ${file}: ${e.message}`); return { changed: false, restarted: false }; }
19
+ log?.info?.(`docker daemon DNS set to ${dns.join(", ")} in ${file}`);
20
+ if (!idle()) { log?.warn?.("docker not restarted: sandboxes are running; the new DNS applies at the next restart"); return { changed: true, restarted: false }; }
21
+ try { await restart(); } catch (e) { log?.warn?.(`docker restart failed: ${e.message}`); return { changed: true, restarted: false }; }
22
+ return { changed: true, restarted: true };
23
+ }
@@ -11,10 +11,11 @@ export const cpuQuotaEnv = (cpus) => (Number.isFinite(cpus) && cpus > 0 ? { CS_C
11
11
  export const SWEEP_TIMEOUT_MS = 10 * 60000;
12
12
  const SWEEP_SRC = new URL("./cache-sweep.mjs", import.meta.url);
13
13
 
14
- function docker(args, { timeoutMs = 120000 } = {}) {
14
+ /** #6189: `keepTail` keeps the END of stderr (a build error's useful part), not the head. */
15
+ function docker(args, { timeoutMs = 120000, keepTail = false } = {}) {
15
16
  return new Promise((resolve, reject) => {
16
17
  execFile("docker", args, { timeout: timeoutMs, maxBuffer: 16 << 20 }, (err, stdout, stderr) => {
17
- if (err) { err.stderr = String(stderr ?? "").slice(0, 2000); reject(err); } else resolve(String(stdout).trim());
18
+ if (err) { const t = String(stderr ?? ""); err.stderr = keepTail ? t.slice(-4000) : t.slice(0, 2000); reject(err); } else resolve(String(stdout).trim());
18
19
  });
19
20
  });
20
21
  }
@@ -84,6 +85,7 @@ export const dockerCli = {
84
85
  /** #6166: retags a local image (the pulled ghcr.io image becomes forgedock-lane:<version>). */
85
86
  async tag(src, dst) { return docker(["tag", src, dst], { timeoutMs: 30000 }); },
86
87
  /** #6166: one label of a local image ("" when unset or the image is missing). */
88
+ async imageRepoDigests(ref) { try { const j = JSON.parse(await docker(["image", "inspect", "--format", "{{json .RepoDigests}}", ref], { timeoutMs: 20000 })); return Array.isArray(j) ? j : []; } catch { return []; } },
87
89
  async imageLabel(ref, label) { try { return await docker(["image", "inspect", "--format", `{{index .Config.Labels "${label}"}}`, ref], { timeoutMs: 20000 }); } catch { return ""; } },
88
90
  async load(file) { return docker(["load", "-q", "-i", file], { timeoutMs: 30 * 60000 }); },
89
91
  async hasImage(ref) { try { await docker(["image", "inspect", ref], { timeoutMs: 20000 }); return true; } catch { return false; } },
@@ -101,7 +103,7 @@ export const dockerCli = {
101
103
  }
102
104
  return res;
103
105
  },
104
- async build(dir, tag, buildArgs = {}) { return docker(["build", "-q", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000 }); },
106
+ async build(dir, tag, buildArgs = {}) { return docker(["build", "--progress=plain", "-t", tag, ...Object.entries(buildArgs).flatMap(([k, v]) => ["--build-arg", `${k}=${v}`]), dir], { timeoutMs: 45 * 60000, keepTail: true }); },
105
107
  /** #5696: removes one lane worktree (/cache/work/<id>) from a cache volume. */
106
108
  async removeWorkDir(volume, image, workDir) { await docker(["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "--entrypoint", "sh", image, "-c", 'rm -rf -- "$1"', "sh", workDir], { timeoutMs: SWEEP_TIMEOUT_MS }); },
107
109
  /** #5696: removes every /cache/work/* dir of a cache volume except the kept ones (full paths). */
@@ -11,7 +11,7 @@ import { tmpDir } from "../tests/_tmp.mjs";
11
11
  const quiet = { info() {}, warn() {}, error() {} };
12
12
  const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
13
13
  const spec = (id, extra = {}) => ({ id, issue: 1, batch: "b", repo: { slug: "o/x", url: "https://github.com/o/x.git" }, command: ["x"], ...extra });
14
- const TARGET = "1.67.0"; // the router's own target: this repo's package.json version (asserted below)
14
+ const TARGET = JSON.parse((await import("node:fs")).readFileSync("package.json", "utf8")).version; // the router's own target: this repo's package.json version (asserted below)
15
15
 
16
16
  // `old` has more free cpus, so capacity order alone would pick it.
17
17
  function fixture({ oldFree = true, newFree = true } = {}) {
@@ -87,7 +87,7 @@ test("cmpVersion is numeric, agents without a version never lag", () => {
87
87
  test("upgradeAgentsAfterUpdate names agents left behind and keeps its string result", async () => {
88
88
  const warned = [], dir = tmpDir("cs-eng-cfg-"), cfgPath = `${dir}/router.json`;
89
89
  (await import("node:fs")).writeFileSync(cfgPath, "{}");
90
- const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, warn: (m) => warned.push(m),
90
+ const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, ensureRouterFresh: async () => ({ ok: true }), warn: (m) => warned.push(m),
91
91
  leftBehind: async () => ({ target: "1.67.0", rows: [{ name: "old", version: "1.66.0" }] }) });
92
92
  assert.equal(r, "upgraded");
93
93
  assert.match(warned[0], /left behind.*old 1\.66\.0/);
@@ -18,3 +18,16 @@ describe("#6037 image manifest", () => {
18
18
  assert.ok(!manifestProvides(loadImageManifest(join(d, "nope.json")), "yq"));
19
19
  });
20
20
  });
21
+
22
+ describe("#6187 variant remote refs", () => {
23
+ it("remoteVariantImage maps the local tag to ghcr and pullVariantImage retags it", async () => {
24
+ const { remoteVariantImage, pullVariantImage, LANE_REGISTRY_IMAGE } = await import("./lane-image.mjs");
25
+ const { laneToolsTag } = await import("./lane-tools.mjs");
26
+ const tag = laneToolsTag("forgedock-lane:1.2.3", ["xvfb"]);
27
+ assert.equal(remoteVariantImage("1.2.3", tag), `${LANE_REGISTRY_IMAGE}:1.2.3${tag.slice(tag.lastIndexOf("-t"))}`);
28
+ assert.match(remoteVariantImage("1.2.3", tag), /:1\.2\.3-t[0-9a-f]{12}$/);
29
+ const seen = [], docker = { pull: async (r) => seen.push(["pull", r]), tag: async (a, b) => seen.push(["tag", a, b]) };
30
+ await pullVariantImage({ docker, tag, version: "1.2.3" });
31
+ assert.deepEqual(seen, [["pull", remoteVariantImage("1.2.3", tag)], ["tag", remoteVariantImage("1.2.3", tag), tag]]);
32
+ });
33
+ });