forgedock 1.64.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.
- package/bin/engine-cli.mjs +53 -8
- package/bin/lean/batch-health.mjs +10 -5
- package/bin/lean/batch.mjs +19 -0
- package/bin/lean/batch.test.mjs +65 -0
- package/bin/lean/clear-breaker.mjs +15 -0
- package/bin/lean/clear-breaker.test.mjs +100 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/execution.mjs +3 -2
- package/bin/lean/lean.mjs +7 -6
- package/bin/lean/lean.test.mjs +1 -1
- package/bin/lean/mirror-bundle.mjs +84 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +61 -0
- package/bin/lean/orchestrate.mjs +46 -5
- package/bin/lean/sandbox-remote.mjs +31 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +15 -0
- package/bin/lean/schedd.mjs +69 -11
- package/bin/lean/schedd.test.mjs +120 -0
- package/bin/pool/agent.mjs +58 -9
- package/bin/pool/cache-sweep.mjs +44 -5
- package/bin/pool/cli.mjs +24 -7
- package/bin/pool/docker.mjs +2 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/mirror-seed.mjs +122 -0
- package/bin/pool/router.mjs +33 -2
- package/docs/CONFIG.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +21 -1
package/bin/engine-cli.mjs
CHANGED
|
@@ -1396,7 +1396,7 @@ async function envBatch({ argv, root, print = (l) => console.log(l) }) {
|
|
|
1396
1396
|
return { ok: true, batch: id };
|
|
1397
1397
|
}
|
|
1398
1398
|
|
|
1399
|
-
const ORCH_USAGE = "usage: forgedock orchestrate <issue...> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
|
|
1399
|
+
const ORCH_USAGE = "usage: forgedock orchestrate <issue...> [--parallel K] [--lane L] [--lane-override] [--force <reason>] [--repo owner/repo] [--auto-children off|decomposed|epic|all] [--epic N] | --resume <id> [issue...] | --set-parallel <id> <K> | --set-max-remote <id> <N> | --set-placement <id> remote|hybrid|local | --clear-breaker <id> | --add <id> <issue...> | --requeue <id> <issue...> [--reason <text>] | --cancel <id> [--stop-remote] | --hold <id> --all [--for 2h] [--reason T] (sugar for --pause) | --hold <id> <issue...> [--for <4h|30m|1d>] [--reason <text>] | --pause <id> [--for <4h|30m|1d>] --reason <text> | --unpause <id> | --gc-orphans | --adopt <issue> [--repo owner/repo] [--lane L] | --release <id> <issue...> | --show-env <id> | --set-env <id> KEY=VAL | --unset-env <id> KEY";
|
|
1400
1400
|
const ORCH_VALUED = ["--parallel", "--lane", "--repo", "--model", "--prefilter-model", "--reason", "--force", "--auto-children", "--epic", "--for"];
|
|
1401
1401
|
const issuesOf = (argv) => {
|
|
1402
1402
|
const issues = [];
|
|
@@ -1534,6 +1534,12 @@ function holdMeta(argv) {
|
|
|
1534
1534
|
return { owner: process.env.FORGE_HOLD_OWNER || `${process.env.USER || process.env.USERNAME || "operator"}@${hostname()}`, ownerPid: process.ppid, ownerHost: hostname(), forMs: parseHoldFor(forLabel), forLabel, reason: reason && !reason.startsWith("--") ? reason : null };
|
|
1535
1535
|
}
|
|
1536
1536
|
|
|
1537
|
+
/** #5975: `--hold --all` pauses the batch without a `--reason`: the reason defaults to the flag that asked. */
|
|
1538
|
+
function holdMetaAll(argv) {
|
|
1539
|
+
const m = holdMeta(argv);
|
|
1540
|
+
return argv.includes("--hold") && !m.reason ? { ...m, reason: "--hold --all" } : m;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1537
1543
|
/** #5469: `--gc-orphans`: cancel every orphaned batch (unhosted, pending issues, idle for a week) through the daemon or the batch files. */
|
|
1538
1544
|
async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l) }) {
|
|
1539
1545
|
let res = viaDaemon ? await viaDaemon() : null;
|
|
@@ -1547,6 +1553,25 @@ async function gcOrphans({ root, viaDaemon = null, print = (l) => console.log(l)
|
|
|
1547
1553
|
return { ok: true, cancelled: res.cancelled ?? [] };
|
|
1548
1554
|
}
|
|
1549
1555
|
|
|
1556
|
+
/**
|
|
1557
|
+
* `--pause <id> [--for 2h] --reason T` / `--unpause <id>` (#5975): the batch's `pause` file, through the daemon (`viaDaemon(op, meta)`,
|
|
1558
|
+
* null when none runs) or directly. Admission stops for every issue, later re-admissions, requeues and adds included; running lanes
|
|
1559
|
+
* are untouched. @returns {{ok, batch, pause}}
|
|
1560
|
+
*/
|
|
1561
|
+
async function pauseBatch({ op, id, root, viaDaemon = null, meta = null, print = (l) => console.log(l) }) {
|
|
1562
|
+
if (!id || String(id).startsWith("--")) throw new Error(ORCH_USAGE);
|
|
1563
|
+
if (op === "pause" && !meta?.reason) throw new Error("--pause needs --reason <text>");
|
|
1564
|
+
let res = viaDaemon ? await viaDaemon(op, meta) : null;
|
|
1565
|
+
if (!res) {
|
|
1566
|
+
const b = (await import("./lean/batch.mjs")).openBatch(root, id);
|
|
1567
|
+
if (!b.exists()) throw new Error(`no batch ${id} in ${root}`);
|
|
1568
|
+
res = op === "pause" ? { pause: b.setPause(meta) } : { changed: b.clearPause() };
|
|
1569
|
+
}
|
|
1570
|
+
print(op === "pause" ? `batch ${id}: paused (${meta.reason}, until ${res.pause?.expiresAt ?? "unpause"}); running lanes continue; forgedock orchestrate --unpause ${id} re-admits`
|
|
1571
|
+
: res.changed === false ? `batch ${id}: not paused` : `batch ${id}: unpaused`);
|
|
1572
|
+
return { ok: true, batch: id, pause: res.pause ?? null };
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1550
1575
|
/**
|
|
1551
1576
|
* `--hold <id> N...` / `--release <id> N...` (#4592): the batch's `hold` file, through the daemon (`viaDaemon(op, issues)`, null
|
|
1552
1577
|
* when none runs) or directly. A held issue is not admitted (a running lane is not stopped); `--release` (or a `--resume` that
|
|
@@ -1692,6 +1717,11 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1692
1717
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1693
1718
|
return sock ? schedd.request(sock, { op, id, issues, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1694
1719
|
};
|
|
1720
|
+
const viaPause = async (id, op, meta) => {
|
|
1721
|
+
let sock = null;
|
|
1722
|
+
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1723
|
+
return sock ? schedd.request(sock, { op, id, ...(meta ? { meta } : {}) }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1724
|
+
};
|
|
1695
1725
|
const batchRootOf = async () => (await import("./lean/batch.mjs")).batchRoot();
|
|
1696
1726
|
if (["--show-env", "--set-env", "--unset-env"].some((f) => argv.includes(f))) return envBatch({ argv, root: await batchRootOf() });
|
|
1697
1727
|
if (argv.includes("--clear-breaker")) return runBatch({ argv, deps, sink: consoleSink() });
|
|
@@ -1712,6 +1742,10 @@ async function orchestrateClient(argv, deps = {}) {
|
|
|
1712
1742
|
try { sock = await schedd.connectDaemon({ dir, spawnDaemon: null }); } catch { sock = null; }
|
|
1713
1743
|
return sock ? schedd.request(sock, { op: "gc-orphans" }, undefined, { timeoutMs: schedd.REQUEST_MS }) : null;
|
|
1714
1744
|
} });
|
|
1745
|
+
for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
|
|
1746
|
+
const id = flag(argv, flagName), pv = (_o, meta) => viaPause(id, op, meta);
|
|
1747
|
+
return pauseBatch({ op, id, root: await batchRootOf(), viaDaemon: pv, meta: op === "pause" ? holdMetaAll(argv) : null });
|
|
1748
|
+
}
|
|
1715
1749
|
for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
|
|
1716
1750
|
const id = flag(argv, `--${op}`);
|
|
1717
1751
|
const root = await batchRootOf(), io = deps.io ?? makeIo();
|
|
@@ -1797,10 +1831,10 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1797
1831
|
try { sock = await schedd.connectDaemon({ dir: deps.scheddDir ?? (await import("./lean/sched.mjs")).schedDir(), spawnDaemon: null }); } catch { sock = null; }
|
|
1798
1832
|
if (sock) {
|
|
1799
1833
|
let r = null;
|
|
1800
|
-
try { r = await schedd.request(sock, { op: "clear-breaker", id: b.id }, undefined, { timeoutMs:
|
|
1834
|
+
try { const waitMs = 2 * (deps.pollMs || 15000); r = await schedd.request(sock, { op: "clear-breaker", id: b.id, waitMs }, undefined, { timeoutMs: waitMs + 5000 }); } catch { r = null; }
|
|
1801
1835
|
if (r?.hosted) {
|
|
1802
|
-
sink.line(`batch ${b.id}: ${r.acknowledged ? (r.cleared ? "breaker cleared" : "no breaker was tripped") : "
|
|
1803
|
-
return { ok: true, batch: b.id, cleared: Boolean(r.cleared), acknowledged: Boolean(r.acknowledged) };
|
|
1836
|
+
sink.line(`batch ${b.id}: ${r.acknowledged ? (r.cleared ? "breaker cleared" : "no breaker was tripped") : "pending: the runner will clear it on its next pass"}${r.acknowledged ? " (live runner acknowledged)" : ""}`);
|
|
1837
|
+
return { ok: true, batch: b.id, cleared: Boolean(r.cleared), acknowledged: Boolean(r.acknowledged), ...(r.pending ? { pending: true } : {}) };
|
|
1804
1838
|
}
|
|
1805
1839
|
}
|
|
1806
1840
|
}
|
|
@@ -1836,6 +1870,9 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
1836
1870
|
return requeueBatch({ id: argv[i + 1], tokens: operandsOf(argv.slice(i + 2)), reason: flag(argv, "--reason"), root, io: deps.io ?? makeIo(), requireHost: true, force: forceOf(argv), print: (l) => sink.line(l) });
|
|
1837
1871
|
}
|
|
1838
1872
|
if (argv.includes("--gc-orphans")) return gcOrphans({ root, print: (l) => sink.line(l) });
|
|
1873
|
+
for (const [flagName, op] of [["--pause", "pause"], ["--unpause", "unpause"], ["--hold", "pause"]]) if (argv.includes(flagName) && (flagName !== "--hold" || argv.includes("--all"))) { // #5975: `--hold <id> --all` is sugar for `--pause`
|
|
1874
|
+
return pauseBatch({ op, id: flag(argv, flagName), root, meta: op === "pause" ? holdMetaAll(argv) : null, print: (l) => sink.line(l) });
|
|
1875
|
+
}
|
|
1839
1876
|
for (const op of ["hold", "release"]) if (argv.includes(`--${op}`)) {
|
|
1840
1877
|
const hid = flag(argv, `--${op}`);
|
|
1841
1878
|
return holdBatch({ op, id: hid, tokens: operandsOf(argv.slice(argv.indexOf(`--${op}`) + 2)), root, meta: op === "hold" ? holdMeta(argv) : null, print: (l) => sink.line(l),
|
|
@@ -2309,7 +2346,7 @@ export async function runBatch({ argv, cwd: callerCwd = process.cwd(), env: call
|
|
|
2309
2346
|
trusted: (n) => trustedOf.get(n) === true,
|
|
2310
2347
|
autoChildren,
|
|
2311
2348
|
...(autoMod.addsEpicChildren(autoChildren.mode) ? { getChildren: async () => ({ list: await autoMod.readChildList({ gh: (a) => leanIo.gh(a), repo, fields: childFields ??= await autoMod.hostListFields((a) => leanIo.gh(a)) }), elsewhere: autoMod.liveElsewhere({ batchMod, root, self: batch.id, repo }) }) } : {}),
|
|
2312
|
-
issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
|
|
2349
|
+
issues, parallel, prefilter, resolveLane: laneOf, store: batch.store, getParallel: batch.readParallel, getClearBreaker: batch.peekClearBreaker, consumeClearBreaker: batch.readClearBreaker, ackClearBreaker: batch.ackClearBreaker, getAdded: batch.readAdded, getRequeued: batch.readRequeued, getCancelled: batch.readCancel, getHeld: batch.readHeld, expireHolds: batch.expireHolds, getPause: batch.readPause, expirePause: batch.expirePause, getHoldInfo: batch.readHoldInfo, getGates: batch.readGates, baseWait: baseWaits.size ? baseWaitOf(baseWaits, { io, leanIo, cwd }) : null, ...lanes,
|
|
2313
2350
|
breaker: orch.breaker, maxDeferrals: orch.maxDeferrals, ...(Number.isInteger(orch.transientRetries) ? { transientRetries: orch.transientRetries } : {}), ...(deps.pollMs ? { pollMs: deps.pollMs } : {}), ...budget, limits, identity, rotator, batchId: batch.id, drift, lifecycle, integration,
|
|
2314
2351
|
...(registry ? { sched: { registry, batch: batch.id, repo, cap: liveLaneCap(orch.globalParallel ?? null, { cfg: readAdmission(cwd), host: { cores: () => cpus().length, memAvailableMb, rampingMb: rampProbe.rampingMb } }), exclusive: true }, priorityOf: async (n) => schedMod.priorityFromLabels(await labelNames(n)) } : {}),
|
|
2315
2352
|
// #5174: hold new local admissions while loadavg/cores is above engine.overload_load_per_core (host-wide batches only)
|
|
@@ -2700,13 +2737,14 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2700
2737
|
const bm = await import("./lean/batch.mjs");
|
|
2701
2738
|
const unfinished = () => { const root = bm.batchRoot(); return bm.listBatches(root).filter((id) => { try { const b = bm.openBatch(root, id); const br = b.store.peek()?.breaker; return !!b.readPlan()?.daemon && !b.isTerminal() && b.pendingIssues().length > 0 && !(br && !br.transport); } catch { return false; } }); };
|
|
2702
2739
|
const start = () => { if (schedd.unitState() === null) schedd.defaultSpawn({ dir }); else schedd.startUnit(); };
|
|
2740
|
+
const unit = deps.unitState ?? schedd.unitState; // #5966: active unit but no daemon is alerted and the unit restarted
|
|
2703
2741
|
const batchVerdicts = () => schedd.batchVerdicts(bm.batchRoot());
|
|
2704
|
-
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts });
|
|
2742
|
+
return (deps.watchdog ?? health.watchdog)({ dir, ...(sec > 0 ? { stallMs: sec * 1000 } : {}), unfinished, start, batchVerdicts, unit });
|
|
2705
2743
|
}
|
|
2706
2744
|
if (argv.length) throw new Error("usage: forgedock schedd [status | watchdog [--stall-sec N]]");
|
|
2707
2745
|
(deps.renice ?? (await import("./lean/schedd-health.mjs")).bestEffortRenice)(); // #4780: lanes must not starve the scheduler
|
|
2708
2746
|
process.title = "forgedock-schedd"; // distinctive name for OOM-killer avoid lists and ps (#4673)
|
|
2709
|
-
const d = await schedd.startDaemon({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
|
|
2747
|
+
const d = await schedd.startDaemon({ dir, runBatch: (a) => runBatch({ ...a, daemon: true, deps: deps.batchDeps ?? {} }), exit: deps.exit ?? ((c) => process.exit(c)), ...(deps.due !== undefined ? { due: deps.due } : { due: scheddDue }),
|
|
2710
2748
|
...(deps.daemonPreflight !== undefined ? { preflight: deps.daemonPreflight } : deps.batchDeps ? {} : { preflight: async () => { const lc = await import("./lean/lanecheck.mjs"); return (await lc.runLaneChecks({ exec: readExecution(process.cwd()), io: await lc.hostLaneIo() })).filter((c) => !c.ok); } }) });
|
|
2711
2749
|
if (!d.running) {
|
|
2712
2750
|
// #4775: under systemd, exiting here (code 0) makes `Restart=always` loop while another daemon holds the lock: stand by, take over when it dies
|
|
@@ -2718,7 +2756,14 @@ export async function scheddFromCli(argv, deps = {}) {
|
|
|
2718
2756
|
// #4454: a signal stops the hosted batch loops, then releases the lock and socket, then exits 128+signo
|
|
2719
2757
|
schedd.exitOnSignals(d, { ...(deps.processOn ? { on: deps.processOn } : {}), ...(deps.exit ? { exit: deps.exit } : {}) });
|
|
2720
2758
|
await d.closed;
|
|
2721
|
-
|
|
2759
|
+
await d.settled?.(); // #5984: a self-stop keeps spawning/probing the successor after `closed`; exiting now would leave no daemon
|
|
2760
|
+
// #5966 R1: a handover whose successor never listened re-hosted the batches in a new daemon; follow it to its end
|
|
2761
|
+
let cur = d;
|
|
2762
|
+
while (cur.rehosted?.()) { cur = cur.rehosted(); await cur.closed; await cur.settled?.(); }
|
|
2763
|
+
// #5966: a self-initiated stop (handover, stall recovery, lost socket) exits non-zero so systemd restarts the unit instead of leaving a zombie
|
|
2764
|
+
const code = cur.stopCode?.();
|
|
2765
|
+
if (code) (deps.exit ?? ((c) => process.exit(c)))(code);
|
|
2766
|
+
return { running: false, ...(code ? { exitCode: code } : {}) };
|
|
2722
2767
|
}
|
|
2723
2768
|
|
|
2724
2769
|
/**
|
|
@@ -325,8 +325,9 @@ export function runningSplit(state, parallel = null) {
|
|
|
325
325
|
* not held, no retry-at in the future, every in-batch dependency ended well. Independent of the runner (it may be dead), so the
|
|
326
326
|
* schedd polls it. `hosted`: a runner is alive. `gates` (#5745): the failing preflight checks `[{code, detail}]` holding admission, named in the detail. @returns null (healthy) or `{code, ready, idleMin, hosted, detail[, gates]}`. Pure.
|
|
327
327
|
*/
|
|
328
|
-
export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [], lanesAliveMs = null } = {}) {
|
|
328
|
+
export function evaluateDispatchStall(state, { held = [], parallel = null, hosted = false, lastProgressMs = null, now = Date.now(), windowMin = DEFAULT_STALL_MIN, cancelled = false, reported = false, gates = [], lanesAliveMs = null, paused = null } = {}) {
|
|
329
329
|
if (!state || cancelled || reported || lastProgressMs === null) return null;
|
|
330
|
+
if (paused) return null; // #5975: an operator pause is an intended wait, not a dispatch stall
|
|
330
331
|
if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
|
|
331
332
|
const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
|
|
332
333
|
const running = Object.keys(state.running ?? {}).length;
|
|
@@ -373,15 +374,18 @@ export function recordStallRecovery(batch, stall, { action, sig = stall.ready.jo
|
|
|
373
374
|
return text;
|
|
374
375
|
}
|
|
375
376
|
|
|
377
|
+
/** #5975: `paused (reason, until …)`, the text every surface shows for a batch pause. */
|
|
378
|
+
export const pausedText = (p) => `paused (${p?.reason ?? "no reason given"}, until ${p?.expiresAt ?? "unpause"})`;
|
|
379
|
+
|
|
376
380
|
/** The first-hour report of one batch: dispatched / running / merged / stuck, and why. Pure. */
|
|
377
|
-
export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null } = {}) {
|
|
381
|
+
export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null, paused = null } = {}) {
|
|
378
382
|
const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
|
|
379
383
|
const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
|
|
380
384
|
const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
|
|
381
385
|
const why = (n) => results[n]?.outcome ? `#${n} ${results[n].outcome}` : heldSet.has(n) ? `#${n} held${holdInfo?.[n] ? ` (${holdInfo[n].owner}, since ${holdInfo[n].since})` : ""}` : Number(state?.notBefore?.[n]) > now ? `#${n} waiting on a retry` : `#${n} pending`;
|
|
382
386
|
const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
|
|
383
387
|
const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
|
|
384
|
-
const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
|
|
388
|
+
const reasons = [...(paused ? [pausedText(paused)] : []), ...stuck.map(why), ...(stall ? [stall.detail] : [])];
|
|
385
389
|
const summary = `first hour: ${dispatched}/${order.length} dispatched, ${running.length} running, ${merged.length} merged, ${stuck.length} stuck${reasons.length ? ` (${reasons.slice(0, 6).join("; ")})` : ""}`;
|
|
386
390
|
return { batch: batchId, at: new Date(now).toISOString(), counts, summary, lines: [`batch ${batchId}: ${summary}`, ...reasons.slice(0, 12).map((r) => ` ${r}`)] };
|
|
387
391
|
}
|
|
@@ -429,7 +433,7 @@ export function batchVerdict(id, stall, decision = null, { acted = false } = {})
|
|
|
429
433
|
|
|
430
434
|
/** #5938: whether the batch still has ready issues with a free lane (the idle window was already met when the stall was stored). */
|
|
431
435
|
const stallStillHolds = (b, now) => {
|
|
432
|
-
try { const state = b.store.peek(); if (!state) return true; return evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: true, lastProgressMs: b.lastProgressMs() ?? now, now, windowMin: 0 }) !== null; } catch { return true; }
|
|
436
|
+
try { const state = b.store.peek(); if (!state) return true; return evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: true, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs() ?? now, now, windowMin: 0 }) !== null; } catch { return true; }
|
|
433
437
|
};
|
|
434
438
|
|
|
435
439
|
/** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
|
|
@@ -439,7 +443,8 @@ export function summaryLines(root, { now = Date.now() } = {}) {
|
|
|
439
443
|
try {
|
|
440
444
|
const b = openBatch(root, id);
|
|
441
445
|
if (b.readReport() || b.readCancel()) continue;
|
|
442
|
-
const fh = readFirstHour(b.dir), h = readHealth(b.dir);
|
|
446
|
+
const fh = readFirstHour(b.dir), h = readHealth(b.dir), pz = b.readPause?.() ?? null;
|
|
447
|
+
if (pz) out.push(` batch ${id}: ${pausedText(pz)}`);
|
|
443
448
|
if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
|
|
444
449
|
if (h?.stall && now - Date.parse(h.stall.at) < 24 * 3600 * 1000 && stallStillHolds(b, now)) out.push(` batch ${id}: DISPATCH STALLED since ${h.stall.at}: ${h.stall.detail}${h.stall.cause ? ` (${h.stall.cause})` : ""}`);
|
|
445
450
|
} catch { /* an unreadable batch has no line */ }
|
package/bin/lean/batch.mjs
CHANGED
|
@@ -225,6 +225,8 @@ export function openBatch(root, id) {
|
|
|
225
225
|
},
|
|
226
226
|
/** #5947: `--clear-breaker` for a hosted runner: the request file (a timestamp) is consumed by the runner, which answers in `clear-breaker.ack`. */
|
|
227
227
|
requestClearBreaker: () => { try { rmSync(f("clear-breaker.ack"), { force: true }); } catch { /* best effort */ } const at = Date.now(); put(f("clear-breaker"), `${at}\n`); return at; },
|
|
228
|
+
/** #5964: the pending request's `at` without deleting it (the runner consumes it after deciding); null when none. */
|
|
229
|
+
peekClearBreaker: () => { try { const at = Number(readFileSync(f("clear-breaker"), "utf8").trim()); return Number.isFinite(at) && at > 0 ? at : true; } catch { return null; } },
|
|
228
230
|
readClearBreaker: () => { try { readFileSync(f("clear-breaker"), "utf8"); rmSync(f("clear-breaker"), { force: true }); return true; } catch { return false; } },
|
|
229
231
|
ackClearBreaker: (info = {}) => put(f("clear-breaker.ack"), JSON.stringify({ at: Date.now(), ...info }) + "\n"),
|
|
230
232
|
readClearBreakerAck: () => readJson(f("clear-breaker.ack")),
|
|
@@ -329,6 +331,23 @@ export function openBatch(root, id) {
|
|
|
329
331
|
self.releaseIssues(due.map((e) => e.issue));
|
|
330
332
|
return out;
|
|
331
333
|
},
|
|
334
|
+
/** #5975: batch-level pause (`pause` file): `{owner, since, expiresAt|null, reason, ownerPid, ownerHost}`; admission stops for every issue, present and future. */
|
|
335
|
+
setPause: ({ owner = "operator", reason = null, forMs = null, ownerPid = null, ownerHost = null } = {}) => {
|
|
336
|
+
const now = Date.now(), rec = { owner: String(owner), since: new Date(now).toISOString(), expiresAt: Number(forMs) > 0 ? new Date(now + Number(forMs)).toISOString() : null, reason: reason ? String(reason) : null, ownerPid: Number.isSafeInteger(ownerPid) ? ownerPid : null, ownerHost: ownerHost ?? null };
|
|
337
|
+
put(f("pause"), JSON.stringify(rec) + "\n");
|
|
338
|
+
return rec;
|
|
339
|
+
},
|
|
340
|
+
/** #5975: the pause record, or null when missing or invalid. */
|
|
341
|
+
readPause: () => { const v = readJson(f("pause")); return v && typeof v === "object" && !Array.isArray(v) && typeof v.since === "string" ? v : null; },
|
|
342
|
+
/** #5975: lift the pause. @returns {boolean} whether one was set */
|
|
343
|
+
clearPause: () => { const had = !!self.readPause(); try { rmSync(f("pause"), { force: true }); } catch { /* already gone */ } return had; },
|
|
344
|
+
/** #5975: lift the pause when its `expiresAt` has passed. @returns {object|null} the expired record (with `ownerGone`) */
|
|
345
|
+
expirePause: (now = Date.now()) => {
|
|
346
|
+
const p = self.readPause();
|
|
347
|
+
if (!p?.expiresAt || !(Date.parse(p.expiresAt) <= now)) return null;
|
|
348
|
+
self.clearPause();
|
|
349
|
+
return { ...p, ownerGone: ownerGone(p) };
|
|
350
|
+
},
|
|
332
351
|
/** Remove `list` from the `hold` file. @returns {number[]} the issues that were held */
|
|
333
352
|
releaseIssues: (list) => {
|
|
334
353
|
const have = new Set(readAdded(f("hold")));
|
package/bin/lean/batch.test.mjs
CHANGED
|
@@ -2080,3 +2080,68 @@ describe("#5669: an upgrade handover adopts live lanes instead of requeueing the
|
|
|
2080
2080
|
assert.deepEqual(rows.map((r) => [r.issue, r.outcome]), [[4, "merged"]]);
|
|
2081
2081
|
});
|
|
2082
2082
|
});
|
|
2083
|
+
|
|
2084
|
+
describe("#5975: batch pause", () => {
|
|
2085
|
+
it("pause file: set, read, clear, expiry and invalid content", () => {
|
|
2086
|
+
const b = openBatch(tmpDir("batch-pause5975-"), "b1");
|
|
2087
|
+
b.writePlan({ argv: [], repo: "o/r" });
|
|
2088
|
+
assert.equal(b.readPause(), null);
|
|
2089
|
+
const rec = b.setPause({ owner: "op@h", reason: "release cut", forMs: 7200000 });
|
|
2090
|
+
assert.equal(rec.reason, "release cut");
|
|
2091
|
+
assert.equal(Date.parse(b.readPause().expiresAt) - Date.parse(b.readPause().since), 7200000);
|
|
2092
|
+
assert.equal(b.expirePause(Date.now()), null, "not due yet");
|
|
2093
|
+
const gone = b.expirePause(Date.now() + 7300000);
|
|
2094
|
+
assert.equal(gone.owner, "op@h");
|
|
2095
|
+
assert.equal(b.readPause(), null, "expiry lifts it");
|
|
2096
|
+
b.setPause({ owner: "op@h", reason: "x" });
|
|
2097
|
+
assert.equal(b.expirePause(Date.now() + 1e12), null, "no expiry never expires");
|
|
2098
|
+
assert.equal(b.clearPause(), true);
|
|
2099
|
+
assert.equal(b.clearPause(), false);
|
|
2100
|
+
writeFileSync(join(b.dir, "pause"), "not json");
|
|
2101
|
+
assert.equal(b.readPause(), null);
|
|
2102
|
+
writeFileSync(join(b.dir, "pause"), "[1]");
|
|
2103
|
+
assert.equal(b.readPause(), null);
|
|
2104
|
+
});
|
|
2105
|
+
|
|
2106
|
+
it("through the CLI: --pause needs --reason, records the expiry, --unpause lifts it; sched show lists it", async () => {
|
|
2107
|
+
const root = tmpDir("batch-pause5975-cli-");
|
|
2108
|
+
const b = openBatch(root, "b1");
|
|
2109
|
+
b.writePlan({ argv: [], repo: "o/r" });
|
|
2110
|
+
b.store.save({ order: [1, 2], pending: [1, 2] });
|
|
2111
|
+
const io = { gh: async () => JSON.stringify({ state: "OPEN" }) };
|
|
2112
|
+
await assert.rejects(orchestrateFromCli(["--pause", "b1"], { batchRoot: root, io }), /--reason/);
|
|
2113
|
+
await assert.rejects(orchestrateFromCli(["--pause", "b1", "--reason", "x", "--for", "soon"], { batchRoot: root, io }), /--for expects/);
|
|
2114
|
+
await assert.rejects(orchestrateFromCli(["--pause", "nope", "--reason", "x"], { batchRoot: root, io }), /no batch nope/);
|
|
2115
|
+
const res = await quiet(() => orchestrateFromCli(["--pause", "b1", "--for", "2h", "--reason", "release cut"], { batchRoot: root, io }));
|
|
2116
|
+
assert.equal(res.pause.reason, "release cut");
|
|
2117
|
+
assert.ok(Date.parse(b.readPause().expiresAt) - Date.parse(b.readPause().since) === 2 * 3600000);
|
|
2118
|
+
const { summaryLines } = await import("./batch-health.mjs");
|
|
2119
|
+
assert.ok(summaryLines(root).some((l) => /batch b1: paused \(release cut, until \d{4}-/.test(l)));
|
|
2120
|
+
await quiet(() => orchestrateFromCli(["--unpause", "b1"], { batchRoot: root, io }));
|
|
2121
|
+
assert.equal(b.readPause(), null);
|
|
2122
|
+
assert.ok(!summaryLines(root).some((l) => /paused/.test(l)));
|
|
2123
|
+
});
|
|
2124
|
+
|
|
2125
|
+
it("--hold <id> --all is sugar for --pause; --hold <id> N still holds one issue (#5975)", async () => {
|
|
2126
|
+
const root = tmpDir("batch-pause5975-all-");
|
|
2127
|
+
const b = openBatch(root, "b1");
|
|
2128
|
+
b.writePlan({ argv: [], repo: "o/r" });
|
|
2129
|
+
b.store.save({ order: [1, 2], pending: [1, 2] });
|
|
2130
|
+
const io = { gh: async () => JSON.stringify({ state: "OPEN" }) };
|
|
2131
|
+
await quiet(() => orchestrateFromCli(["--hold", "b1", "1"], { batchRoot: root, io }));
|
|
2132
|
+
assert.equal(b.readPause(), null, "a per-issue hold does not pause the batch");
|
|
2133
|
+
await quiet(() => orchestrateFromCli(["--hold", "b1", "--all", "--for", "2h"], { batchRoot: root, io }));
|
|
2134
|
+
assert.equal(b.readPause().reason, "--hold --all");
|
|
2135
|
+
assert.ok(Date.parse(b.readPause().expiresAt) > Date.parse(b.readPause().since));
|
|
2136
|
+
await quiet(() => orchestrateFromCli(["--unpause", "b1"], { batchRoot: root, io }));
|
|
2137
|
+
assert.equal(b.readPause(), null);
|
|
2138
|
+
});
|
|
2139
|
+
|
|
2140
|
+
it("a paused batch is not a dispatch stall", async () => {
|
|
2141
|
+
const { evaluateDispatchStall } = await import("./batch-health.mjs");
|
|
2142
|
+
const state = { order: [1], pending: [1], results: {}, running: {}, parallel: 1 };
|
|
2143
|
+
const opts = { hosted: true, lastProgressMs: 0, now: 3600000 * 5, windowMin: 10 };
|
|
2144
|
+
assert.ok(evaluateDispatchStall(state, opts), "unpaused: a stall");
|
|
2145
|
+
assert.equal(evaluateDispatchStall(state, { ...opts, paused: { reason: "x" } }), null);
|
|
2146
|
+
});
|
|
2147
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #5964: the runner's decision on a hosted `--clear-breaker` request. The request carries the time it was made;
|
|
3
|
+
* it clears only a breaker that tripped at or before it, so a stale request cannot close a later trip.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @param {{tripped: ({at?: number}|null|undefined), requestAt: (number|boolean|null|undefined)}} p
|
|
8
|
+
* @returns {{clear: boolean, stale: boolean}} `clear`: reset the breaker; `stale`: the request predates the current trip (discard it)
|
|
9
|
+
*/
|
|
10
|
+
export function decideClear({ tripped, requestAt }) {
|
|
11
|
+
if (requestAt === true) return { clear: true, stale: false }; // legacy boolean seam: unconditional
|
|
12
|
+
if (typeof requestAt !== "number" || !Number.isFinite(requestAt)) return { clear: false, stale: false };
|
|
13
|
+
if (tripped && Number.isFinite(tripped.at) && tripped.at > requestAt) return { clear: false, stale: true };
|
|
14
|
+
return { clear: true, stale: false };
|
|
15
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5964: hosted --clear-breaker is a durable, time-scoped request the runner consumes on its next pass, however long that is.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
|
+
import { decideClear } from "./clear-breaker.mjs";
|
|
10
|
+
import { openBatch } from "./batch.mjs";
|
|
11
|
+
import { orchestrate } from "./orchestrate.mjs";
|
|
12
|
+
import { runBatch } from "../engine-cli.mjs";
|
|
13
|
+
|
|
14
|
+
const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {}, peek: () => st }; };
|
|
15
|
+
const EE = (detail) => ({ terminalReason: "engine-error", detail });
|
|
16
|
+
const MERGED = { terminalReason: "merged", pr: 9 };
|
|
17
|
+
|
|
18
|
+
/** A runner whose every pass costs 12 s of injected time; `req` is the pending request `at` (or null), made `reqAfterMs` after the trip. */
|
|
19
|
+
const slowRun = async ({ reqAfterMs }) => {
|
|
20
|
+
let t = 1_000_000, tripAt = null, req = null, consumed = 0; const acks = [], calls = [];
|
|
21
|
+
const script = { 1: [EE("boom A")], 2: [EE("boom B")], 3: [MERGED] };
|
|
22
|
+
const rows = await orchestrate({ issues: [1, 2, 3], parallel: 1, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
|
|
23
|
+
sleep: async (ms) => { t += Math.max(12000, Number(ms) || 0); },
|
|
24
|
+
runOne: async (n) => { calls.push(n); t += 12000; return script[n][0]; },
|
|
25
|
+
onUpdate: (u) => { if (u.outcome === "breaker" && tripAt === null) { tripAt = t; req = tripAt + reqAfterMs; } },
|
|
26
|
+
getClearBreaker: () => req, consumeClearBreaker: () => { req = null; consumed++; }, ackClearBreaker: (i) => acks.push(i) });
|
|
27
|
+
return { rows, acks, calls, consumed };
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
describe("#5964 decideClear", () => {
|
|
31
|
+
it("clears a trip at or before the request; never a later one; boolean is legacy; nothing without a request", () => {
|
|
32
|
+
assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 150 }), { clear: true, stale: false });
|
|
33
|
+
assert.deepEqual(decideClear({ tripped: { at: 100 }, requestAt: 100 }), { clear: true, stale: false });
|
|
34
|
+
assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: 150 }), { clear: false, stale: true });
|
|
35
|
+
assert.deepEqual(decideClear({ tripped: { at: 200 }, requestAt: true }), { clear: true, stale: false });
|
|
36
|
+
assert.deepEqual(decideClear({ tripped: null, requestAt: 150 }), { clear: true, stale: false });
|
|
37
|
+
for (const requestAt of [null, false, undefined, NaN, "x"]) assert.deepEqual(decideClear({ tripped: { at: 1 }, requestAt }), { clear: false, stale: false }, String(requestAt));
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe("#5964 runner pass", () => {
|
|
42
|
+
it("slow pass: request survives and next pass clears (a request 1 s into a 12 s pass is cleared and acked on the next pass, and admissions resume)", async () => {
|
|
43
|
+
const r = await slowRun({ reqAfterMs: 1000 });
|
|
44
|
+
assert.ok(r.acks.some((a) => a.cleared === true), "acked a real clear");
|
|
45
|
+
assert.equal(r.consumed, 1);
|
|
46
|
+
assert.ok(r.calls.includes(3), "issue 3 was admitted after the clear");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("a request older than a later trip does not clear it (stale), and is consumed", async () => {
|
|
50
|
+
const r = await slowRun({ reqAfterMs: -5000 });
|
|
51
|
+
assert.equal(r.acks.some((a) => a.cleared === true), false);
|
|
52
|
+
assert.equal(r.consumed, 1);
|
|
53
|
+
assert.equal(r.calls.includes(3), false, "the later trip stays closed");
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe("#5964 slow pass over the real batch request file", () => {
|
|
58
|
+
it("slow pass: a request made 1 s into a 12 s pass stays on disk, the next pass clears tripped, acks, consumes it, and admissions resume", async () => {
|
|
59
|
+
const root = tmpDir("clrbrk-"); const b = openBatch(root, "b3"); b.store.save({ id: "b3" });
|
|
60
|
+
let t = 1_000_000, tripped = false, requested = false, release = null, onDiskAtNextPass = null; const calls = [], acks = [];
|
|
61
|
+
const gate = new Promise((r) => { release = r; });
|
|
62
|
+
const script = { 1: EE("boom A"), 2: EE("boom B"), 3: null, 4: MERGED };
|
|
63
|
+
const rows = await orchestrate({ issues: [1, 2, 3, 4], parallel: 3, readBody: async () => "", now: () => t, store: memStore(), pollMs: 12000, breaker: { errors: 2, window_min: 10 },
|
|
64
|
+
sleep: async () => {
|
|
65
|
+
if (tripped && !requested) { requested = true; b.requestClearBreaker(); t += 12000; release(); } // the request lands during a 12 s pass
|
|
66
|
+
else t += 12000;
|
|
67
|
+
},
|
|
68
|
+
runOne: async (n) => { calls.push(n); if (n === 3) { await gate; return MERGED; } return script[n]; },
|
|
69
|
+
onUpdate: (u) => { if (u.outcome === "breaker") tripped = true; },
|
|
70
|
+
getClearBreaker: () => { if (requested && onDiskAtNextPass === null) onDiskAtNextPass = existsSync(join(root, "b3", "clear-breaker")); return b.peekClearBreaker(); },
|
|
71
|
+
consumeClearBreaker: b.readClearBreaker, ackClearBreaker: (i) => { acks.push(i); b.ackClearBreaker(i); } });
|
|
72
|
+
assert.equal(onDiskAtNextPass, true, "the request survived until the runner's next pass");
|
|
73
|
+
assert.equal(acks.some((a) => a.cleared === true), true, "tripped was cleared and acked");
|
|
74
|
+
assert.equal(b.readClearBreakerAck().cleared, true);
|
|
75
|
+
assert.equal(existsSync(join(root, "b3", "clear-breaker")), false, "consumed after the decision");
|
|
76
|
+
assert.ok(calls.includes(4), "admissions resumed (issue 4 ran) with no restart");
|
|
77
|
+
assert.equal(rows.find((r) => r.issue === 4)?.outcome, "merged");
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
describe("#5964 batch request file and CLI", () => {
|
|
82
|
+
it("peekClearBreaker returns the request time without deleting it; readClearBreaker consumes", () => {
|
|
83
|
+
const root = tmpDir("clrbrk-"); const b = openBatch(root, "b1"); b.store.save({ id: "b1" });
|
|
84
|
+
assert.equal(b.peekClearBreaker(), null);
|
|
85
|
+
const at = b.requestClearBreaker();
|
|
86
|
+
assert.equal(b.peekClearBreaker(), at);
|
|
87
|
+
assert.equal(existsSync(join(root, "b1", "clear-breaker")), true, "peek leaves the file");
|
|
88
|
+
assert.equal(b.readClearBreaker(), true);
|
|
89
|
+
assert.equal(b.peekClearBreaker(), null);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("unhosted (no daemon) batch keeps the direct state.json rewrite", async () => {
|
|
93
|
+
const root = tmpDir("clrbrk-"); const b = openBatch(root, "b2"); b.store.save({ id: "b2", breaker: { at: 1 }, errorTimes: [1] }); writeFileSync(join(root, "b2", "plan.json"), "{}");
|
|
94
|
+
const lines = [];
|
|
95
|
+
const r = await runBatch({ argv: ["--clear-breaker", "b2"], deps: { batchRoot: root, noDaemon: true }, sink: { line: (l) => lines.push(l) } });
|
|
96
|
+
assert.equal(r.cleared, true);
|
|
97
|
+
assert.equal(b.store.load().breaker, null);
|
|
98
|
+
assert.match(lines[0], /breaker cleared/);
|
|
99
|
+
});
|
|
100
|
+
});
|
package/bin/lean/depcache.mjs
CHANGED
|
@@ -26,6 +26,15 @@ import { join, dirname, basename, relative, resolve, isAbsolute } from "node:pat
|
|
|
26
26
|
import { safeSegment } from "./ledger.mjs";
|
|
27
27
|
|
|
28
28
|
export const depcacheRoot = (env = process.env) => String(env.FORGE_DEPCACHE_ROOT ?? "").trim() || join(homedir(), ".forge", "depcache");
|
|
29
|
+
/**
|
|
30
|
+
* #5901: the per-repo directory under the cache root. A pool lane's checkout is `/cache/work/<sandbox-id>`, so a key made
|
|
31
|
+
* from the checkout path is new for every lane and every lane installs its own copy. The repo slug (`owner/repo`) is the
|
|
32
|
+
* same for all of them; `fallback` (the path-based key) is used only when no repo is known.
|
|
33
|
+
*/
|
|
34
|
+
export const depcacheNamespace = ({ repo, fallback } = {}) => {
|
|
35
|
+
const slug = String(repo ?? "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "_").replace(/^[._]+|[._]+$/g, "");
|
|
36
|
+
return slug || fallback;
|
|
37
|
+
};
|
|
29
38
|
export const DEPCACHE_INSTALL_TIMEOUT_MS = 15 * 60000;
|
|
30
39
|
export const DEPCACHE_MAX_AGE_MS = 7 * 24 * 3600 * 1000;
|
|
31
40
|
const STORES = "stores";
|
package/bin/lean/execution.mjs
CHANGED
|
@@ -144,6 +144,7 @@ export function parseExecution(sec = {}) {
|
|
|
144
144
|
const patRaw = Array.isArray(s.host_capability_patterns) ? s.host_capability_patterns : str(s.host_capability_patterns) ? str(s.host_capability_patterns).split(",") : [];
|
|
145
145
|
const hostCapabilityPatterns = patRaw.map((x) => { const t = str(x), i = t.indexOf(":"); return { name: t.slice(0, i).trim().toLowerCase(), pattern: t.slice(i + 1).trim() }; })
|
|
146
146
|
.filter((x) => CAPABILITY_RE.test(x.name) && x.pattern && safeRegExp(x.pattern));
|
|
147
|
+
const repoSource = ["dispatcher", "github", "auto"].includes(str(s.repo_source).toLowerCase()) ? str(s.repo_source).toLowerCase() : null; // #5949: where a pool sandbox's repo mirror comes from; unset = auto
|
|
147
148
|
const wsN = Number(str(s.warm_sandboxes));
|
|
148
149
|
const warmSandboxes = str(s.warm_sandboxes) !== "" && Number.isInteger(wsN) && wsN > 0 ? wsN : 0; // #4912: warm sandboxes the pool agent keeps ready; 0 = off
|
|
149
150
|
const lt = validateLaneTools(s.lane_tools); // #5650: invalid entries are dropped here and reported in laneToolsErrors; the remote provider refuses to start with them
|
|
@@ -160,7 +161,7 @@ export function parseExecution(sec = {}) {
|
|
|
160
161
|
const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
|
|
161
162
|
const publicDefault = str(s.public_default).toLowerCase() === "actions" ? "actions" : null; // #5900: opt-in only
|
|
162
163
|
const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
|
|
163
|
-
return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
|
|
164
|
+
return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
|
|
164
165
|
}
|
|
165
166
|
|
|
166
167
|
const round1 = (x) => Math.round(x * 10) / 10;
|
|
@@ -667,7 +668,7 @@ export function providerByName(name, opts) {
|
|
|
667
668
|
// #4685/#5131: an empty env/keychain lookup of `token_env` falls back to `token_file`, then the (matching) router's token file.
|
|
668
669
|
const credentials = (n) => (n === tokenEnv ? resolve().token : resolveCredential(n, { env, keychain })); // per call, keychain memoised (#5159)
|
|
669
670
|
const settings = { ...exec, ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(forgeYaml ? { forgeYaml } : {}),
|
|
670
|
-
...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}) }; // #4778: dispatch-time relay pre-fetch
|
|
671
|
+
...(typeof opts?.prefetch === "function" ? { prefetch: opts.prefetch } : {}), ...(pool && opts?.cwd ? { repoDir: opts.cwd } : {}) }; // #4778; #5949: the dispatcher's clone seeds the pool mirror: dispatch-time relay pre-fetch
|
|
671
672
|
return remoteProvider({ batch: opts.batch, repo: opts.repo, settings, ...(pool ? { name: "pool" } : {}), env, credentials,
|
|
672
673
|
transport: remoteTransportFor(settings, { transport: opts?.transport, env, credentials, ...(opts?.fetchFn ? { fetchFn: opts.fetchFn } : {}) }), ...(opts?.now ? { now: opts.now } : {}) });
|
|
673
674
|
}
|
package/bin/lean/lean.mjs
CHANGED
|
@@ -41,6 +41,7 @@ import { ceilingFor, modelInfo, restartDecision, DEFAULT_CEILING, WINDOW_SHARE,
|
|
|
41
41
|
import { dockerLabels, LEDGER_TTL_MS } from "./ledger.mjs";
|
|
42
42
|
import { batchImageCache, envNamesOf, provisionSandboxes } from "./testsandbox.mjs";
|
|
43
43
|
import { repoKey, estimateCostUsd } from "../runner.mjs";
|
|
44
|
+
import { depcacheNamespace } from "./depcache.mjs";
|
|
44
45
|
import { prepareToolchain } from "./toolchain.mjs";
|
|
45
46
|
import { toolStats } from "./toolstats.mjs";
|
|
46
47
|
import { readTestMap, readTestMapAtRef, selectCommands, mergeChecks, factsPath, TEST_MAP_FILE } from "./testmap.mjs";
|
|
@@ -1819,7 +1820,7 @@ export async function runCore(o) {
|
|
|
1819
1820
|
if (io.deps?.prepare) {
|
|
1820
1821
|
const tD = now();
|
|
1821
1822
|
let res;
|
|
1822
|
-
try { res = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); } catch (e) { res = [{ status: "failed", eco: null, key: null, ms: 0, reason: String(e?.message ?? e).slice(0, 300) }]; }
|
|
1823
|
+
try { res = await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); } catch (e) { res = [{ status: "failed", eco: null, key: null, ms: 0, reason: String(e?.message ?? e).slice(0, 300) }]; }
|
|
1823
1824
|
depResults = Array.isArray(res) ? res : []; // #5447: classified against the changed files at the gate
|
|
1824
1825
|
setupStep("deps", tD);
|
|
1825
1826
|
for (const r of Array.isArray(res) ? res : []) {
|
|
@@ -2642,10 +2643,10 @@ export async function runCore(o) {
|
|
|
2642
2643
|
const projDeps = declaredEnv(frozen).filter((t) => deps5683.owner(t) !== null); // #5683: a sub-project's declared dependency is prepared and resolved through its bin dirs, never a host tool
|
|
2643
2644
|
const probeEnv = async () => { const miss = []; for (const t of declaredEnv(frozen)) { if (deps5683.owner(t) !== null) continue; const r = io.runCommand ? await io.runCommand({ command: t === "pytest" ? "python3 -m pytest --version" : `command -v ${t} >/dev/null || { test -d node_modules/${t} && ! test -e node_modules/.bin/${t}; } || ls -d .venv/lib/python*/site-packages/${t} >/dev/null 2>&1`, cwd: wt, timeoutMs: 30000, env: projEnv() }).catch(() => ({ rc: 1 })) : { rc: 0 }; if ((r?.rc ?? 0) !== 0) miss.push(t); } return miss; };
|
|
2644
2645
|
let envMiss = await probeEnv();
|
|
2645
|
-
if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
|
|
2646
|
+
if (projDeps.length && io.deps?.prepare) { try { await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "TESTPLAN_ENV_PROJECT_DEPS", names: projDeps }); } catch { /* the install gate reports failures */ } }
|
|
2646
2647
|
if (envMiss.length) {
|
|
2647
2648
|
try {
|
|
2648
|
-
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
|
|
2649
|
+
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined });
|
|
2649
2650
|
if (envMiss.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
|
|
2650
2651
|
envMiss = await probeEnv();
|
|
2651
2652
|
ev({ event: "TESTPLAN_ENV_PROVISIONED", remaining: envMiss });
|
|
@@ -2671,10 +2672,10 @@ export async function runCore(o) {
|
|
|
2671
2672
|
const remoteDeps = await depOwnerOf(); // #5683: a tool that is a tracked manifest dependency is prepared in the sandbox, never a lane_tools recipe or a host tool
|
|
2672
2673
|
const ownedDep = (t) => t === "forgedock" || remoteDeps.owner(t) !== null, notOwned = (m) => ({ ...m, tools: m.tools.filter((t) => !ownedDep(t)) });
|
|
2673
2674
|
let tm0 = toolMisses(planMisses ?? await preflightValidates(frozen).catch(() => [])), tm = notOwned(tm0);
|
|
2674
|
-
if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
|
|
2675
|
+
if (tm0.tools.length && !tm.tools.length) { try { if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); ev({ event: "REMOTE_PROJECT_DEPS", tools: tm0.tools }); } catch { /* the install gate reports failures */ } }
|
|
2675
2676
|
if (tm.tools.length) { // #5423: provision the sandbox once (nested lockfiles, pytest) and re-probe before giving the lane up
|
|
2676
2677
|
try {
|
|
2677
|
-
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined });
|
|
2678
|
+
if (io.deps?.prepare) await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined });
|
|
2678
2679
|
if (tm.tools.includes("pytest") && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
|
|
2679
2680
|
tm = notOwned(toolMisses(await preflightValidates(frozen).catch(() => [])));
|
|
2680
2681
|
ev({ event: "REMOTE_PROVISIONED", remaining: tm.tools });
|
|
@@ -3602,7 +3603,7 @@ export async function runCore(o) {
|
|
|
3602
3603
|
if (unrun.length && !gateProvisioned && (io.deps?.prepare || (wantsPytest && io.runCommand))) {
|
|
3603
3604
|
gateProvisioned = true;
|
|
3604
3605
|
try {
|
|
3605
|
-
if (io.deps?.prepare) { const rp = await io.deps.prepare({ wt, repoKey: repoKey(cwd), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : []; }
|
|
3606
|
+
if (io.deps?.prepare) { const rp = await io.deps.prepare({ wt, repoKey: depcacheNamespace({ repo, fallback: repoKey(cwd) }), env: toolchain?.env ?? undefined }); depResults = Array.isArray(rp) ? rp : []; }
|
|
3606
3607
|
if (wantsPytest && io.runCommand) await io.runCommand({ command: "python3 -m pip install --user --quiet pytest", cwd: wt, timeoutMs: 180000, env: laneEnv() });
|
|
3607
3608
|
} catch { /* the rerun below reports what is still missing */ }
|
|
3608
3609
|
ev({ event: "GATE_PROVISIONED", kinds: [...new Set(unrun.map((f) => f.kind))] });
|
package/bin/lean/lean.test.mjs
CHANGED
|
@@ -6715,7 +6715,7 @@ describe("shared dependency cache wiring (#4220)", () => {
|
|
|
6715
6715
|
assert.equal((await run(w, { dir })).terminalReason, "merged");
|
|
6716
6716
|
assert.equal(d.calls.length, 1);
|
|
6717
6717
|
assert.equal(d.calls[0].wt, "/wt/lean-7");
|
|
6718
|
-
assert.
|
|
6718
|
+
assert.equal(d.calls[0].repoKey, "o_r"); // #5901: the repo slug, not the checkout path
|
|
6719
6719
|
assert.equal(d.calls[0].worktreeAdded, true);
|
|
6720
6720
|
const ev = readLog(dir, 7).filter((e) => e.event === "DEPS_PREPARED");
|
|
6721
6721
|
assert.deepEqual(ev.map((e) => [e.status, e.eco, e.key]), [["hit", "pnpm", "0123456789abcdef"]]);
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5949: dispatcher side of repo seeding. Builds an incremental `git bundle` from the dispatching host's own clone (everything the
|
|
5
|
+
* agent's mirror lacks; `--all`-equivalent when the mirror is absent) and uploads it through the pool router in checksummed,
|
|
6
|
+
* resumable chunks (`transport.mirrors` / `transport.seed`). Any failure throws; the caller falls back to the GitHub path.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from "node:child_process";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { promisify } from "node:util";
|
|
11
|
+
|
|
12
|
+
const run = promisify(execFile);
|
|
13
|
+
/** Decoded bytes per chunk (the agent and router cap it at 512 KB). */
|
|
14
|
+
export const CHUNK = 384 * 1024;
|
|
15
|
+
const MAX_CHUNK_RETRIES = 3;
|
|
16
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
17
|
+
const git = async (cwd, args, opts = {}) => (await run("git", args, { cwd, encoding: opts.binary ? "buffer" : "utf8", maxBuffer: 1 << 30 })).stdout;
|
|
18
|
+
|
|
19
|
+
/** The refs to ship: origin's branches (the agent maps them to refs/heads/*; local branches only when there are none) and tags; never the origin/HEAD symref. */
|
|
20
|
+
async function wantRefs(repoDir) {
|
|
21
|
+
const list = async (...pats) => (await git(repoDir, ["for-each-ref", "--format=%(refname)", ...pats])).split("\n").filter(Boolean);
|
|
22
|
+
const origin = (await list("refs/remotes/origin")).filter((r) => r !== "refs/remotes/origin/HEAD");
|
|
23
|
+
return [...(origin.length ? origin : await list("refs/heads")), ...(await list("refs/tags"))];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The bundle bytes for `repoDir` given the agent's `tips` ({ref: sha} or "absent"), or null when the agent already has everything.
|
|
28
|
+
* Tips the dispatcher's repo does not contain are skipped as exclusions (the bundle is then larger, never invalid).
|
|
29
|
+
*/
|
|
30
|
+
export async function buildBundle(repoDir, tips) {
|
|
31
|
+
const refs = await wantRefs(repoDir);
|
|
32
|
+
if (!refs.length) throw new Error("local repo has no refs to bundle");
|
|
33
|
+
const excl = [];
|
|
34
|
+
if (tips && typeof tips === "object") {
|
|
35
|
+
for (const sha of new Set(Object.values(tips))) {
|
|
36
|
+
try { await git(repoDir, ["cat-file", "-e", `${sha}^{commit}`]); excl.push(`^${sha}`); } catch { /* unknown here: not excluded */ }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
try { return await git(repoDir, ["bundle", "create", "-", ...refs, ...excl], { binary: true }); }
|
|
40
|
+
catch (e) { if (/empty bundle/i.test(String(e.stderr))) return null; throw e; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Size of the whole repo's packed objects in bytes (what a full transfer would move). */
|
|
44
|
+
async function repoBytes(repoDir) {
|
|
45
|
+
try { const o = await git(repoDir, ["count-objects", "-v"]); const n = (k) => Number(new RegExp(`^${k}: (\\d+)`, "m").exec(o)?.[1] ?? 0); return (n("size") + n("size-pack")) * 1024; } catch { return 0; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Seed the agent mirror of `slug` for sandbox `id`. Returns {sent, bytes, chunks, full, ms, upToDate}. Throws on any failure;
|
|
50
|
+
* an older router/agent without the endpoints (404/405 from `transport.mirrors`) throws `{unsupported: true}`.
|
|
51
|
+
*/
|
|
52
|
+
export async function seedMirror({ transport, id, slug, cacheKey = null, repoDir, now = () => Date.now() }) {
|
|
53
|
+
if (typeof transport.mirrors !== "function" || typeof transport.seed !== "function") throw Object.assign(new Error("transport has no mirror seeding"), { unsupported: true });
|
|
54
|
+
const t0 = now();
|
|
55
|
+
if (!(await wantRefs(repoDir).catch(() => [])).length) throw new Error("local repo has no refs to bundle"); // nothing to seed from: no round trip
|
|
56
|
+
const q = await transport.mirrors(id, { slug, cache_key: cacheKey });
|
|
57
|
+
const tips = q?.mirrors?.[slug];
|
|
58
|
+
if (tips === undefined) throw Object.assign(new Error("agent answered /mirrors without this repo"), { unsupported: true });
|
|
59
|
+
const full = tips === "absent";
|
|
60
|
+
const bundle = await buildBundle(repoDir, full ? null : tips);
|
|
61
|
+
if (!bundle) return { sent: false, bytes: 0, chunks: 0, full, ms: now() - t0, upToDate: true };
|
|
62
|
+
const upload = sha256(bundle), base = { slug, cache_key: cacheKey, upload };
|
|
63
|
+
let offset = (await transport.mirrors(id, { slug, cache_key: cacheKey, upload }))?.upload_offset ?? 0, chunks = 0, sent = 0;
|
|
64
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > bundle.length) offset = 0;
|
|
65
|
+
while (offset < bundle.length) {
|
|
66
|
+
const buf = bundle.subarray(offset, offset + CHUNK);
|
|
67
|
+
const body = { ...base, offset, data_b64: buf.toString("base64"), sha256: sha256(buf) };
|
|
68
|
+
let res = null;
|
|
69
|
+
for (let attempt = 0; attempt < MAX_CHUNK_RETRIES && res === null; attempt++) {
|
|
70
|
+
try { res = await transport.seed(id, body); }
|
|
71
|
+
catch (e) {
|
|
72
|
+
if (e.status === 409 && Number.isInteger(e.offset)) { res = { offset: e.offset, resumed: true }; break; } // the agent has a different length: resume from its offset
|
|
73
|
+
if (e.status && e.status < 500 && e.status !== 429) throw e;
|
|
74
|
+
if (attempt === MAX_CHUNK_RETRIES - 1) throw e;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (!res.resumed) { sent += buf.length; chunks++; }
|
|
78
|
+
offset = res.offset;
|
|
79
|
+
}
|
|
80
|
+
await transport.seed(id, { ...base, finish: { size: bundle.length, sha256: upload } });
|
|
81
|
+
const ms = now() - t0, whole = await repoBytes(repoDir);
|
|
82
|
+
const saved_ms = sent > 0 && ms > 0 && whole > sent ? Math.round(((whole - sent) / sent) * ms) : null; // estimate: the whole repo at this upload's own rate
|
|
83
|
+
return { sent: true, bytes: sent, bundle_bytes: bundle.length, chunks, full, ms, saved_ms, upToDate: false };
|
|
84
|
+
}
|