forgedock 1.65.0 → 1.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,7 +72,7 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
72
72
  try {
73
73
  const b = openBatch(root, id);
74
74
  if (!b.readPlan()?.daemon || b.isTerminal()) continue;
75
- const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
75
+ const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
76
76
  const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
77
77
  out.push(batchVerdict(id, stall, decision));
78
78
  } catch { /* one unreadable batch has no verdict */ }
@@ -90,6 +90,8 @@ export function sharedPendingLines(batches) {
90
90
  export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
91
91
  export const IDLE_MS = 10 * 60 * 1000;
92
92
  export const STOP_MS = 10 * 1000;
93
+ export const HARD_EXIT_MS = 30 * 1000; // #5966: a self-initiated stop exits by then even if close() hangs
94
+ export const SUCCESSOR_MS = 10 * 1000; // #5966: how long a handover waits for the successor to listen
93
95
  export const LOCK_CHECK_MS = 5 * 1000;
94
96
  export const ADMIT_MS = 120 * 1000; // #4775: how long one add/requeue/attach/resume waits for its batch to start before answering an error
95
97
  export const LAG_MS = 5 * 1000; // #4775: an event-loop stall longer than this is logged
@@ -218,7 +220,9 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
218
220
  root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
219
221
  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,
220
222
  abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
221
- hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined } = {}) {
223
+ hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
224
+ exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined } = {}) {
225
+ const startOpts = arguments[0] ?? {};
222
226
  const p = scheddPaths(dir);
223
227
  // #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
224
228
  const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
@@ -237,7 +241,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
237
241
  const conns = new Set();
238
242
  const runs = new Map(); // every runBatch in flight (hosted or not yet started) -> its AbortController (#4454)
239
243
  const starting = new Map(); // batch id -> host() promise of a start-up resume not yet hosted (#4503: an attach waits for it)
240
- let closing = null, resolveClosed, keepSock = false;
244
+ let closing = null, resolveClosed, keepSock = false, stopCode = null, rehosted = null;
241
245
  let idleTimer, lockTimer, lagTimer, stallTimer, dueTimer; // assigned below; close() clears them
242
246
  let lastActive = Date.now();
243
247
  const touch = () => { lastActive = Date.now(); };
@@ -418,6 +422,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
418
422
  const changed = req.op === "hold" ? b.holdIssues(req.issues ?? [], req.meta ?? null) : b.releaseIssues(req.issues ?? []);
419
423
  return send({ type: "ok", changed, held: b.readHeld(), hosted: hosted.has(req.id) }, true);
420
424
  }
425
+ if (req.op === "pause" || req.op === "unpause") { // #5975: batch-level admission pause
426
+ const b = openBatch(root, req.id);
427
+ if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
428
+ if (req.op === "pause" && !req.meta?.reason) throw new Error("--pause needs --reason <text>");
429
+ const res = req.op === "pause" ? { pause: b.setPause(req.meta ?? {}) } : { changed: b.clearPause() };
430
+ return send({ type: "ok", ...res, hosted: hosted.has(req.id) }, true);
431
+ }
421
432
  if (req.op === "gc-orphans") { // #5469: cancel every orphaned batch (unhosted, pending issues, idle past the threshold)
422
433
  const { orphaned } = unhostedBatches(Date.now(), Number.isFinite(req.minAgeMs) ? req.minAgeMs : ORPHAN_AGE_MS);
423
434
  for (const o of orphaned) openBatch(root, o.id).requestCancel({ reason: "gc-orphans" });
@@ -515,6 +526,50 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
515
526
  });
516
527
  return closing;
517
528
  };
529
+ // #5966: a self-initiated stop (version handover, stall recovery). Under a systemd unit the process exits non-zero after a bounded
530
+ // drain so `Restart=` starts the successor (a hard timer fires even if close() hangs); without a unit it starts the successor and
531
+ // waits for it to listen, retrying once, then exits non-zero instead of lingering as an unreachable zombie.
532
+ const defaultProbe = () => new Promise((r) => {
533
+ if (process.platform === "win32") return r(true);
534
+ const c = createConnection(p.sock);
535
+ c.once("connect", () => { c.destroy(); r(true); });
536
+ c.once("error", () => r(false));
537
+ });
538
+ const probeFn = probe !== undefined ? probe : respawn === undefined ? defaultProbe : null;
539
+ const waitListening = async () => {
540
+ const end = Date.now() + successorMs;
541
+ for (;;) {
542
+ try { if (await probeFn()) return true; } catch { /* not yet */ }
543
+ if (Date.now() >= end) return false;
544
+ await new Promise((r) => setTimeout(r, successorPollMs));
545
+ }
546
+ };
547
+ let selfStopping = null;
548
+ const selfStop = () => (selfStopping ??= (async () => {
549
+ stopCode = 1;
550
+ const underUnit = ["active", "activating"].includes(unit());
551
+ let hard;
552
+ if (exit) { hard = setTimeout(() => { log(`schedd: stop did not finish within ${hardExitMs} ms, exiting`); exit(1); }, hardExitMs); hard.unref?.(); }
553
+ try {
554
+ await close();
555
+ const spawnOnce = () => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } };
556
+ spawnOnce();
557
+ if (probeFn && !underUnit) {
558
+ let ok = await waitListening();
559
+ if (!ok) { log("schedd: successor not listening; retrying"); spawnOnce(); ok = await waitListening(); }
560
+ if (!ok) {
561
+ // R1 (#5966): no successor came up: keep hosting by resuming the batches in this process (the lock is free again)
562
+ log(`schedd: no successor listening after ${successorMs} ms; hosting the batches again`);
563
+ try { rehosted = await (rehost !== undefined ? rehost() : startDaemon({ ...startOpts })); } catch (e) { log(`schedd: re-host failed: ${e?.message ?? e}`); }
564
+ if (rehosted?.running) { clearTimeout(hard); return; }
565
+ rehosted = null;
566
+ log("schedd: could not host again; exiting non-zero");
567
+ }
568
+ }
569
+ } catch (e) { log(`schedd: stop failed: ${e?.message ?? e}`); }
570
+ clearTimeout(hard);
571
+ if (exit) exit(1);
572
+ })());
518
573
  idleTimer = setInterval(() => {
519
574
  if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
520
575
  }, Math.min(idleMs, 30_000));
@@ -528,13 +583,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
528
583
  const now = loadedVersion ? versionOf() : null;
529
584
  if (now && now !== loadedVersion) {
530
585
  log(`schedd: install moved v${loadedVersion} → v${now}; handing over`);
531
- close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } });
586
+ selfStop();
532
587
  return;
533
588
  }
534
589
  let owner = NaN;
535
590
  try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
536
591
  if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
537
- else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); close(); }
592
+ else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); stopCode = 1; close(); }
538
593
  }, lockCheckMs);
539
594
  lockTimer.unref?.();
540
595
  // #4775: an event loop starved by host load leaves sockets unanswered and children unreaped; leave a trace of it.
@@ -552,7 +607,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
552
607
  // upgrade handover path (#5204): close() aborts every runner and kills the daemon's own children (lanes keep running), then a
553
608
  // fresh daemon resumes every batch. Once per batch and ready set (recorded in health.json before the restart).
554
609
  const restartStall = restartForStall !== undefined ? (id) => restartForStall(id)
555
- : (id) => { log(`schedd: restarting to recover stalled batch ${id}`); close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } }); };
610
+ : (id) => { log(`schedd: restarting to recover stalled batch ${id}`); selfStop(); };
556
611
  let watching = false;
557
612
  const watchBatches = async () => {
558
613
  if (closing || watching) return;
@@ -571,7 +626,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
571
626
  const created = Date.parse(plan.created ?? "");
572
627
  if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
573
628
  const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
574
- const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
629
+ const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
575
630
  let stall = evaluateDispatchStall(state, stallOpts);
576
631
  if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
577
632
  let gates = [];
@@ -579,7 +634,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
579
634
  if (gates.length) stall = evaluateDispatchStall(state, { ...stallOpts, gates }) ?? stall;
580
635
  }
581
636
  if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
582
- if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
637
+ if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, paused: b.readPause?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
583
638
  }
584
639
  const sig = stall ? stall.ready.join(",") : "";
585
640
  const last = b.lastProgressMs();
@@ -645,7 +700,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
645
700
  started.catch((e) => log(`schedd: resume ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
646
701
  }
647
702
  }
648
- return { running: true, pid, sock: p.sock, close, closed };
703
+ return { running: true, pid, sock: p.sock, close: () => (rehosted ? rehosted.close() : close()), closed, stopCode: () => stopCode, rehosted: () => rehosted, settled: () => selfStopping ?? closed };
649
704
  }
650
705
 
651
706
  /** #5204: `version` of the package.json of this install (../../package.json), null when it cannot be read. */
@@ -793,6 +793,90 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
793
793
  } finally { await d2?.close?.(); }
794
794
  });
795
795
 
796
+ it("#5966: a handover under an active unit exits non-zero after close, and the hard bound fires when a batch stop hangs", async () => {
797
+ for (const hang of [false, true]) {
798
+ const dir = tmpDir("schedd-exit-"), root = join(dir, "batches"), lines = [], exits = [];
799
+ let version = "1.51.0";
800
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active",
801
+ exit: (c) => exits.push(c), stopMs: hang ? 60_000 : 1000, hardExitMs: 200,
802
+ runBatch: ({ sink, signal }) => { sink.batch({ id: "x", dir }); return new Promise((_, rej) => { if (!hang) signal.addEventListener("abort", () => rej(Object.assign(new Error("stopped"), { code: "batch.stopped" }))); }); } });
803
+ request(await connectDaemon({ dir, spawnDaemon: null }), { op: "submit", argv: ["x"], cwd: dir, env: {} }).catch(() => {});
804
+ await until(() => lines.some((l) => l.includes("listening")));
805
+ version = "1.52.0";
806
+ await until(() => exits.length > 0);
807
+ assert.deepEqual(exits, [1], `hang=${hang}`);
808
+ assert.equal(d.stopCode(), 1);
809
+ if (hang) assert.ok(lines.some((l) => l.includes("did not finish within")), lines.join("\n"));
810
+ await d.close();
811
+ }
812
+ });
813
+
814
+ it("#5966 R1: without a unit, a handover whose successor never listens keeps hosting (re-hosted here); if that fails it exits non-zero", async () => {
815
+ const dir = tmpDir("schedd-nosucc-"), root = join(dir, "batches"), lines = [], exits = [];
816
+ let version = "1.51.0", spawns = 0;
817
+ const d = await startDaemon({ dir, root, log: (m) => lines.push(m), resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
818
+ exit: (c) => exits.push(c), respawn: () => { spawns++; }, probe: async () => false, successorMs: 50, successorPollMs: 10, runBatch: async () => ({}) });
819
+ version = "1.52.0";
820
+ await until(() => d.rehosted());
821
+ const d2 = d.rehosted();
822
+ try {
823
+ assert.equal(d2.running, true, "a daemon hosts again and holds the lock");
824
+ assert.equal(readFileSync(scheddPaths(dir).lock, "utf8").trim(), String(process.pid));
825
+ assert.deepEqual(exits, [], "no exit while hosting continues");
826
+ assert.equal(spawns, 2, "the successor was started twice");
827
+ assert.ok(lines.some((l) => l.includes("hosting the batches again")));
828
+ } finally { await d2.close(); }
829
+ // re-host impossible -> exit non-zero
830
+ const dir2 = tmpDir("schedd-nosucc2-"), exits2 = [];
831
+ let v2 = "1.51.0";
832
+ await startDaemon({ dir: dir2, root: join(dir2, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => v2, unit: () => null,
833
+ exit: (c) => exits2.push(c), respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, rehost: async () => null, runBatch: async () => ({}) });
834
+ v2 = "1.52.0";
835
+ await until(() => exits2.length > 0);
836
+ assert.deepEqual(exits2, [1]);
837
+ });
838
+
839
+ it("#5984 handover: settled() outlives closed until the successor is spawned and probed (CLI exits only after it)", async () => {
840
+ const dir = tmpDir("schedd-settled-"), order = [];
841
+ let version = "1.51.0";
842
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
843
+ exit: (c) => order.push(`exit${c}`), respawn: () => order.push("respawn"), probe: async () => { order.push("probe"); return true; }, successorMs: 200, successorPollMs: 10, runBatch: async () => ({}) });
844
+ version = "1.52.0";
845
+ await d.closed;
846
+ order.push("closed-seen"); // what scheddFromCli used to exit on
847
+ await d.settled();
848
+ order.push("settled");
849
+ assert.ok(order.indexOf("respawn") < order.indexOf("settled") && order.indexOf("probe") < order.indexOf("settled"), order.join(","));
850
+ assert.equal(d.stopCode(), 1);
851
+ });
852
+
853
+ it("#5984 rehost: settled() of the stopped daemon resolves once the rehosted daemon is up; lost-lock/idle close settles via closed", async () => {
854
+ const dir = tmpDir("schedd-settled2-");
855
+ let version = "1.51.0";
856
+ const d = await startDaemon({ dir, root: join(dir, "batches"), log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => null,
857
+ exit: () => {}, respawn: () => {}, probe: async () => false, successorMs: 30, successorPollMs: 10, runBatch: async () => ({}) });
858
+ version = "1.52.0";
859
+ await d.closed; await d.settled();
860
+ const d2 = d.rehosted();
861
+ assert.equal(d2?.running, true, "rehosted before settled resolves");
862
+ await d2.close();
863
+ const dir3 = tmpDir("schedd-settled3-");
864
+ const d3 = await startDaemon({ dir: dir3, root: join(dir3, "batches"), log: () => {}, resumeOnStart: false, runBatch: async () => ({}) });
865
+ await d3.close();
866
+ await d3.settled();
867
+ assert.equal(d3.stopCode(), null);
868
+ });
869
+
870
+ it("#5966: a stall-recovery restart also exits (shared self-stop path)", async () => {
871
+ const dir = tmpDir("schedd-stallexit-"), root = join(dir, "batches"), exits = [];
872
+ let version = "1.51.0";
873
+ const d = await startDaemon({ dir, root, log: () => {}, resumeOnStart: false, lockCheckMs: 30, installedVersion: () => version, unit: () => "active", exit: (c) => exits.push(c), runBatch: async () => ({}) });
874
+ version = "1.52.0";
875
+ await until(() => exits.length > 0);
876
+ assert.deepEqual(exits, [1]);
877
+ await d.closed;
878
+ });
879
+
796
880
  it("#5204: readInstalledVersion reads this install's package.json version, null when unreadable", () => {
797
881
  assert.equal(readInstalledVersion(), JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version);
798
882
  const dir = tmpDir("schedd-ver-");
@@ -14,7 +14,7 @@ import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs"
14
14
  import { jsonStore } from "./store.mjs";
15
15
  import { makeWarm } from "./warm.mjs";
16
16
  import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
17
- import { hostDiskFree, ensureNatPin, netState } from "./health.mjs";
17
+ import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
18
18
  import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
19
19
  import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
20
20
  import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
@@ -104,7 +104,7 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
104
104
  }
105
105
  }
106
106
 
107
- export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
107
+ export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
108
108
  const stateDir = cfg.state_dir;
109
109
  const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
110
110
  const sb = () => store.data.sandboxes;
@@ -179,6 +179,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
179
179
  let lastCachePrune = -Infinity;
180
180
  // #5757: cache volume hygiene state: per-volume sweep error/size/last use (last use also from launches in this process).
181
181
  let lastCacheSweep = -Infinity;
182
+ let lastLaunchSweep = -Infinity;
182
183
  const cacheErr = new Map(), cacheInfo = new Map(), cacheUsed = new Map(), adoptedCache = new Set(); // adoptedCache: pre-label volumes this agent mounts (labels cannot be added to an existing volume)
183
184
  const sweepFail = (v, what, e) => { const m = `${what} ${v}: ${String(e.stderr || e.message).slice(0, 200)}`; cacheErr.set(`${what}:${v}`, m); log.warn?.(m); };
184
185
  const dirMb = (d) => { let n = 0, seen = 0; const walk = (x) => { if (seen++ > 200000) return; let st; try { st = lstatSync(x); } catch { return; } n += st.size; if (st.isDirectory()) { try { for (const e of readdirSync(x)) walk(join(x, e)); } catch { /* unreadable */ } } }; walk(d); return Math.round(n / 1048576); };
@@ -227,6 +228,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
227
228
  const a = hostSamples[0], b = hostSamples[hostSamples.length - 1];
228
229
  return a && b && b.t - a.t >= 60000 ? Math.round(((a.gb - b.gb) / ((b.t - a.t) / 3600000)) * 10) / 10 : null;
229
230
  }
231
+ // #5967: free physical memory of the Windows host (neighbour WSL VMs squeeze the lane VM invisibly); null off WSL or unreadable: no field, no gate.
232
+ let hostMemCache = { at: -Infinity, v: null };
233
+ const readHostMem = () => {
234
+ if (now() - hostMemCache.at >= 30000) hostMemCache = { at: now(), v: (hostMem ?? hostMemFree)() };
235
+ return hostMemCache.v;
236
+ };
237
+ const memFloorGb = () => cfg.host_mem_floor_gb ?? 4;
238
+ const memPausedRecs = () => activeRecs().filter((r) => r.memPaused);
239
+ function hostMemView() {
240
+ let hm = null; try { hm = readHostMem(); } catch { hm = null; }
241
+ if (!hm || !Number.isFinite(hm.free_gb)) return {};
242
+ return { host_mem_free_gb: hm.free_gb, host_mem_low: hm.free_gb < memFloorGb() || memPausedRecs().length > 0, host_mem_floor_gb: memFloorGb(), ...(Array.isArray(hm.vmmem) && hm.vmmem.length ? { vmmem: hm.vmmem } : {}), ...(memPausedRecs().length ? { mem_paused: memPausedRecs().length } : {}) };
243
+ }
230
244
  let netCache = { at: -Infinity, v: null };
231
245
  const readNet = () => { if (now() - netCache.at > 60000) netCache = { at: now(), v: net() }; return netCache.v; };
232
246
  // #5884: lane disk cap (cfg.lane_disk_cap_gb, unset = off, nothing added to /capacity): sandbox dirs plus cache volumes.
@@ -360,7 +374,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
360
374
  const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
361
375
  const e = effectiveCapacity();
362
376
  const h = live(cfg);
363
- return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10 }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
377
+ return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
364
378
  }
365
379
 
366
380
  /** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
@@ -395,6 +409,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
395
409
  if (existing?.drained && existing.state === "exited") { await destroy(existing.id, "drained: relaunch"); existing = null; } // #5856: the router/dispatcher rescheduled a drained lane under the same id
396
410
  if (existing?.diskPressure && existing.state === "exited") { await destroy(existing.id, "disk pressure: resume", { keepWork: true }); existing = null; } // #5891: the worktree stays, the lane adopts it
397
411
  if (existing) { existing.lease = now(); store.save(); return { status: 200, body: view(existing) }; }
412
+ if (now() - lastLaunchSweep > 60000) { lastLaunchSweep = now(); await cacheSweep(now()).catch(() => {}); } // #5901: trim the depcache to its cap before this lane can write a new entry (throttled; the periodic sweep also runs)
398
413
  if (Number.isInteger(spec.warm)) warm.configure({ spec, cpus, mem_gb, limit, n: spec.warm }); // #4912: the lane's execution.warm_sandboxes sizes the repo's pool
399
414
  const prio = spec.priority ?? "normal";
400
415
  if (!PRIORITIES.includes(prio)) throw Object.assign(new Error(`spec.priority must be one of ${PRIORITIES.join(", ")}`), { status: 400 });
@@ -420,6 +435,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
420
435
  const floor = floorGb();
421
436
  return { status: 503, body: { error: `host disk low: ${gate.host_disk_free_gb} GB free, floor ${floor} GB with ${c.active} running`, code: "pool.disk_low", host_disk_free_gb: gate.host_disk_free_gb, floor_gb: floor }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
422
437
  }
438
+ const mg = hostMemView();
439
+ if (mg.host_mem_low) { // #5967: after the disk gate, before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
440
+ return { status: 503, body: { error: `host memory low: ${mg.host_mem_free_gb} GB free, floor ${mg.host_mem_floor_gb} GB`, code: "pool.host_mem", reason: "host_mem", host_mem_free_gb: mg.host_mem_free_gb, floor_gb: mg.host_mem_floor_gb }, retryAfter: cfg.host_mem_retry_after_s ?? 60 };
441
+ }
423
442
  if (c.disk_capped) { // #5884: lane disk is at the hard cap; pressure prune runs in reap(), the lane defers like pool.disk_low
424
443
  return { status: 503, body: { error: `lane disk full: ${c.lane_disk_used_gb} GB of ${c.lane_disk_cap_gb} GB cap`, code: "pool.disk_cap", lane_disk_used_gb: c.lane_disk_used_gb, cap_gb: c.lane_disk_cap_gb }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
425
444
  }
@@ -506,7 +525,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
506
525
  return { status: 201, body: view(rec) };
507
526
  }
508
527
 
509
- const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
528
+ const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
510
529
 
511
530
  const warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
512
531
 
@@ -515,7 +534,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
515
534
  const s = await docker.inspect(r.name);
516
535
  if (!s) { r.state = "exited"; r.finishedAt ??= now(); }
517
536
  else if (!s.running && r.state !== "starting") { r.state = "exited"; r.exitCode = s.exitCode; r.finishedAt = Date.parse(s.finishedAt) || now(); }
518
- else if (s.running) r.state = r.diskPaused ? "paused" : "running";
537
+ else if (s.running) r.state = r.diskPaused || r.memPaused ? "paused" : "running";
519
538
  return r;
520
539
  }
521
540
 
@@ -609,7 +628,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
609
628
  for (const v of await ownCacheVolumes()) {
610
629
  if (never.includes(v)) continue;
611
630
  try {
612
- const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, keep, now: t });
631
+ const r = await docker.sweepCache(v, image, { maxAgeDays: cfg.cache_max_age_days ?? 14, maxGb: cfg.cache_max_gb ?? null, maxDepcacheGb: cfg.depcache_max_gb ?? 40, keep, now: t });
613
632
  cacheInfo.set(v, r); cacheErr.delete(`cache sweep:${v}`);
614
633
  if (r.errors?.length) cacheErr.set(`cache sweep:${v}`, `cache sweep ${v}: ${r.errors[0]}`);
615
634
  volumes.push({ name: v, lastUsedMs: Math.max(r.last_used_ms ?? -Infinity, cacheUsed.get(v) ?? -Infinity) });
@@ -691,6 +710,24 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
691
710
  log.error?.(`stopped ${victim.id} (sandbox.disk_pressure): host free ${free} GB < ${hard} GB`);
692
711
  }
693
712
  }
713
+ // #5967: runtime host-memory control, once per reap. Below floor/2 pause the newest running sandbox (lease kept); at floor + margin resume.
714
+ async function hostMemPressure(t) {
715
+ hostMemCache.at = -Infinity;
716
+ let hm = null; try { hm = readHostMem(); } catch { hm = null; }
717
+ if (!hm || !Number.isFinite(hm.free_gb)) return;
718
+ const free = hm.free_gb, floor = memFloorGb();
719
+ for (const r of memPausedRecs()) r.lease = t; // a paused lane stays leased: it is not lost
720
+ if (free >= floor + (cfg.host_mem_resume_margin_gb ?? 1)) {
721
+ for (const r of memPausedRecs()) {
722
+ try { for (const n of cntNames(r)) await docker.unpause?.(n); r.memPaused = false; r.state = r.diskPaused ? "paused" : "running"; log.info?.(`resumed ${r.id}: host memory ${free} GB`); } catch (e) { log.warn?.(`unpause ${r.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
723
+ }
724
+ return;
725
+ }
726
+ if (free >= floor / 2 || memPausedRecs().length) return; // one paused sandbox at a time; resumes only above floor + margin
727
+ const victim = activeRecs().filter((r) => r.state === "running").sort((a, b) => b.startedAt - a.startedAt)[0];
728
+ if (!victim) return;
729
+ try { for (const n of cntNames(victim)) await docker.pause?.(n); victim.memPaused = true; victim.state = "paused"; victim.lease = t; log.warn?.(`paused ${victim.id} (memory): host free ${free} GB < ${floor / 2} GB`); } catch (e) { log.warn?.(`pause ${victim.id}: ${String(e.stderr || e.message).slice(0, 200)}`); }
730
+ }
694
731
  /** #5884: at the prune threshold of lane_disk_cap_gb prune this agent's own leftovers and sweep caches; fstrim on an interval and after a prune. Log lines only. */
695
732
  let lastFstrim = -Infinity;
696
733
  async function diskPressure(t) {
@@ -715,10 +752,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
715
752
  const t = now();
716
753
  for (const r of Object.values(sb())) {
717
754
  try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
718
- const why = t - r.lease > leaseTtlMs && !r.diskPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
755
+ const why = t - r.lease > leaseTtlMs && !r.diskPaused && !r.memPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
719
756
  if (why) await destroy(r.id, why);
720
757
  }
721
758
  await hostDiskPressure(t); // #5891
759
+ await hostMemPressure(t); // #5967
722
760
  const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
723
761
  for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
724
762
  await sampleUsage();
@@ -8,8 +8,10 @@ import { existsSync, readFileSync, rmSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
 
10
10
  export const CACHE_LABEL = "computeshare.cache=1";
11
+ /** #5969: dirs older entrypoints (and volumes/images already out there) export as lane cache dirs; still swept, capped and pruned. */
12
+ export const LEGACY_STORES = ["uv", "npm", "pip", "poetry"];
11
13
  /** #5955: every package-manager store the lanes write (depcache.mjs env(), agent.mjs pnpm store), relative to the /cache volume root. One list for the sweep and pruneCaches. */
12
- export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-cache", "poetry-cache", "pip-cache"].map((n) => `forge-depcache/stores/${n}`)];
14
+ export const PACKAGE_STORES = ["pnpm-store", ...["pnpm-store", "npm-cache", "uv-cache", "poetry-cache", "pip-cache"].map((n) => `forge-depcache/stores/${n}`), ...LEGACY_STORES];
13
15
  /** #5881: owner label; the reaper and sweeps touch only containers and volumes carrying their own agent's label. */
14
16
  export const agentLabel = (id) => `computeshare.agent=${id}`;
15
17
  const DAY = 86400000;
@@ -31,6 +33,14 @@ export function planCacheCap(entries, capBytes) {
31
33
  return { delete: out, total, after };
32
34
  }
33
35
 
36
+ /**
37
+ * #5901: least-recently-used plan for one repo's depcache snapshots ({path, bytes, lastUsedMs, live}). Same rule as
38
+ * `planCacheCap` with last use as the order; live (locked) snapshots count towards the total and are never chosen.
39
+ */
40
+ export function planDepcacheCap(entries, capBytes) {
41
+ return planCacheCap(entries.map((e) => ({ ...e, mtimeMs: e.lastUsedMs })), capBytes);
42
+ }
43
+
34
44
  /**
35
45
  * Cache volumes to remove: last use known (`lastUsedMs` a number), older than `idleMs`, no sandbox record references
36
46
  * it and it is not in the never-evict list. `volumes` is [{name, lastUsedMs}].
@@ -44,8 +54,34 @@ const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: "ut
44
54
  const sizeOf = (p) => (Number(sh("du", ["-sk", p]).split(/\s/)[0]) || 0) * 1024;
45
55
  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 }; });
46
56
 
57
+ const SNAP = /^[a-z]+-[0-9a-f]{16}$/;
58
+ /** 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; };
60
+
61
+ /**
62
+ * #5901: depcache is `<dc>/<repoKey>/<eco>-<key>/`. Each snapshot (not the repo dir, whose mtime moves with every new
63
+ * 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
+ * is in use and kept. Fills `depcacheBytes[repoKey]` with what remains.
65
+ */
66
+ function sweepDepcache(dc, { cutoff, capBytes, rm, depcacheBytes }) {
67
+ for (const repo of kids(dc)) {
68
+ const rk = repo.path.slice(dc.length + 1);
69
+ 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)
71
+ 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) }));
74
+ for (const k of snaps.filter((x) => x.lastUsedMs < cutoff && !x.live)) rm(k.path);
75
+ snaps = snaps.filter((x) => existsSync(x.path));
76
+ if (!snaps.length) { if (repo.mtimeMs < cutoff) rm(repo.path); continue; } // nothing left in it and untouched for the max age
77
+ for (const k of snaps) k.bytes = sizeOf(k.path);
78
+ if (capBytes !== null) for (const p of planDepcacheCap(snaps, capBytes).delete) rm(p);
79
+ depcacheBytes[rk] = snaps.filter((x) => existsSync(x.path)).reduce((a, x) => a + x.bytes, 0);
80
+ }
81
+ }
82
+
47
83
  /** Runs inside the container. Returns {size_bytes, last_used_ms, removed, errors}. */
48
- export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, keep = [], now = Date.now() } = {}) {
84
+ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, maxDepcacheGb = null, keep = [], now = Date.now() } = {}) {
49
85
  const errors = [], removed = [];
50
86
  const rm = (p) => { try { rmSync(p, { recursive: true, force: true }); removed.push(p); } catch (e) { errors.push(`${p}: ${e.message}`); } };
51
87
  const cutoff = now - maxAgeDays * DAY;
@@ -57,7 +93,8 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
57
93
  }
58
94
  const ageOut = (dir, skip = []) => { for (const k of kids(dir)) if (k.mtimeMs < cutoff && !skip.includes(k.path)) rm(k.path); };
59
95
  const dc = join(root, "forge-depcache");
60
- if (existsSync(dc)) { ageOut(join(dc, "stores")); ageOut(dc, [join(dc, "stores")]); } // snapshots, then store entries
96
+ 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
61
98
  if (existsSync(join(root, "env"))) ageOut(join(root, "env"));
62
99
  const ps = join(root, "pnpm-store");
63
100
  if (existsSync(ps)) sh("pnpm", ["store", "prune", "--store-dir", ps]);
@@ -72,7 +109,7 @@ export function sweepVolume({ root = "/cache", maxAgeDays = 14, maxGb = null, ke
72
109
  }
73
110
  let last = null;
74
111
  try { const n = Number(readFileSync(join(root, ".last-used"), "utf8").trim()); if (Number.isFinite(n) && n > 0) last = n * 1000; } catch { /* never recorded */ }
75
- return { size_bytes: sizeOf(root), last_used_ms: last, removed: removed.length, errors: errors.slice(0, 5) };
112
+ return { size_bytes: sizeOf(root), last_used_ms: last, depcache_bytes: depcacheBytes, removed: removed.length, errors: errors.slice(0, 5) };
76
113
  }
77
114
 
78
115
  if (process.env.CS_CACHE_SWEEP_OPTS) process.stdout.write(JSON.stringify(sweepVolume(JSON.parse(process.env.CS_CACHE_SWEEP_OPTS))) + "\n");
package/bin/pool/cli.mjs CHANGED
@@ -69,6 +69,16 @@ export function statusTable(agents) {
69
69
  }
70
70
 
71
71
  /** The `forgedock pool` verbs (and the `computeshare` script). Throws on usage or router errors; `deps` injects the HTTP client and config. */
72
+ /** #5901: one line per agent cache volume with each repo's depcache size, from the router's /agents view. */
73
+ export function depcacheLines(agents) {
74
+ const out = [];
75
+ for (const a of agents ?? []) for (const [vol, v] of Object.entries(a.cache_volumes ?? {})) {
76
+ const repos = Object.entries(v.depcache_gb ?? {}).map(([k, gb]) => `${k} ${gb} GB`).join(", ");
77
+ if (repos) out.push(`${a.name} ${vol}: depcache ${repos}`);
78
+ }
79
+ return out;
80
+ }
81
+
72
82
  export async function runPoolCli(argv, deps = {}) {
73
83
  const [cmd, ...rest] = argv;
74
84
  const call = deps.call ?? httpCall;
@@ -117,6 +127,7 @@ export async function runPoolCli(argv, deps = {}) {
117
127
  if (rest.includes("--json")) console.log(JSON.stringify(r.data, null, 2));
118
128
  else if (!r.ok) throw new Error(`router refused: HTTP ${r.status} ${JSON.stringify(r.data)}`);
119
129
  else console.log(statusTable(r.data?.agents ?? []));
130
+ if (!rest.includes("--json") && r.ok) for (const l of depcacheLines(r.data?.agents)) console.log(l); // #5901
120
131
  // #5735: lane sandboxes used/ceiling per agent, and the lane total across all batches
121
132
  for (const a of Array.isArray(r.data?.agents) ? r.data.agents : []) if (a?.lanes) console.log(`${a.name}: lanes ${a.lanes.used}/${a.lanes.ceiling ?? "-"}`);
122
133
  if (Number.isInteger(r.data?.remote_lanes)) console.log(`remote lanes across batches: ${r.data.remote_lanes}`);
@@ -124,6 +135,7 @@ export async function runPoolCli(argv, deps = {}) {
124
135
  if (a.transport) console.log(`${a.name}: transport ${a.transport}`); // #5882
125
136
  const n = a.net; // #5923
126
137
  if (n?.mirrored) console.log(`${a.name}: net mirrored, port range ${n.port_range ?? "?"}, NAT pin ${n.nat_pin ? "present" : "MISSING"}${n.degraded ? " DEGRADED" : ""}`);
138
+ if (Number.isFinite(a.host_mem_free_gb)) console.error(`${a.name}: host_mem_free_gb ${a.host_mem_free_gb}${Array.isArray(a.vmmem) && a.vmmem.length ? `, other VMs: ${a.vmmem.map((v) => `${v.name} ${v.gb} GB`).join(", ")}` : ""}${a.host_mem_low ? " WARNING: host memory below the floor, new sandboxes are refused" : ""}`); // #5967
127
139
  if (!Number.isFinite(a.host_disk_free_gb)) continue;
128
140
  console.error(`${a.name}: host_disk_free_gb ${a.host_disk_free_gb}${Number.isFinite(a.host_disk_growth_gb_per_h) ? `, growth ${a.host_disk_growth_gb_per_h} GB/h` : ""}${a.disk_warning ? ` WARNING: ${a.disk_warning}` : ""}`);
129
141
  }
@@ -67,6 +67,24 @@ export function hostDiskFree({ path = null, osrelease = readRelease, statfs = st
67
67
  } catch { return null; }
68
68
  }
69
69
 
70
+ /**
71
+ * #5967: Windows host free physical memory and the vmmem working sets (other WSL/Hyper-V VMs), via powershell.exe over the interop
72
+ * socket. `{ free_gb, vmmem: [{name, gb}] }` (1 decimal), or null off WSL or on any error (absent means unknown: no gate). All I/O injectable.
73
+ */
74
+ const PS_MEM = "$f=(Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory; $v=@(Get-Process vmmem* -ErrorAction SilentlyContinue | ForEach-Object { @{ name=$_.ProcessName; bytes=$_.WorkingSet64 } }); @{ free_kb=$f; vmmem=$v } | ConvertTo-Json -Compress -Depth 3";
75
+ export function hostMemFree({ osrelease = readRelease, run = winRun, env = process.env } = {}) {
76
+ try {
77
+ if (!/microsoft/i.test(String(osrelease() ?? ""))) return null;
78
+ const out = run("/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", PS_MEM], env);
79
+ if (!out) return null;
80
+ const j = JSON.parse(String(out).trim());
81
+ const kb = Number(j?.free_kb);
82
+ if (!Number.isFinite(kb) || kb < 0) return null;
83
+ const vm = j.vmmem == null ? [] : Array.isArray(j.vmmem) ? j.vmmem : [j.vmmem];
84
+ return { free_gb: Math.round(kb / 104857.6) / 10, vmmem: vm.filter((p) => Number.isFinite(Number(p?.bytes))).map((p) => ({ name: String(p.name ?? "vmmem"), gb: Math.round(Number(p.bytes) / 107374182.4) / 10 })) };
85
+ } catch { return null; }
86
+ }
87
+
70
88
  /** #5923: WSL mirrored networking gives the guest a narrow source-port slice; docker MASQUERADE must stay inside it or replies drop. */
71
89
  const DEFAULT_RANGE = [32768, 60999];
72
90
  const NAT_BRIDGE_FMT = '{{.Name}}|{{index .Options "com.docker.network.bridge.name"}}|{{range .IPAM.Config}}{{.Subnet}} {{end}}';
@@ -9,11 +9,15 @@
9
9
  */
10
10
  import { createHash } from "node:crypto";
11
11
  import { execFile } from "node:child_process";
12
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
12
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
13
13
  import { join } from "node:path";
14
14
 
15
15
  /** Per-chunk cap on the decoded payload; base64 of it stays under the 1 MB JSON body limit of the router and agent. */
16
16
  export const SEED_CHUNK_MAX = 512 * 1024;
17
+ /** Abandoned uploads: a `.part` untouched this long is swept; one upload and all uploads together are capped (#5970). */
18
+ export const SEED_PART_TTL_MS = 60 * 60000;
19
+ export const SEED_UPLOAD_MAX = 2 * 1024 ** 3;
20
+ export const SEED_TOTAL_MAX = 4 * 1024 ** 3;
17
21
  export const mirrorName = (slug) => String(slug).replace(/\//g, "_");
18
22
  const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9._-]+)?$/;
19
23
  const SHA_RE = /^[a-f0-9]{64}$/;
@@ -60,10 +64,23 @@ export function localRunner({ root, seedDir }) {
60
64
  }
61
65
 
62
66
  /** `runnerFor({slug, cache_key})` -> runner. Returns the agent's mirror seed handlers. */
63
- export function makeMirrorSeed({ seedDir, runnerFor }) {
67
+ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_MS, uploadMax = SEED_UPLOAD_MAX, totalMax = SEED_TOTAL_MAX }) {
64
68
  mkdirSync(seedDir, { recursive: true });
65
69
  const part = (up) => join(seedDir, `${up}.part`);
66
70
  const size = (up) => { try { return statSync(part(up)).size; } catch { return 0; } };
71
+ /** Removes `.part` files idle past the TTL; returns the bytes the remaining ones hold. */
72
+ const sweep = () => {
73
+ let total = 0;
74
+ for (const n of readdirSync(seedDir)) {
75
+ if (!n.endsWith(".part")) continue;
76
+ try {
77
+ const st = statSync(join(seedDir, n));
78
+ if (Date.now() - st.mtimeMs > partTtlMs) rmSync(join(seedDir, n), { force: true }); else total += st.size;
79
+ } catch { /* removed concurrently */ }
80
+ }
81
+ return total;
82
+ };
83
+ sweep();
67
84
  const check = (b) => {
68
85
  if (typeof b?.slug !== "string" || !SLUG_RE.test(b.slug)) throw fail(400, "slug required");
69
86
  if (typeof b.upload !== "string" || !SHA_RE.test(b.upload)) throw fail(400, "upload must be the bundle sha256");
@@ -84,6 +101,8 @@ export function makeMirrorSeed({ seedDir, runnerFor }) {
84
101
  if (sha256(buf) !== b.sha256) throw fail(422, "chunk checksum mismatch");
85
102
  const have = size(b.upload);
86
103
  if (b.offset !== have) throw fail(409, "offset mismatch", { offset: have });
104
+ if (have + buf.length > uploadMax) throw fail(413, `upload exceeds ${uploadMax} bytes`);
105
+ if (sweep() + buf.length > totalMax) throw fail(413, `seed dir exceeds ${totalMax} bytes`);
87
106
  appendFileSync(part(b.upload), buf);
88
107
  return { offset: have + buf.length };
89
108
  },
@@ -242,6 +242,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
242
242
  }
243
243
  return out;
244
244
  }
245
+ /** #5967: host free memory and the other-VM (vmmem) working sets per agent. */
246
+ const memReport = (c) => Number.isFinite(c.host_mem_free_gb) ? { host_mem_free_gb: c.host_mem_free_gb, ...(Array.isArray(c.vmmem) && c.vmmem.length ? { vmmem: c.vmmem } : {}), ...(c.host_mem_low === true ? { host_mem_low: true } : {}) } : {};
245
247
  async function capacities() {
246
248
  const out = [];
247
249
  for (const [name, a] of Object.entries(agents())) {
@@ -256,7 +258,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
256
258
  /** Agent liveness for the scheduler (#4547): an agent is online when it answers and is not paused. */
257
259
  async function status() {
258
260
  const caps = await capacities();
259
- const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c) }));
261
+ const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c), ...memReport(c) }));
260
262
  return { online: agentsView.filter((a) => a.ok && !a.paused).length, total: agentsView.length, agents: agentsView };
261
263
  }
262
264
 
@@ -368,7 +370,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
368
370
  const sized = (await capacities()).filter((c) => c.ok && !c.paused && inAccount(c, spec) && fitsPriority(c, spec, size));
369
371
  const diskLow = sized.filter((c) => c.host_disk_low === true).map((c) => c.name); // #5733: never POST to a host whose drive is short
370
372
  const capped = sized.filter((c) => c.disk_capped === true && c.host_disk_low !== true).map((c) => c.name); // #5884: lane disk at its hard cap
371
- const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
373
+ const memLow = sized.filter((c) => c.host_mem_low === true && c.host_disk_low !== true && c.disk_capped !== true).map((c) => c.name); // #5967: host memory under the floor
374
+ const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true && c.host_mem_low !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
372
375
  const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
373
376
  let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
374
377
  const seeded = seedPick.get(spec.id)?.agent; // #5949: the agent holding this lane's seeded mirror goes first
@@ -387,6 +390,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
387
390
  if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
388
391
  if (diskLow.length) return { status: 503, body: { error: "no host has free disk", code: "pool.disk_low", agents: diskLow }, retryAfter: cfg.disk_low_retry_after_s ?? 300 }; // a capacity deferral, not a failure
389
392
  if (capped.length) return { status: 503, body: { error: "no host has lane disk below its cap", code: "pool.disk_cap", agents: capped }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
393
+ if (memLow.length) return { status: 503, body: { error: "no host has free memory", code: "pool.host_mem", reason: "host_mem", agents: memLow }, retryAfter: cfg.host_mem_retry_after_s ?? 60 }; // a capacity deferral, not a failure
390
394
  return { status: 503, body: { error: "no host has a free reservation", lane: size }, retryAfter: cfg.retry_after_s ?? 60 };
391
395
  }
392
396