forgedock 1.67.0 → 1.68.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 (140) hide show
  1. package/bin/config-schema.mjs +1 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +99 -12
  4. package/bin/engine.mjs +10 -0
  5. package/bin/forgedock.mjs +17 -1
  6. package/bin/help-text.mjs +1 -0
  7. package/bin/lean/admission.mjs +21 -0
  8. package/bin/lean/admission.test.mjs +30 -0
  9. package/bin/lean/advisory.test.mjs +25 -10
  10. package/bin/lean/amendment-schema.mjs +3 -4
  11. package/bin/lean/attempts.mjs +34 -31
  12. package/bin/lean/attempts.test.mjs +33 -19
  13. package/bin/lean/basered.mjs +26 -0
  14. package/bin/lean/batch-health.mjs +17 -12
  15. package/bin/lean/batch-health.test.mjs +39 -11
  16. package/bin/lean/batch.test.mjs +51 -2
  17. package/bin/lean/ci-gate.mjs +2 -90
  18. package/bin/lean/ci-gate.test.mjs +1 -127
  19. package/bin/lean/ci-precheck.mjs +25 -8
  20. package/bin/lean/ci-precheck.test.mjs +24 -0
  21. package/bin/lean/clear-breaker.test.mjs +4 -3
  22. package/bin/lean/commentstate.mjs +10 -5
  23. package/bin/lean/commentstate.test.mjs +12 -1
  24. package/bin/lean/conformance.e2e.test.mjs +9 -6
  25. package/bin/lean/conformance.mjs +56 -196
  26. package/bin/lean/conformance.test.mjs +40 -376
  27. package/bin/lean/depcache.mjs +100 -10
  28. package/bin/lean/depcache.test.mjs +105 -0
  29. package/bin/lean/docsgate.mjs +0 -32
  30. package/bin/lean/docsgate.test.mjs +2 -23
  31. package/bin/lean/effects-cap.test.mjs +9 -1
  32. package/bin/lean/effects-killtree.test.mjs +35 -0
  33. package/bin/lean/effects.mjs +42 -24
  34. package/bin/lean/engine-readmit.test.mjs +35 -0
  35. package/bin/lean/envgap.mjs +93 -0
  36. package/bin/lean/envgap.test.mjs +53 -0
  37. package/bin/lean/execution.mjs +10 -4
  38. package/bin/lean/execution.test.mjs +12 -0
  39. package/bin/lean/failure-census.mjs +170 -0
  40. package/bin/lean/failure-census.test.mjs +59 -0
  41. package/bin/lean/guardgate.test.mjs +2 -3
  42. package/bin/lean/heavy.mjs +33 -4
  43. package/bin/lean/heavy.test.mjs +38 -6
  44. package/bin/lean/hotarea.mjs +0 -36
  45. package/bin/lean/hotarea.test.mjs +1 -22
  46. package/bin/lean/issuewatch-verify.mjs +19 -4
  47. package/bin/lean/issuewatch.mjs +21 -4
  48. package/bin/lean/issuewatch.test.mjs +48 -1
  49. package/bin/lean/lane-audit-gap.mjs +66 -0
  50. package/bin/lean/lane-audit-gap.test.mjs +59 -0
  51. package/bin/lean/lane-audit-llm.mjs +5 -0
  52. package/bin/lean/lane-audit-query.mjs +47 -0
  53. package/bin/lean/lane-audit-query.test.mjs +44 -0
  54. package/bin/lean/lane-audit-signatures.mjs +33 -0
  55. package/bin/lean/lane-audit.mjs +110 -0
  56. package/bin/lean/lane-audit.test.mjs +97 -0
  57. package/bin/lean/lane-recovery.test.mjs +33 -0
  58. package/bin/lean/lanecheck.mjs +5 -3
  59. package/bin/lean/lanecheck.test.mjs +6 -0
  60. package/bin/lean/lean.mjs +206 -148
  61. package/bin/lean/lean.test.mjs +406 -190
  62. package/bin/lean/limits.mjs +17 -0
  63. package/bin/lean/limits.test.mjs +15 -1
  64. package/bin/lean/live-execution.mjs +21 -2
  65. package/bin/lean/live-execution.test.mjs +39 -0
  66. package/bin/lean/orchestrate-attempts.test.mjs +17 -9
  67. package/bin/lean/orchestrate-envhold.test.mjs +47 -0
  68. package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
  69. package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
  70. package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
  71. package/bin/lean/orchestrate-pause.test.mjs +53 -1
  72. package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
  73. package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
  74. package/bin/lean/orchestrate-stacking.test.mjs +10 -0
  75. package/bin/lean/orchestrate.mjs +188 -33
  76. package/bin/lean/postdeploy-check.test.mjs +1 -3
  77. package/bin/lean/precheck.mjs +20 -0
  78. package/bin/lean/preflight.mjs +100 -11
  79. package/bin/lean/preflight.test.mjs +44 -4
  80. package/bin/lean/prompts.mjs +10 -21
  81. package/bin/lean/recurrence.mjs +6 -148
  82. package/bin/lean/recurrence.test.mjs +11 -147
  83. package/bin/lean/release-flakes.mjs +14 -2
  84. package/bin/lean/release-flakes.test.mjs +17 -1
  85. package/bin/lean/release-ledger.mjs +19 -1
  86. package/bin/lean/release-ledger.test.mjs +23 -0
  87. package/bin/lean/release-preflight.mjs +28 -0
  88. package/bin/lean/release-preflight.test.mjs +42 -1
  89. package/bin/lean/release-review.mjs +40 -5
  90. package/bin/lean/release-review.test.mjs +43 -2
  91. package/bin/lean/release.mjs +43 -14
  92. package/bin/lean/release.test.mjs +32 -0
  93. package/bin/lean/retry.mjs +1 -1
  94. package/bin/lean/retry.test.mjs +6 -1
  95. package/bin/lean/rotator.mjs +9 -0
  96. package/bin/lean/rotator.test.mjs +11 -1
  97. package/bin/lean/sandbox-remote.mjs +16 -9
  98. package/bin/lean/schedd.mjs +11 -6
  99. package/bin/lean/schedd.test.mjs +65 -5
  100. package/bin/lean/selfreview.mjs +1 -1
  101. package/bin/lean/statuscomment.mjs +4 -1
  102. package/bin/lean/validate-catalog.mjs +108 -0
  103. package/bin/lean/validate-catalog.test.mjs +46 -1
  104. package/bin/lean/verify.mjs +1 -1
  105. package/bin/pool/affinity.test.mjs +91 -0
  106. package/bin/pool/agent.mjs +143 -9
  107. package/bin/pool/cache-sweep.mjs +31 -10
  108. package/bin/pool/ci-autoscale.mjs +160 -0
  109. package/bin/pool/cli.mjs +37 -8
  110. package/bin/pool/docker.mjs +3 -0
  111. package/bin/pool/engine-placement.test.mjs +94 -0
  112. package/bin/pool/lane-target.mjs +41 -0
  113. package/bin/pool/lane-tools.mjs +7 -2
  114. package/bin/pool/lane-tools.test.mjs +9 -0
  115. package/bin/pool/mirror-seed.mjs +15 -11
  116. package/bin/pool/router.mjs +88 -32
  117. package/bin/pool/version.mjs +29 -2
  118. package/bin/review-staging.mjs +11 -3
  119. package/bin/runner.mjs +59 -11
  120. package/bin/stats/release.mjs +7 -0
  121. package/bin/stats/release.test.mjs +20 -0
  122. package/bin/stats/scorecard.mjs +187 -0
  123. package/bin/stats/scorecard.test.mjs +89 -0
  124. package/docs/CONFIG.md +41 -0
  125. package/docs/OUTCOME-CODES.md +1 -0
  126. package/docs/STATS.md +17 -0
  127. package/package.json +1 -1
  128. package/pool/image/Dockerfile +14 -2
  129. package/pool/image/manifest.json +25 -0
  130. package/pool/image/mirror.sh +11 -2
  131. package/pool/install/install-agent.ps1 +11 -4
  132. package/scripts/ci-local/adapters/github-actions.mjs +8 -0
  133. package/scripts/ci-local/cli.mjs +1 -1
  134. package/scripts/ci-local/plan.mjs +3 -2
  135. package/scripts/ci-local.test.sh +11 -0
  136. package/scripts/failure-census.mjs +67 -0
  137. package/scripts/review-finalize.sh +5 -5
  138. package/scripts/review-finalize.test.sh +8 -1
  139. package/scripts/verify-phase-trail.sh +11 -0
  140. package/scripts/verify-phase-trail.test.sh +9 -0
@@ -4,7 +4,7 @@
4
4
  // itself runs inside a short-lived container of the lane image with the cache volume on /cache. The agent ships this
5
5
  // file's source in CS_CACHE_SWEEP_SRC and the options in CS_CACHE_SWEEP_OPTS; the JSON result goes to stdout.
6
6
  import { execFileSync } from "node:child_process";
7
- import { existsSync, readFileSync, rmSync } from "node:fs";
7
+ import { existsSync, readFileSync, rmSync, statSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
 
10
10
  export const CACHE_LABEL = "computeshare.cache=1";
@@ -15,6 +15,7 @@ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-
15
15
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
16
16
  export const agentLabel = (id) => `computeshare.agent=${id}`;
17
17
  const DAY = 86400000;
18
+ const LOCK_LIVE_MS = 2 * 3600000; // a depcache key lock younger than this may belong to a running install or lane
18
19
 
19
20
  /**
20
21
  * Oldest-first deletion plan to bring `entries` ({path, bytes, mtimeMs, live}) under `capBytes`. Live entries (the work
@@ -55,22 +56,42 @@ const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
55
56
  const kids = (dir) => sh("find", [dir, "-mindepth", "1", "-maxdepth", "1", "-printf", "%p\t%T@\n"]).split("\n").filter(Boolean).map((l) => { const i = l.lastIndexOf("\t"); return { path: l.slice(0, i), mtimeMs: Number(l.slice(i + 1)) * 1000 }; });
56
57
 
57
58
  const SNAP = /^[a-z]+-[0-9a-f]{16}$/;
59
+ const num = (p) => { try { const n = Number(readFileSync(p, "utf8").trim()); return Number.isFinite(n) && n > 0 ? n : null; } catch { return null; } };
60
+ const mtimeOf = (p) => { try { return statSync(p).mtimeMs; } catch { return null; } };
61
+ /** #5898: a snapshot is in use while its `<snap>.lock` is younger than LOCK_LIVE_MS (the container cannot check pids). */
62
+ const lockLive = (p, now) => { const m = mtimeOf(`${p}.lock`); return m !== null && now - m < LOCK_LIVE_MS; };
58
63
  /** Last use of a depcache snapshot: its `last-used` file (epoch ms, written on every hit), else the directory mtime. */
59
- const snapLastUsed = (k) => { try { const n = Number(readFileSync(join(k.path, "last-used"), "utf8").trim()); if (n > 0) return n; } catch { /* none yet */ } return k.mtimeMs; };
64
+ const snapLastUsed = (k) => {
65
+ let created = null;
66
+ try { created = Number(JSON.parse(readFileSync(join(k.path, "manifest.json"), "utf8")).created) || null; } catch { /* no manifest */ }
67
+ return num(join(k.path, "last-used")) ?? created ?? k.mtimeMs;
68
+ };
69
+ /** Every depcache snapshot as {path, lastUsedMs, live}; last use falls back to manifest `created`, then mtime. */
70
+ function depcacheSnaps(dc, now) {
71
+ const out = [];
72
+ for (const repo of kids(dc)) {
73
+ if (repo.path.endsWith("/stores")) continue;
74
+ for (const k of kids(repo.path)) {
75
+ if (!SNAP.test(k.path.slice(repo.path.length + 1))) continue;
76
+ out.push({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) });
77
+ }
78
+ }
79
+ return out;
80
+ }
60
81
 
61
82
  /**
62
83
  * #5901: depcache is `<dc>/<repoKey>/<eco>-<key>/`. Each snapshot (not the repo dir, whose mtime moves with every new
63
84
  * snapshot) ages out by its last use and is trimmed least-recently-used past the per-repo cap. A snapshot with a lock file
64
85
  * is in use and kept. Fills `depcacheBytes[repoKey]` with what remains.
65
86
  */
66
- function sweepDepcache(dc, { cutoff, capBytes, rm, depcacheBytes }) {
87
+ function sweepDepcache(dc, { cutoff, now, capBytes, rm, depcacheBytes }) {
67
88
  for (const repo of kids(dc)) {
68
89
  const rk = repo.path.slice(dc.length + 1);
69
90
  if (rk === "stores") continue;
70
- if (SNAP.test(rk)) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
91
+ if (SNAP.test(rk)) { if (snapLastUsed(repo) < cutoff && !lockLive(repo.path, now)) rm(repo.path); continue; } // an entry of the flat layout (no repo level)
71
92
  let snaps = kids(repo.path).filter((k) => SNAP.test(k.path.slice(repo.path.length + 1)));
72
- const live = (k) => existsSync(`${k.path}.lock`);
73
- snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: live(k) }));
93
+ for (const k of kids(repo.path)) if (/\.(tmp-\d+|lock)$/.test(k.path) && k.mtimeMs < cutoff) rm(k.path); // dead publishers' tmp dirs, old locks
94
+ snaps = snaps.map((k) => ({ ...k, lastUsedMs: snapLastUsed(k), live: lockLive(k.path, now) }));
74
95
  for (const k of snaps.filter((x) => x.lastUsedMs < cutoff && !x.live)) rm(k.path);
75
96
  snaps = snaps.filter((x) => existsSync(x.path));
76
97
  if (!snaps.length) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // nothing left in it and untouched for the max age
@@ -94,7 +115,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
94
115
  const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
95
116
  const dc = join(root, "forge-depcache");
96
117
  const depcacheBytes = {};
97
- if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
118
+ if (existsSync(dc)) { ageOut(join(dc, "stores")); sweepDepcache(dc, { cutoff, now, capBytes: Number.isFinite(maxDepcacheGb) ? maxDepcacheGb * 1024 ** 3 : null, rm, depcacheBytes }); } // store entries, then snapshots per repo
98
119
  if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
99
120
  const ps = join(root, "pnpm-store");
100
121
  if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
@@ -103,12 +124,12 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ma
103
124
  const entries = [];
104
125
  const keepSet = new Set(keep);
105
126
  for (const k of kids(join(root, "work"))) entries.push({ ...k, bytes: sizeOf(k.path), live: keepSet.has(k.path) });
106
- for (const d of [...PACKAGE_STORES, "env", "forge-depcache", "forge-depcache/stores"]) for (const k of kids(join(root, d))) if (!k.path.endsWith("/stores")) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
127
+ for (const d of [...PACKAGE_STORES, "env", "forge-depcache/stores"]) for (const k of kids(join(root, d))) entries.push({ ...k, bytes: sizeOf(k.path), live: false });
128
+ for (const k of depcacheSnaps(dc, now)) entries.push({ path: k.path, mtimeMs: k.lastUsedMs, bytes: sizeOf(k.path), live: k.live });
107
129
  const plan = planCacheCap(entries, maxGb * 1024 ** 3);
108
130
  for (const p of plan.delete) rm(p);
109
131
  }
110
- let last = null;
111
- try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
132
+ const lastSec = num(join(root, ".last-used")), last = lastSec === null ? null : lastSec * 1000;
112
133
  return { size_bytes: sizeOf(root), last_used_ms: last, depcache_bytes: depcacheBytes, removed: removed.length, errors: errors.slice(0, 5) };
113
134
  }
114
135
 
@@ -0,0 +1,160 @@
1
+ // #5695: demand- and capacity-driven CI runner autoscaler for the pool router. The decision logic (admitRunner, planScale,
2
+ // runnerPriority, decisionRecord) is pure; createAutoscaler wires it to the router's webhook, tick and agents.
3
+ // Imports stay inside bin/pool: the router ships agents only AGENT_BUNDLE_PATHS (pool-agent-bundle.test.mjs).
4
+
5
+ /** Priority classes, lowest number first: deploy > release-PR CI > lanes > ordinary PR CI. */
6
+ export const PRIORITY = { deploy: 0, release: 1, lane: 2, pr: 3 };
7
+ export const DEFAULT_FLOORS = { mem_available_gb: 3, load_per_cpu: 0.8, lane_cpus: 2, lane_mem_gb: 3, net_rx_mbps_max: null };
8
+ export const DEFAULT_SIZE = { cpus: 1, mem_gb: 2 };
9
+
10
+ const num = (v, d) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : d);
11
+
12
+ /** Deploy labels and an explicit job.priority win; a release branch or job.release is release CI; the rest is PR CI. */
13
+ export function runnerPriority(job = {}) {
14
+ if (Number.isInteger(job.priority) && job.priority >= 0 && job.priority <= PRIORITY.pr) return job.priority;
15
+ if (/deploy/i.test(String(job.label ?? "")) || (job.labels ?? []).some((l) => /deploy/i.test(l))) return PRIORITY.deploy;
16
+ if (job.release === true || /^(release|hotfix)[/-]/i.test(String(job.head_branch ?? ""))) return PRIORITY.release;
17
+ return PRIORITY.pr;
18
+ }
19
+
20
+ /** One telemetry record per decision, carrying every input it was made from. */
21
+ export function decisionRecord({ action, label, job = null, admit = null, reason, inputs = {}, dry_run = false, at = null }) {
22
+ return { at, action, label, job: job?.id ?? null, priority: job ? runnerPriority(job) : null, admit, reason, dry_run, inputs };
23
+ }
24
+
25
+ /**
26
+ * Does one more runner fit? free = {mem_available_gb, load_per_cpu, vcpus, cpus_free, mem_free_gb}; reserved = what earlier
27
+ * admissions of this round already took; net = {rx_mbps}. The lane floor keeps cpus_free/mem_free_gb for lanes at every
28
+ * priority, so CI never blocks a lane beyond it.
29
+ */
30
+ export function admitRunner({ free, floors = {}, reserved = {}, job = {}, net = null, size = null }) {
31
+ const f = { ...DEFAULT_FLOORS, ...floors }, sz = size ?? job.size ?? DEFAULT_SIZE;
32
+ const rc = num(reserved.cpus, 0), rm = num(reserved.mem_gb, 0), vcpus = Math.max(1, num(free.vcpus, 1));
33
+ const after = {
34
+ mem_available_gb: num(free.mem_available_gb, Infinity) - rm - sz.mem_gb,
35
+ load_per_cpu: num(free.load_per_cpu, 0) + (rc + sz.cpus) / vcpus,
36
+ cpus_free: num(free.cpus_free, Infinity) - rc - sz.cpus,
37
+ mem_free_gb: num(free.mem_free_gb, Infinity) - rm - sz.mem_gb,
38
+ };
39
+ const inputs = { free, floors: f, reserved: { cpus: rc, mem_gb: rm }, size: sz, after, ...(net ? { net } : {}) };
40
+ const no = (reason) => ({ admit: false, reason, inputs });
41
+ if (after.mem_available_gb < f.mem_available_gb) return no(`MemAvailable ${after.mem_available_gb.toFixed(1)} GB after reservation < floor ${f.mem_available_gb}`);
42
+ if (after.load_per_cpu > f.load_per_cpu) return no(`load ${after.load_per_cpu.toFixed(2)}/cpu after reservation > ${f.load_per_cpu}`);
43
+ if (after.cpus_free < f.lane_cpus || after.mem_free_gb < f.lane_mem_gb) return no("lane floor: reservation would leave lanes less than the configured floor");
44
+ const rx = num(net?.rx_mbps, null);
45
+ if (f.net_rx_mbps_max && rx !== null && rx > f.net_rx_mbps_max && runnerPriority(job) > PRIORITY.deploy) return no(`network ${rx} MB/s > ${f.net_rx_mbps_max} (saturated)`);
46
+ return { admit: true, reason: "fits", inputs };
47
+ }
48
+
49
+ const inWindow = (window, t) => (window ?? []).find((w) => Number(w.from) <= t && t < Number(w.to)) ?? null;
50
+
51
+ /**
52
+ * Decide this round's runner starts and stops.
53
+ * demand: {label: [job]} queued jobs; running: {label: {total, busy}}; labels: {label: {min, max, size}};
54
+ * lanes: {waiting} (a waiting lane outranks ordinary PR CI); window: [{from,to}] maintenance windows in epoch ms.
55
+ * Returns decision records; `start`/`stop` ones are actionable. Candidates are admitted in priority order.
56
+ */
57
+ export function planScale({ demand = {}, running = {}, labels = {}, lanes = {}, window = [], free, floors = {}, net = null, now = 0, dry_run = false }) {
58
+ const out = [], rec = (d) => out.push(decisionRecord({ at: now, dry_run, ...d }));
59
+ const win = inWindow(window, now), cand = [];
60
+ for (const [label, cfg] of Object.entries(labels)) {
61
+ const queued = demand[label] ?? [], r = running[label] ?? { total: 0, busy: 0 };
62
+ const min = num(cfg.min, 0), max = num(cfg.max, 0), size = cfg.size ?? DEFAULT_SIZE, idle = Math.max(0, r.total - r.busy);
63
+ const ctx = { queued: queued.length, total: r.total, busy: r.busy, idle, min, max, size };
64
+ const want = Math.min(Math.max(queued.length - idle, min - r.total, 0), Math.max(0, max - r.total));
65
+ const jobs = [...queued].sort((a, b) => runnerPriority({ label, ...a }) - runnerPriority({ label, ...b }));
66
+ for (let i = 0; i < want; i++) cand.push({ label, size, job: { label, ...(jobs[i] ?? { id: null }) }, ctx });
67
+ const keep = Math.max(min, queued.length), surplus = Math.max(0, idle - Math.max(0, keep - r.busy));
68
+ if (surplus > 0 && !win) rec({ action: "stop", label, admit: true, reason: `${surplus} idle runner(s) above max(min, queued)`, inputs: { ...ctx, surplus } });
69
+ else if (want === 0) rec({ action: "hold", label, admit: null, reason: "no runner needed", inputs: ctx });
70
+ }
71
+ cand.sort((a, b) => runnerPriority(a.job) - runnerPriority(b.job));
72
+ const reserved = { cpus: 0, mem_gb: 0 };
73
+ for (const c of cand) {
74
+ if (win) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: `maintenance window${win.why ? `: ${win.why}` : ""}`, inputs: { ...c.ctx, window: win } }); continue; }
75
+ if ((lanes.waiting ?? 0) > 0 && runnerPriority(c.job) > PRIORITY.lane) { rec({ action: "hold", label: c.label, job: c.job, admit: false, reason: "a lane is waiting and outranks ordinary PR CI", inputs: { ...c.ctx, lanes } }); continue; }
76
+ const v = admitRunner({ free, floors, reserved, job: c.job, net, size: c.size });
77
+ if (v.admit) { reserved.cpus += c.size.cpus; reserved.mem_gb += c.size.mem_gb; }
78
+ rec({ action: v.admit ? "start" : "hold", label: c.label, job: c.job, admit: v.admit, reason: v.reason, inputs: { ...v.inputs, ...c.ctx } });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /**
84
+ * Router-side controller. `ingest` takes a GitHub workflow_job payload (queued/in_progress/completed); `reconcile` (router
85
+ * tick) polls the jobs API as a fallback, plans, and asks an agent to start or stop ephemeral JIT runners. Off by default;
86
+ * dry_run logs every decision and starts nothing.
87
+ */
88
+ export function createAutoscaler({ cfg = {}, now, log, capacities, agentCall, githubToken, fetchFn, agents }) {
89
+ const c = cfg.ci_autoscale ?? {};
90
+ const jobs = new Map(); // job id -> {id,label,status,runner,head_branch,at}
91
+ const decisions = [];
92
+ let lastPoll = -Infinity, seq = 0;
93
+ const labelOf = (wj) => (wj?.labels ?? []).find((l) => Object.hasOwn(c.labels ?? {}, l)) ?? null;
94
+ const track = (wj) => {
95
+ const label = labelOf(wj);
96
+ if (!label || !Number.isFinite(Number(wj.id))) return null;
97
+ if (wj.status === "completed") { jobs.delete(Number(wj.id)); return { label, status: "completed" }; }
98
+ const j = { id: Number(wj.id), label, labels: wj.labels, status: wj.status === "in_progress" ? "in_progress" : "queued", runner: wj.runner_name ?? null, head_branch: wj.head_branch ?? null, at: now() };
99
+ jobs.set(j.id, j);
100
+ return { label, status: j.status };
101
+ };
102
+ function ingest(body) {
103
+ if (!c.enabled) return { enabled: false, tracked: false };
104
+ const t = body?.workflow_job ? track(body.workflow_job) : null;
105
+ return { enabled: true, tracked: Boolean(t), ...(t ?? {}) };
106
+ }
107
+ const gh = async (path, body) => {
108
+ const r = await fetchFn(`https://api.github.com${path}`, { method: body ? "POST" : "GET", headers: { authorization: `Bearer ${await githubToken()}`, accept: "application/vnd.github+json", ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
109
+ if (!r.ok) throw new Error(`GitHub ${path} -> ${r.status}`);
110
+ return r.json();
111
+ };
112
+ async function poll() {
113
+ if (!c.repo || now() - lastPoll < (c.poll_s ?? 300) * 1000) return;
114
+ lastPoll = now();
115
+ const seen = new Set();
116
+ try {
117
+ const runs = (await gh(`/repos/${c.repo}/actions/runs?status=queued&per_page=20`)).workflow_runs ?? [];
118
+ for (const run of runs) for (const wj of (await gh(`/repos/${c.repo}/actions/runs/${run.id}/jobs?per_page=100`)).jobs ?? []) {
119
+ if (wj.status === "queued" && labelOf(wj)) { seen.add(Number(wj.id)); if (!jobs.has(Number(wj.id))) track({ ...wj, head_branch: wj.head_branch ?? run.head_branch }); }
120
+ }
121
+ for (const [id, j] of jobs) if (j.status === "queued" && !seen.has(id) && now() - j.at > (c.poll_s ?? 300) * 1000) jobs.delete(id); // the API no longer lists it
122
+ } catch (e) { log.warn?.(`ci-autoscale poll: ${e.message}`); }
123
+ }
124
+ const emit = (d) => { decisions.push(d); if (decisions.length > 200) decisions.shift(); log.info?.(`ci-autoscale ${JSON.stringify(d)}`); };
125
+
126
+ async function reconcile() {
127
+ if (!c.enabled) return [];
128
+ for (const [id, j] of jobs) if (now() - j.at > 6 * 3600000) jobs.delete(id); // a lost completed event
129
+ await poll();
130
+ const caps = (await capacities()).filter((x) => x.ok && !x.paused);
131
+ if (!caps.length) return [];
132
+ const host = caps.sort((a, b) => (b.live?.mem_available_gb ?? 0) - (a.live?.mem_available_gb ?? 0))[0];
133
+ const free = { mem_available_gb: host.live?.mem_available_gb, load_per_cpu: host.live?.load_per_core, vcpus: host.vm?.cpus ?? host.cpus_total, cpus_free: host.cpus_free, mem_free_gb: host.mem_free_gb };
134
+ const demand = {}, running = {};
135
+ for (const label of Object.keys(c.labels ?? {})) {
136
+ demand[label] = [...jobs.values()].filter((j) => j.label === label && j.status === "queued");
137
+ const mine = (host.runners ?? []).filter((r) => r.label === label), busyNames = new Set([...jobs.values()].filter((j) => j.status === "in_progress" && j.runner).map((j) => j.runner));
138
+ running[label] = { total: mine.length, busy: mine.filter((r) => busyNames.has(r.name)).length, names: mine.map((r) => r.name).filter((n) => !busyNames.has(n)) };
139
+ }
140
+ const win = (c.windows ?? []).map((w) => ({ from: Date.parse(w.from), to: Date.parse(w.to), why: w.why }));
141
+ const plan = planScale({ demand, running, labels: c.labels, lanes: { waiting: 0 }, window: win, free, floors: { ...c.floors, lane_cpus: c.lane_floor?.cpus ?? c.floors?.lane_cpus, lane_mem_gb: c.lane_floor?.mem_gb ?? c.floors?.lane_mem_gb }, net: host.net ?? null, now: now(), dry_run: Boolean(c.dry_run) });
142
+ for (const d of plan) {
143
+ emit(d);
144
+ if (c.dry_run) continue;
145
+ const a = agents()[host.name];
146
+ try {
147
+ if (d.action === "start") {
148
+ const name = `ci-${d.label}-${now().toString(36)}-${seq++}`.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64);
149
+ const jit = await gh(`/repos/${c.repo}/actions/runners/generate-jitconfig`, { name, runner_group_id: c.runner_group_id ?? 1, labels: ["self-hosted", d.label], work_folder: "_work" });
150
+ const r = await agentCall(a, "POST", "/runners", { name, label: d.label, jitconfig: jit.encoded_jit_config, cpus: d.inputs.size.cpus, mem_gb: d.inputs.size.mem_gb });
151
+ if (!r.ok) log.warn?.(`ci-autoscale start ${name} on ${host.name}: HTTP ${r.status}`);
152
+ } else if (d.action === "stop") {
153
+ for (const n of running[d.label].names.slice(0, d.inputs.surplus)) await agentCall(a, "DELETE", `/runners/${encodeURIComponent(n)}`);
154
+ }
155
+ } catch (e) { log.warn?.(`ci-autoscale ${d.action} ${d.label}: ${e.message}`); }
156
+ }
157
+ return plan;
158
+ }
159
+ return { ingest, reconcile, decisions, jobs };
160
+ }
package/bin/pool/cli.mjs CHANGED
@@ -11,11 +11,12 @@ import { startRouter } from "./router.mjs";
11
11
  import { dockerCli } from "./docker.mjs";
12
12
  import { readSecret } from "./store.mjs";
13
13
  import { call as httpCall } from "./http.mjs";
14
+ import { agentsLeftBehind, leftBehindLine } from "./version.mjs";
14
15
 
15
16
  const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
16
17
  const loadJson = (p) => JSON.parse(readFileSync(p, "utf8"));
17
18
 
18
- const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] | remove <agent> [--config path]";
19
+ const USAGE = "usage: forgedock pool router [install] | enroll [--cpus N --mem GB --agent-url URL | --outbound | --one-liner] | status [--json] [--account A] | link <user_code> [--account A] | policy <agent> [--cpus N --mem GB --idle-only --pause --resume-policy] | limit <agent> --lanes N|none | pause | resume | uninstall [--yes] | upgrade [agent] [--wait [--timeout S] | --now] | remove <agent> [--config path]";
19
20
  const HELP_FLAGS = ["--help", "-h"];
20
21
  // Flags each verb accepts: `value` flags consume the next token, `bool` flags stand alone. Anything else dash-prefixed is rejected (#5008).
21
22
  const VERB_FLAGS = {
@@ -27,7 +28,7 @@ const VERB_FLAGS = {
27
28
  pause: { value: ["--config"], bool: [] },
28
29
  resume: { value: ["--config"], bool: [] },
29
30
  uninstall: { value: [], bool: ["--yes"] },
30
- upgrade: { value: ["--config"], bool: [] },
31
+ upgrade: { value: ["--config", "--timeout"], bool: ["--now", "--wait"] },
31
32
  remove: { value: ["--config"], bool: [] },
32
33
  limit: { value: ["--config", "--lanes"], bool: [] },
33
34
  enroll: { value: ["--config", "--cpus", "--mem", "--agent-url"], bool: ["--outbound", "--one-liner"] },
@@ -63,19 +64,21 @@ const num = (x) => (Number.isFinite(x) ? String(Math.round(x * 10) / 10) : "-");
63
64
  /** #5885: one row per host: used/borrowable/total cpus and memory, lane counts, pause state and why lanes are throttled or drained. */
64
65
  export function statusTable(agents) {
65
66
  const withAccount = agents.some((a) => a.account); // #5886: the column appears only when an agent has an account
66
- const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", "REASON"];
67
+ const withEngine = agents.some((a) => a.engine_version); // the ENGINE column appears only when an agent reports its lane engine
68
+ const head = ["HOST", ...(withAccount ? ["ACCOUNT"] : []), "CPUS used/borrow/total", "MEM GB used/borrow/total", "ACTIVE", "THROTTLED", "PAUSED", ...(withEngine ? ["ENGINE"] : []), "REASON"];
67
69
  const rows = agents.map((a) => {
68
70
  const name = a.name ?? a.host ?? "?";
69
71
  const acct = withAccount ? [a.account ?? "-"] : [];
70
- if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", "-", `unreachable${a.error ? `: ${a.error}` : ""}`];
72
+ if (a.ok === false) return [name, ...acct, "-", "-", "-", "-", ...(withEngine ? ["-"] : []), "-", `unreachable${a.error ? `: ${a.error}` : ""}`];
71
73
  const used = (tot, free) => (Number.isFinite(tot) && Number.isFinite(free) ? tot - Math.max(0, free) : null);
72
74
  const borrow = (b, free) => num(b ?? free);
73
75
  const paused = a.owner_paused ? "owner" : a.paused ? (a.pending_resize ? "resize" : "yes") : "no";
74
76
  const why = [a.owner_paused ? "paused by owner" : null, a.paused && !a.owner_paused && a.pending_resize ? "draining for resize" : null,
77
+ Number.isInteger(a.lane_target) ? `lane target ${a.lane_target}/${a.lane_ceiling ?? "-"}` : null, a.draining && !a.owner_paused && !a.pending_resize ? `draining: ${a.draining_reason ?? "yes"}` : null,
75
78
  a.idle_gate ? `owner busy: ${a.idle_gate}` : null, a.last_drain ? `last drain ${a.last_drain.sandbox} at ${a.last_drain.at}: ${a.last_drain.reason}` : null].filter(Boolean).join("; ");
76
79
  return [name, ...acct, `${num(used(a.cpus_total, a.cpus_free))}/${borrow(a.cpus_borrowable, a.cpus_free)}/${num(a.cpus_total)}`,
77
80
  `${num(used(a.mem_total_gb, a.mem_free_gb))}/${borrow(a.mem_borrowable_gb, a.mem_free_gb)}/${num(a.mem_total_gb)}`,
78
- String(a.active ?? "-"), String(a.throttled ?? 0), paused, why || "-"];
81
+ String(a.active ?? "-"), String(a.throttled ?? 0), paused, ...(withEngine ? [a.engine_version ? `${a.engine_version}${a.engine_skew ? " SKEW" : ""}` : "-"] : []), why || "-"];
79
82
  });
80
83
  const w = head.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
81
84
  return [head, ...rows].map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(w[i]))).join(" ")).join("\n");
@@ -267,12 +270,38 @@ export async function runPoolCli(argv, deps = {}) {
267
270
  // Push the current code (and lane image, when its recipe changed) to one agent or all of them.
268
271
  const cfg = routerConfig();
269
272
  const base = `http://${cfg.listen.host}:${cfg.listen.port}`;
270
- const only = rest.find((x) => !x.startsWith("--") && x !== flag("config"));
271
- const list = (await call(base, "GET", "/agents", { token: cfg.forgedock_token })).data?.agents ?? [];
273
+ const only = rest.find((x) => !x.startsWith("--") && x !== flag("config") && x !== flag("timeout"));
274
+ const now = rest.includes("--now"), wait = rest.includes("--wait");
275
+ const timeoutS = flag("timeout") === undefined ? 1800 : Number(flag("timeout"));
276
+ if (!Number.isFinite(timeoutS) || timeoutS < 0) throw new Error("usage: --timeout takes a number of seconds");
277
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
278
+ const clock = deps.now ?? Date.now;
279
+ const agentsNow = async () => (await call(base, "GET", "/agents", { token: cfg.forgedock_token })).data?.agents ?? [];
280
+ const list = await agentsNow();
272
281
  for (const a of list.filter((x) => !only || x.name === only)) {
273
- const r = await call(base, "POST", `/agents/${encodeURIComponent(a.name)}/upgrade`, { token: cfg.forgedock_token, timeoutMs: 30000 });
282
+ // The pool host is shared: upgrading restarts the agent under live sandboxes, so refuse unless asked (--wait drains, --now forces).
283
+ let active = a.active;
284
+ if (Number(active) > 0 && wait && !now) {
285
+ const deadline = clock() + timeoutS * 1000;
286
+ while (Number(active) > 0) {
287
+ if (clock() >= deadline) throw new Error(`${a.name}: still ${active} active sandbox(es) after ${timeoutS}s; not upgraded`);
288
+ await sleep(deps.pollMs ?? 10000);
289
+ active = (await agentsNow()).find((x) => x.name === a.name)?.active;
290
+ }
291
+ } else if (Number(active) > 0 && !now) {
292
+ throw new Error(`${a.name}: ${active} active sandbox(es) on this shared host; not upgraded. Use --wait to wait for idle, or --now to force.`);
293
+ }
294
+ const r = await call(base, "POST", `/agents/${encodeURIComponent(a.name)}/upgrade`, { body: now ? { force: true } : undefined, token: cfg.forgedock_token, timeoutMs: 30000 });
295
+ if (r.status === 409) throw new Error(`${a.name}: ${r.data?.active ?? "some"} active sandbox(es); not upgraded (HTTP 409)`);
274
296
  console.log(`${a.name}: HTTP ${r.status} ${JSON.stringify(r.data)}`);
275
297
  }
298
+ // R5: name the agents still on an older engine once the pushes are done (an agent restarts asynchronously, so this can lag briefly).
299
+ const behind = deps.leftBehind ? await deps.leftBehind(base, cfg) : deps.call ? [] : await (async () => { // a custom `call` seam is a fixture without /status
300
+ const get = (p) => httpCall(base, "GET", p, { token: cfg.forgedock_token }).catch(() => null);
301
+ const target = (await get("/version"))?.data?.version;
302
+ return agentsLeftBehind((await get("/status"))?.data?.agents, target).map((r) => ({ ...r, target }));
303
+ })();
304
+ if (behind.length) console.log(leftBehindLine(behind, behind[0].target));
276
305
  break;
277
306
  }
278
307
  case "remove": {
@@ -4,6 +4,9 @@ import { execFile } from "node:child_process";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { PACKAGE_STORES } from "./cache-sweep.mjs";
6
6
 
7
+ /** #6047: the lane's CPU quota as env, for lanes whose cgroup files are hidden (read by quotaCores in lean/admission.mjs). */
8
+ export const cpuQuotaEnv = (cpus) => (Number.isFinite(cpus) && cpus > 0 ? { CS_CPU_QUOTA: String(cpus) } : {});
9
+
7
10
  /** #5757: work-dir and cache sweeps walk big trees (node_modules): 10 min, not the 120 s of a small rm. */
8
11
  export const SWEEP_TIMEOUT_MS = 10 * 60000;
9
12
  const SWEEP_SRC = new URL("./cache-sweep.mjs", import.meta.url);
@@ -0,0 +1,94 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ // #6091: engine-version aware placement (prefer the orchestrator's engine, execution.min_lane_engine gate), status skew, left-behind report.
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { createRouter } from "./router.mjs";
7
+ import { statusTable } from "./cli.mjs";
8
+ import { cmpVersion, agentsLeftBehind, upgradeAgentsAfterUpdate } from "./version.mjs";
9
+ import { tmpDir } from "../tests/_tmp.mjs";
10
+
11
+ const quiet = { info() {}, warn() {}, error() {} };
12
+ const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
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)
15
+
16
+ // `old` has more free cpus, so capacity order alone would pick it.
17
+ function fixture({ oldFree = true, newFree = true } = {}) {
18
+ const posts = [];
19
+ const caps = { old: { version: "1.66.0", cpus_free: 8, mem_free_gb: 16 }, new: { version: TARGET, cpus_free: newFree ? 2 : 0, mem_free_gb: newFree ? 16 : 0 } };
20
+ if (!oldFree) caps.old = { version: "1.66.0", cpus_free: 0, mem_free_gb: 0 };
21
+ const fetchFn = async (url, init) => {
22
+ const u = new URL(url), h = u.hostname;
23
+ if (u.pathname === "/capacity") return json(caps[h]);
24
+ posts.push(`${h}${u.pathname}`);
25
+ return json({ id: JSON.parse(init.body).spec.id, state: "running" }, u.pathname === "/warm/claim" ? 200 : 201);
26
+ };
27
+ const router = createRouter({ state_dir: tmpDir("cs-eng-"), lane: { cpus: 2, mem_gb: 3 }, enroll_token: "e", forgedock_token: "fd", repo_root: process.cwd() }, { fetchFn, now: () => 5_000_000, log: quiet });
28
+ router.store.data.agents.old = { url: "http://old:7711", token: "t" };
29
+ router.store.data.agents.new = { url: "http://new:7711", token: "t" };
30
+ return { router, posts };
31
+ }
32
+ const target = async () => (await import("./version.mjs")).versionOf(process.cwd()).version;
33
+ test("fixture target is the router's target", async () => assert.equal(await target(), TARGET));
34
+
35
+ test("launch prefers the agent on the orchestrator engine over one with more free cpus", async () => {
36
+ const { router } = fixture();
37
+ const r = await router.launch(spec("l1"));
38
+ assert.equal(r.status, 201);
39
+ assert.equal(r.body.agent, "new");
40
+ });
41
+
42
+ test("only the old agent free and min_lane_engine unset: the lane runs there and says its engine", async () => {
43
+ const { router } = fixture({ newFree: false });
44
+ const r = await router.launch(spec("l2"));
45
+ assert.equal(r.status, 201);
46
+ assert.equal(r.body.agent, "old");
47
+ assert.equal(r.body.engine_version, "1.66.0");
48
+ });
49
+
50
+ test("min_lane_engine above the only free agent defers with pool.engine_old", async () => {
51
+ const { router, posts } = fixture({ newFree: false });
52
+ const r = await router.launch(spec("l3", { min_lane_engine: "1.67" }));
53
+ assert.equal(r.status, 503);
54
+ assert.equal(r.body.code, "pool.engine_old");
55
+ assert.ok(r.retryAfter > 0);
56
+ assert.deepEqual(posts, []);
57
+ });
58
+
59
+ test("claim follows the same order and gate", async () => {
60
+ const { router, posts } = fixture();
61
+ const c = await router.claim(spec("c1", { min_lane_engine: "1.67" }));
62
+ assert.equal(c.body.agent, "new");
63
+ assert.deepEqual(posts, ["new/warm/claim"]);
64
+ });
65
+
66
+ test("status carries each agent's engine and flags skew; statusTable shows it", async () => {
67
+ const { router } = fixture();
68
+ const s = await router.status();
69
+ const t = await target();
70
+ const old = s.agents.find((a) => a.name === "old");
71
+ assert.equal(old.engine_version, "1.66.0");
72
+ assert.equal(old.engine_skew, cmpVersion("1.66.0", t) < 0);
73
+ const table = statusTable([{ name: "a", ok: true, engine_version: "1.66.0", engine_skew: true }, { name: "b", ok: true, engine_version: TARGET, engine_skew: false }]);
74
+ assert.match(table, /ENGINE/);
75
+ assert.match(table, /1\.66\.0 SKEW/);
76
+ assert.doesNotMatch(table.split("\n")[2], /SKEW/);
77
+ assert.doesNotMatch(statusTable([{ name: "a", ok: true }]), /ENGINE/, "no version info: table as before");
78
+ });
79
+
80
+ test("cmpVersion is numeric, agents without a version never lag", () => {
81
+ assert.ok(cmpVersion("1.10.0", "1.9.9") > 0);
82
+ assert.equal(cmpVersion("1.67", "1.67.0"), 0);
83
+ assert.equal(cmpVersion(undefined, "1.67.0"), null);
84
+ assert.deepEqual(agentsLeftBehind([{ name: "a", ok: true, engine_version: "1.66.0" }, { name: "b", ok: true }, { name: "c", ok: true, engine_version: "1.67.0" }], "1.67.0"), [{ name: "a", version: "1.66.0" }]);
85
+ });
86
+
87
+ test("upgradeAgentsAfterUpdate names agents left behind and keeps its string result", async () => {
88
+ const warned = [], dir = tmpDir("cs-eng-cfg-"), cfgPath = `${dir}/router.json`;
89
+ (await import("node:fs")).writeFileSync(cfgPath, "{}");
90
+ const r = await upgradeAgentsAfterUpdate({ configPath: cfgPath, runPoolCli: async () => {}, warn: (m) => warned.push(m),
91
+ leftBehind: async () => ({ target: "1.67.0", rows: [{ name: "old", version: "1.66.0" }] }) });
92
+ assert.equal(r, "upgraded");
93
+ assert.match(warned[0], /left behind.*old 1\.66\.0/);
94
+ });
@@ -0,0 +1,41 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #6061: the per-worker lane target. Same AIMD thresholds as the orchestrator controller (bin/lean/concurrency.mjs, imported):
5
+ * +1 while free memory is above floor + headroom and load per core is green for a hold window, halve (min 1) on load above
6
+ * 1.5/core or low memory, never above the configured ceiling. `drainState` says when the worker accepts no new lane (running
7
+ * lanes always finish). Pure: the caller keeps `greenSince` / busy timers and feeds the clock.
8
+ */
9
+ import { LOAD_GREEN, LOAD_HALVE, MEM_FLOOR_GB, MEM_HEADROOM_GB } from "../lean/concurrency.mjs";
10
+
11
+ export const GREEN_HOLD_MS = 60_000;
12
+ export const DRAIN_AFTER_MS = 5 * 60_000;
13
+ const fin = (v) => typeof v === "number" && Number.isFinite(v);
14
+
15
+ /** Is the host over its pressure line (load above 1.5/core or free memory under the floor)? Unknown figures are not pressure. */
16
+ export const pressured = (live, { memFloorGb = MEM_FLOOR_GB } = {}) =>
17
+ (fin(live?.load_per_core) && live.load_per_core > LOAD_HALVE) || (fin(live?.mem_available_gb) && live.mem_available_gb < memFloorGb);
18
+
19
+ /** Next `{ target, greenSince, change }` (change: "grow" | "halve" | null). `refused` (a pool.* refusal) also halves. */
20
+ export function step({ target, ceiling, live, refused = false, now = Date.now(), greenSince = null, holdMs = GREEN_HOLD_MS, memFloorGb = MEM_FLOOR_GB, memHeadroomGb = MEM_HEADROOM_GB } = {}) {
21
+ const top = Math.max(1, Number.isInteger(ceiling) ? ceiling : 1);
22
+ const t = Math.min(top, Math.max(1, Number.isInteger(target) ? target : 1));
23
+ if (refused || pressured(live, { memFloorGb })) {
24
+ const next = Math.max(1, Math.floor(t / 2));
25
+ return { target: next, greenSince: null, change: next < t ? "halve" : null };
26
+ }
27
+ const green = fin(live?.load_per_core) && live.load_per_core < LOAD_GREEN && fin(live?.mem_available_gb) && live.mem_available_gb > memFloorGb + memHeadroomGb;
28
+ if (!green) return { target: t, greenSince: null, change: null };
29
+ const since = greenSince ?? now;
30
+ if (t < top && now - since >= holdMs) return { target: t + 1, greenSince: now, change: "grow" }; // each step needs a fresh hold window
31
+ return { target: t, greenSince: since, change: null };
32
+ }
33
+
34
+ /** `{ draining, reason }`: paused (owner, policy or config), or the host busy for `drainAfterMs`. */
35
+ export function drainState({ paused = false, ownerPaused = false, policyPaused = false, busyForMs = 0, drainAfterMs = DRAIN_AFTER_MS } = {}) {
36
+ if (ownerPaused) return { draining: true, reason: "paused by owner" };
37
+ if (policyPaused) return { draining: true, reason: "paused by policy" };
38
+ if (paused) return { draining: true, reason: "paused" };
39
+ if (busyForMs >= drainAfterMs) return { draining: true, reason: `host busy for ${Math.round(busyForMs / 60000)}m` };
40
+ return { draining: false, reason: null };
41
+ }
@@ -17,6 +17,7 @@ export const RECIPES = {
17
17
  python: { versioned: true, steps: (v) => [apt(v ? `python${v} python${v}-venv` : "python3 python3-venv")] },
18
18
  xvfb: { versioned: false, steps: () => [apt("xvfb xauth")] }, // headless X for browser/GUI tests that call xvfb-run
19
19
  shellcheck: { versioned: false, steps: () => [apt("shellcheck")] }, // shell-script linter for validate commands
20
+ yaml: { versioned: false, steps: () => [apt("python3-yaml")] }, // PyYAML for validate commands that `import yaml` (#5749)
20
21
  playwright: { versioned: true, steps: (v) => [`RUN npx --yes playwright${v ? `@${v}` : ""} install --with-deps chromium`] },
21
22
  // Example of a release-tarball tool; the version is required.
22
23
  promtool: { versioned: true, steps: (v) => [`RUN curl -fsSL https://github.com/prometheus/prometheus/releases/download/v${v ?? "2.54.1"}/prometheus-${v ?? "2.54.1"}.linux-amd64.tar.gz | tar -xz --strip-components=1 -C /usr/local/bin --wildcards '*/promtool'`] },
@@ -78,13 +79,17 @@ export function installCommands(entry, { root = true } = {}) {
78
79
  */
79
80
  const PYPI = { yaml: "PyYAML", PIL: "Pillow", cv2: "opencv-python-headless", bs4: "beautifulsoup4", sklearn: "scikit-learn", dateutil: "python-dateutil", jwt: "PyJWT", dotenv: "python-dotenv", google: "protobuf", attr: "attrs", magic: "python-magic", Crypto: "pycryptodome", OpenSSL: "pyOpenSSL", serial: "pyserial", usb: "pyusb", zmq: "pyzmq", git: "GitPython", jose: "python-jose", multipart: "python-multipart" };
80
81
  const SAFE = /^@?[A-Za-z0-9][A-Za-z0-9._/+-]*$/;
82
+ /** Debian/Ubuntu package stems where the import name differs (python3-<stem>). */
83
+ const APT_PY = { PIL: "pil", cv2: "opencv", bs4: "bs4", sklearn: "sklearn", dateutil: "dateutil", jwt: "jwt", dotenv: "dotenv", serial: "serial", git: "git", magic: "magic" };
81
84
  export function genericInstallCommands(miss, { root = true } = {}) {
82
85
  const tool = String(miss?.tool ?? "").trim();
83
86
  if (!tool || !SAFE.test(tool) || tool.includes("..")) return [];
84
87
  const su = (c) => (root ? c : `sudo sh -c ${JSON.stringify(c)}`);
85
88
  if (miss.kind === "python-module") {
86
- const pkg = PYPI[tool.split(".")[0]] ?? tool.split(".")[0];
87
- return [`python3 -m pip install --user --quiet ${pkg} || python3 -m pip install --user --quiet --break-system-packages ${pkg}`];
89
+ const mod = tool.split(".")[0], pkg = PYPI[mod] ?? mod;
90
+ // 2026-11-26: lane images may ship python3 without pip; the distro package (python3-<module>) is the fallback
91
+ const deb = `python3-${(APT_PY[mod] ?? mod).toLowerCase().replace(/_/g, "-")}`;
92
+ return [`python3 -m pip install --user --quiet ${pkg} || python3 -m pip install --user --quiet --break-system-packages ${pkg} || (${su(`apt-get update -qq && apt-get install -y --no-install-recommends ${deb} && rm -rf /var/lib/apt/lists/*`)})`];
88
93
  }
89
94
  if (miss.kind === "node-module") return [`npm install --no-save --no-audit --no-fund ${tool}`];
90
95
  if (miss.kind === "command" && !tool.includes("/")) return [su(`apt-get update -qq && apt-get install -y --no-install-recommends ${tool} && rm -rf /var/lib/apt/lists/*`)];
@@ -35,3 +35,12 @@ describe("#5652 in-sandbox lane tool install", () => {
35
35
  assert.match(installCommands("python@3.12")[0], /python3\.12 python3\.12-venv/);
36
36
  });
37
37
  });
38
+
39
+ describe("#5749 yaml recipe", () => {
40
+ it("#5749 yaml has a lane_tools recipe", () => {
41
+ assert.ok(hasRecipe("yaml"));
42
+ assert.match(installCommands("yaml")[0], /apt-get install .*python3-yaml/);
43
+ assert.ok(hasRecipe("shellcheck"));
44
+ assert.ok(!hasRecipe("vite") && !hasRecipe("forgedock"), "#5749: manifest/owned deps get no recipe");
45
+ });
46
+ });
@@ -66,8 +66,12 @@ export function localRunner({ root, seedDir }) {
66
66
  /** `runnerFor({slug, cache_key})` -> runner. Returns the agent's mirror seed handlers. */
67
67
  export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_MS, uploadMax = SEED_UPLOAD_MAX, totalMax = SEED_TOTAL_MAX }) {
68
68
  mkdirSync(seedDir, { recursive: true });
69
- const part = (up) => join(seedDir, `${up}.part`);
70
- const size = (up) => { try { return statSync(part(up)).size; } catch { return 0; } };
69
+ // Concurrent lanes seeding the same repo build byte-identical bundles (same sha256). One shared `<sha>.part` let them
70
+ // append into each other's upload: 409 offset mismatch, then 422 when one finish deleted the file under the others
71
+ // (2026-11-26 lane-lifecycle audit: bursts of 5–12 lanes within seconds). Each uploader now has its own part file.
72
+ const who = (u) => (typeof u === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(u) ? `.${u}` : "");
73
+ const part = (up, uploader) => join(seedDir, `${up}${who(uploader)}.part`);
74
+ const size = (up, uploader) => { try { return statSync(part(up, uploader)).size; } catch { return 0; } };
71
75
  /** Removes `.part` files idle past the TTL; returns the bytes the remaining ones hold. */
72
76
  const sweep = () => {
73
77
  let total = 0;
@@ -87,11 +91,11 @@ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_M
87
91
  };
88
92
  return {
89
93
  /** `GET /mirrors`: {mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}. */
90
- async tips({ slug, cache_key = null, upload = null }) {
94
+ async tips({ slug, cache_key = null, upload = null, uploader = null }) {
91
95
  if (typeof slug !== "string" || !SLUG_RE.test(slug)) throw fail(400, "slug required");
92
96
  const out = String(await runnerFor({ slug, cache_key })(TIPS_SCRIPT, { NAME: mirrorName(slug) })).trim();
93
97
  const mirror = out === "ABSENT" ? "absent" : Object.fromEntries(out.split("\n").filter(Boolean).map((l) => { const i = l.indexOf(" "); return [l.slice(i + 1), l.slice(0, i)]; }));
94
- return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload) } : {}) };
98
+ return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload, uploader) } : {}) };
95
99
  },
96
100
  /** One chunk: {slug, cache_key, upload, offset, data_b64, sha256}. A wrong offset is a 409 carrying the offset to resume from. */
97
101
  chunk(b) {
@@ -99,23 +103,23 @@ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_M
99
103
  const buf = Buffer.from(String(b.data_b64 ?? ""), "base64");
100
104
  if (!buf.length || buf.length > SEED_CHUNK_MAX) throw fail(413, `chunk must be 1..${SEED_CHUNK_MAX} bytes`);
101
105
  if (sha256(buf) !== b.sha256) throw fail(422, "chunk checksum mismatch");
102
- const have = size(b.upload);
106
+ const have = size(b.upload, b.uploader);
103
107
  if (b.offset !== have) throw fail(409, "offset mismatch", { offset: have });
104
108
  if (have + buf.length > uploadMax) throw fail(413, `upload exceeds ${uploadMax} bytes`);
105
109
  if (sweep() + buf.length > totalMax) throw fail(413, `seed dir exceeds ${totalMax} bytes`);
106
- appendFileSync(part(b.upload), buf);
110
+ appendFileSync(part(b.upload, b.uploader), buf);
107
111
  return { offset: have + buf.length };
108
112
  },
109
113
  /** Verifies the whole bundle against {size, sha256 = upload} and applies it. A corrupt upload is dropped; the mirror is never touched on failure. */
110
114
  async finish(b) {
111
115
  check(b);
112
116
  const f = b.finish ?? {};
113
- const have = size(b.upload);
117
+ const p = part(b.upload, b.uploader), have = size(b.upload, b.uploader);
114
118
  if (!Number.isInteger(f.size) || have !== f.size) throw fail(409, "incomplete upload", { offset: have });
115
- if (!existsSync(part(b.upload)) || sha256(readFileSync(part(b.upload))) !== b.upload) { rmSync(part(b.upload), { force: true }); throw fail(422, "bundle checksum mismatch"); }
116
- try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}.part` }); }
117
- catch (e) { rmSync(part(b.upload), { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
118
- rmSync(part(b.upload), { force: true });
119
+ if (!existsSync(p) || sha256(readFileSync(p)) !== b.upload) { rmSync(p, { force: true }); throw fail(422, "bundle checksum mismatch"); }
120
+ try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}${who(b.uploader)}.part` }); }
121
+ catch (e) { rmSync(p, { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
122
+ rmSync(p, { force: true });
119
123
  return { ok: true, ...(await this.tips({ slug: b.slug, cache_key: b.cache_key })) };
120
124
  },
121
125
  };