forgedock 1.65.0 → 1.67.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/config-schema.mjs +2 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +143 -19
- package/bin/forgedock.mjs +7 -0
- package/bin/help-text.mjs +3 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/advisory.test.mjs +49 -0
- package/bin/lean/amendment-schema.mjs +31 -0
- package/bin/lean/attempts.mjs +159 -0
- package/bin/lean/attempts.test.mjs +127 -0
- package/bin/lean/basered.mjs +55 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +13 -5
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +62 -0
- package/bin/lean/batch.test.mjs +119 -3
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/commentstate.mjs +41 -0
- package/bin/lean/commentstate.test.mjs +32 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +4 -2
- package/bin/lean/conformance.mjs +35 -3
- package/bin/lean/conformance.test.mjs +52 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/execution.mjs +31 -13
- package/bin/lean/execution.test.mjs +46 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/lean.mjs +130 -30
- package/bin/lean/lean.test.mjs +138 -47
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +74 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +84 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +202 -28
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/prompts.mjs +6 -10
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +38 -2
- package/bin/lean/recurrence.test.mjs +56 -1
- package/bin/lean/sandbox-remote.mjs +33 -2
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +19 -0
- package/bin/lean/schedd.mjs +97 -10
- package/bin/lean/schedd.test.mjs +138 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +37 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/verify.mjs +2 -1
- package/bin/pool/agent.mjs +46 -8
- package/bin/pool/cache-sweep.mjs +41 -4
- package/bin/pool/cli.mjs +28 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/lane-tools.mjs +21 -0
- package/bin/pool/mirror-seed.mjs +21 -2
- package/bin/pool/router.mjs +6 -2
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +1 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +2 -1
- package/scripts/check-devdocs-freshness.sh +1 -1
|
@@ -13,6 +13,7 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
|
|
13
13
|
import { spawn as spawnProc } from "node:child_process";
|
|
14
14
|
import { join } from "node:path";
|
|
15
15
|
import { listBatches, openBatch, REQUEUABLE, writeAtomic } from "./batch.mjs";
|
|
16
|
+
import { efficiencyLine, readEfficiency } from "./efficiency.mjs";
|
|
16
17
|
|
|
17
18
|
export const DEFAULT_HEALTH = Object.freeze({ rootFailed: true, terminalShare: 0.5, stalled: true, checksMin: Object.freeze([15, 60]), issue: null, notifyCommand: null });
|
|
18
19
|
/** #5469: a hold older than this many hours is flagged (`config.holdHours` overrides). */
|
|
@@ -224,6 +225,8 @@ export function batchStatusLines(root, id, { now = Date.now() } = {}) {
|
|
|
224
225
|
const k = Array.isArray(g?.lanes) ? g.lanes.length : Number(g?.requeued) || 0;
|
|
225
226
|
if (g?.agent) out.push(` agent ${g.agent} restarted at ${g.at ?? "?"}; ${k} lane${k === 1 ? "" : "s"} requeued (sandbox.lost)${g.closed ? "" : ", waiting for the agent"}`);
|
|
226
227
|
}
|
|
228
|
+
const eff = efficiencyLine(readEfficiency(b.dir)); // #5987: the efficiency ledger, when the daemon wrote one
|
|
229
|
+
if (eff) out.push(` ${eff}`);
|
|
227
230
|
return out;
|
|
228
231
|
}
|
|
229
232
|
|
|
@@ -325,8 +328,9 @@ export function runningSplit(state, parallel = null) {
|
|
|
325
328
|
* 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
329
|
* 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
330
|
*/
|
|
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 } = {}) {
|
|
331
|
+
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
332
|
if (!state || cancelled || reported || lastProgressMs === null) return null;
|
|
333
|
+
if (paused) return null; // #5975: an operator pause is an intended wait, not a dispatch stall
|
|
330
334
|
if (state.breaker && !state.breaker.transport) return null; // an operator --resume clears it; a re-host would stop again at once
|
|
331
335
|
const order = new Set((state.order ?? []).map(Number)), results = state.results ?? {}, heldSet = new Set(held.map(Number));
|
|
332
336
|
const running = Object.keys(state.running ?? {}).length;
|
|
@@ -373,15 +377,18 @@ export function recordStallRecovery(batch, stall, { action, sig = stall.ready.jo
|
|
|
373
377
|
return text;
|
|
374
378
|
}
|
|
375
379
|
|
|
380
|
+
/** #5975: `paused (reason, until …)`, the text every surface shows for a batch pause. */
|
|
381
|
+
export const pausedText = (p) => `paused (${p?.reason ?? "no reason given"}, until ${p?.expiresAt ?? "unpause"})`;
|
|
382
|
+
|
|
376
383
|
/** 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 } = {}) {
|
|
384
|
+
export function firstHourReport(state, { batchId, now = Date.now(), held = [], stall = null, holdInfo = null, paused = null } = {}) {
|
|
378
385
|
const order = (state?.order ?? []).map(Number), results = state?.results ?? {}, running = Object.keys(state?.running ?? {}).map(Number);
|
|
379
386
|
const merged = order.filter((n) => GOOD_END.has(results[n]?.outcome)), heldSet = new Set(held.map(Number));
|
|
380
387
|
const stuck = order.filter((n) => !running.includes(n) && !GOOD_END.has(results[n]?.outcome) && (results[n] !== undefined || (state?.pending ?? []).map(Number).includes(n)));
|
|
381
388
|
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
389
|
const dispatched = order.filter((n) => results[n] !== undefined || running.includes(n)).length;
|
|
383
390
|
const counts = { total: order.length, dispatched, running: running.length, merged: merged.length, stuck: stuck.length };
|
|
384
|
-
const reasons = [...stuck.map(why), ...(stall ? [stall.detail] : [])];
|
|
391
|
+
const reasons = [...(paused ? [pausedText(paused)] : []), ...stuck.map(why), ...(stall ? [stall.detail] : [])];
|
|
385
392
|
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
393
|
return { batch: batchId, at: new Date(now).toISOString(), counts, summary, lines: [`batch ${batchId}: ${summary}`, ...reasons.slice(0, 12).map((r) => ` ${r}`)] };
|
|
387
394
|
}
|
|
@@ -429,7 +436,7 @@ export function batchVerdict(id, stall, decision = null, { acted = false } = {})
|
|
|
429
436
|
|
|
430
437
|
/** #5938: whether the batch still has ready issues with a free lane (the idle window was already met when the stall was stored). */
|
|
431
438
|
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; }
|
|
439
|
+
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
440
|
};
|
|
434
441
|
|
|
435
442
|
/** `sched show` lines: per unfinished batch, its first-hour summary and any dispatch stall. */
|
|
@@ -439,7 +446,8 @@ export function summaryLines(root, { now = Date.now() } = {}) {
|
|
|
439
446
|
try {
|
|
440
447
|
const b = openBatch(root, id);
|
|
441
448
|
if (b.readReport() || b.readCancel()) continue;
|
|
442
|
-
const fh = readFirstHour(b.dir), h = readHealth(b.dir);
|
|
449
|
+
const fh = readFirstHour(b.dir), h = readHealth(b.dir), pz = b.readPause?.() ?? null;
|
|
450
|
+
if (pz) out.push(` batch ${id}: ${pausedText(pz)}`);
|
|
443
451
|
if (fh?.summary) out.push(` batch ${id}: ${fh.summary}`);
|
|
444
452
|
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
453
|
} catch { /* an unreadable batch has no line */ }
|
|
@@ -406,3 +406,19 @@ describe("#5938 stall verdict is re-evaluated: full K, recovery lanes, pool capa
|
|
|
406
406
|
assert.match(batchVerdict("b1", s, { action: "alert", cause: "no gh" }), /stalled -> no action, needs you \(no gh;/);
|
|
407
407
|
});
|
|
408
408
|
});
|
|
409
|
+
|
|
410
|
+
describe("#5987 efficiency status line", () => {
|
|
411
|
+
it("batch status shows the efficiency line with and without breaches; none without a ledger", async () => {
|
|
412
|
+
const { writeEfficiency } = await import("./efficiency.mjs");
|
|
413
|
+
const root = tmpDir("bh-eff-");
|
|
414
|
+
mkdirSync(join(root, "b1"));
|
|
415
|
+
const b = openBatch(root, "b1");
|
|
416
|
+
b.writePlan({ argv: ["1"], created: new Date().toISOString() });
|
|
417
|
+
assert.ok(!statusLines(root, { batch: "b1" }).some((l) => /efficiency:/.test(l)));
|
|
418
|
+
const eff = { v: 1, concurrency: { running: 3, ceiling: 12, achieved: 3 }, limiters: ["sandbox.capacity", "pool.host_load"], breaches: [] };
|
|
419
|
+
writeEfficiency(b.dir, eff);
|
|
420
|
+
assert.ok(statusLines(root, { batch: "b1" }).includes(" efficiency: 3/12 lanes (25%) - limiter sandbox.capacity pool.host_load"));
|
|
421
|
+
writeEfficiency(b.dir, { ...eff, breaches: [{ issue: 6001 }, { issue: 6001 }] });
|
|
422
|
+
assert.ok(statusLines(root, { batch: "b1" }).includes(" efficiency: 3/12 lanes (25%) - limiter sandbox.capacity pool.host_load; 2 SLO breaches -> FD#6001"));
|
|
423
|
+
});
|
|
424
|
+
});
|
package/bin/lean/batch.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import { spawn } from "node:child_process";
|
|
|
20
20
|
import { createHash } from "node:crypto";
|
|
21
21
|
import { homedir, hostname } from "node:os";
|
|
22
22
|
import { dirname, join, resolve, sep } from "node:path";
|
|
23
|
+
import { humanCode } from "./reconcile.mjs";
|
|
23
24
|
import { sanitizeOverride, validateExecutionPatch } from "./live-execution.mjs";
|
|
24
25
|
|
|
25
26
|
export const RAM_FS = new Set(["tmpfs", "ramfs"]);
|
|
@@ -113,6 +114,23 @@ const readAdded = (file) => {
|
|
|
113
114
|
export const REQUEUABLE = (outcome) => ["needs-human", "engine-error", "held", "invalid", "skipped", "ci-pending", "pr-ready", "budget-exceeded", "lane-refused", "deferred"].includes(outcome) || /^dependency-/.test(String(outcome));
|
|
114
115
|
/** Key of one requeue entry; the runner records the applied keys in state.json `requeueApplied`. */
|
|
115
116
|
/** #5832: the `{dependency, branch, sha}` a stacked build of `issue` was admitted on (batch state `stacked`), or null. Rows carry `stacked`/`stackedOn`. */
|
|
117
|
+
/**
|
|
118
|
+
* #6008: sandboxes kept for adopt (issue, since, age, phase). `state.kept` records them as the lane returned them; a running
|
|
119
|
+
* remote record (handle) of a batch whose dispatcher is gone (`live` false) is a kept sandbox too. Newest listing order: by issue.
|
|
120
|
+
*/
|
|
121
|
+
export function keptSandboxes(state, { now = Date.now(), live = false } = {}) {
|
|
122
|
+
const out = new Map();
|
|
123
|
+
for (const [k, v] of Object.entries(state?.kept ?? {})) {
|
|
124
|
+
const issue = Number(k); if (!Number.isSafeInteger(issue) || !v) continue;
|
|
125
|
+
out.set(issue, { issue, since: v.since ?? null, phase: v.phase ?? null, ...(v.id ? { id: v.id } : {}) });
|
|
126
|
+
}
|
|
127
|
+
if (!live) for (const [k, rec] of Object.entries(state?.running ?? {})) {
|
|
128
|
+
const issue = Number(k);
|
|
129
|
+
if (!Number.isSafeInteger(issue) || out.has(issue) || !(rec?.handle || rec?.remote)) continue;
|
|
130
|
+
out.set(issue, { issue, since: rec.startedAt ?? null, phase: rec.phase ?? null, ...(rec.handle?.id ? { id: rec.handle.id } : {}) });
|
|
131
|
+
}
|
|
132
|
+
return [...out.values()].sort((a, b) => a.issue - b.issue).map((e) => ({ ...e, ageMs: (() => { const t = typeof e.since === "number" ? e.since : Date.parse(e.since); return Number.isFinite(t) ? Math.max(0, now - t) : null; })() }));
|
|
133
|
+
}
|
|
116
134
|
export const stackedOnOf = (state, issue) => state?.stacked?.[issue] ?? null;
|
|
117
135
|
|
|
118
136
|
export const requeueKey = (e) => `${e.issue}@${e.at}`;
|
|
@@ -185,6 +203,31 @@ export const dispatchOwner = (root, repo, issue, exceptId, opts = {}) => {
|
|
|
185
203
|
return (live.find((o) => o.running) ?? live.find((o) => o.id < exceptId))?.id ?? null;
|
|
186
204
|
};
|
|
187
205
|
|
|
206
|
+
/**
|
|
207
|
+
* #5978: coverage of a selector batch: every open issue the selector matches is exactly one of running, queued, backing-off (a
|
|
208
|
+
* deferral or re-admission wait), waiting on deps, human-blocked (the only reason to stay unscheduled), or `unscheduled`
|
|
209
|
+
* (the unhealthy state: matches but nothing will run it). Shared by `forgedock orchestrate --status`.
|
|
210
|
+
* @param {{state:object, open:Array<{number:number,labels?:string[]}>, now?:number}} p
|
|
211
|
+
*/
|
|
212
|
+
export function coverage({ state, open, now = Date.now() }) {
|
|
213
|
+
const st = state ?? {}, pending = new Set(st.pending ?? []), res = st.results ?? {}, readmit = st.readmit ?? {};
|
|
214
|
+
const out = { running: [], queued: [], backingOff: [], waitingDeps: [], humanBlocked: [], unscheduled: [] };
|
|
215
|
+
for (const { number: n, labels = [] } of open ?? []) {
|
|
216
|
+
const row = res[n], deps = (st.deps?.[n] ?? []).filter((d) => res[d]?.outcome !== "merged" && res[d]?.outcome !== "invalid");
|
|
217
|
+
if (st.running && Object.hasOwn(st.running, String(n))) out.running.push(n);
|
|
218
|
+
else if (row && humanCode(row, labels)) out.humanBlocked.push(n);
|
|
219
|
+
else if (!row && labels.some((l) => humanCode(null, [l]))) out.humanBlocked.push(n);
|
|
220
|
+
else if (pending.has(n) && (st.notBefore?.[n] ?? 0) > now) out.backingOff.push(n);
|
|
221
|
+
else if (pending.has(n) && deps.length) out.waitingDeps.push(n);
|
|
222
|
+
else if (pending.has(n)) out.queued.push(n);
|
|
223
|
+
else if (row && ["deferred", "held", "engine-error"].includes(row.outcome) && readmit[n]) out.backingOff.push(n);
|
|
224
|
+
else if (row && (row.outcome === "pr-ready" || row.outcome === "ci-pending")) out.queued.push(n); // a PR is on its way to merge
|
|
225
|
+
else if (row && /^(skipped|held)$/.test(row.outcome) && deps.length) out.waitingDeps.push(n);
|
|
226
|
+
else out.unscheduled.push(n);
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|
|
230
|
+
|
|
188
231
|
/** Handle on one batch directory. */
|
|
189
232
|
export function openBatch(root, id) {
|
|
190
233
|
if (!ID_RE.test(String(id ?? ""))) throw new Error(`invalid batch id ${JSON.stringify(id)}`);
|
|
@@ -300,6 +343,8 @@ export function openBatch(root, id) {
|
|
|
300
343
|
readRequeued: () => readRequeueFile(f("requeue")),
|
|
301
344
|
/** Entries the runner has not applied yet (a finished or unhosted batch with a pending requeue). */
|
|
302
345
|
unrunRequeues: () => { const done = new Set(readJson(f("state.json"))?.requeueApplied ?? []); return readRequeueFile(f("requeue")).filter((e) => !done.has(requeueKey(e))); },
|
|
346
|
+
/** #6008: the kept-sandbox listing of this batch (issue, since, ageMs, phase); `live` = its dispatcher is running. */
|
|
347
|
+
keptSandboxes: (live = false) => keptSandboxes(readJson(f("state.json")), { live }),
|
|
303
348
|
/** Issues held by `--hold` (#4592): the `hold` file, sorted unique positive integers; [] when missing or invalid. */
|
|
304
349
|
readHeld: () => readAdded(f("hold")),
|
|
305
350
|
/** #4656: gates waiting on issues (`gates` file: [{ name, waitsOn: [n...], since? }], written by the ship/settle pre-flight); [] when missing or invalid. */
|
|
@@ -331,6 +376,23 @@ export function openBatch(root, id) {
|
|
|
331
376
|
self.releaseIssues(due.map((e) => e.issue));
|
|
332
377
|
return out;
|
|
333
378
|
},
|
|
379
|
+
/** #5975: batch-level pause (`pause` file): `{owner, since, expiresAt|null, reason, ownerPid, ownerHost}`; admission stops for every issue, present and future. */
|
|
380
|
+
setPause: ({ owner = "operator", reason = null, forMs = null, ownerPid = null, ownerHost = null } = {}) => {
|
|
381
|
+
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 };
|
|
382
|
+
put(f("pause"), JSON.stringify(rec) + "\n");
|
|
383
|
+
return rec;
|
|
384
|
+
},
|
|
385
|
+
/** #5975: the pause record, or null when missing or invalid. */
|
|
386
|
+
readPause: () => { const v = readJson(f("pause")); return v && typeof v === "object" && !Array.isArray(v) && typeof v.since === "string" ? v : null; },
|
|
387
|
+
/** #5975: lift the pause. @returns {boolean} whether one was set */
|
|
388
|
+
clearPause: () => { const had = !!self.readPause(); try { rmSync(f("pause"), { force: true }); } catch { /* already gone */ } return had; },
|
|
389
|
+
/** #5975: lift the pause when its `expiresAt` has passed. @returns {object|null} the expired record (with `ownerGone`) */
|
|
390
|
+
expirePause: (now = Date.now()) => {
|
|
391
|
+
const p = self.readPause();
|
|
392
|
+
if (!p?.expiresAt || !(Date.parse(p.expiresAt) <= now)) return null;
|
|
393
|
+
self.clearPause();
|
|
394
|
+
return { ...p, ownerGone: ownerGone(p) };
|
|
395
|
+
},
|
|
334
396
|
/** Remove `list` from the `hold` file. @returns {number[]} the issues that were held */
|
|
335
397
|
releaseIssues: (list) => {
|
|
336
398
|
const have = new Set(readAdded(f("hold")));
|
package/bin/lean/batch.test.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { join } from "node:path";
|
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
9
|
import { resolveLane, makeLaneCache } from "./lane.mjs";
|
|
10
10
|
import { orchestrate, deferPolicy, DEFER_BACKOFF_S, formatOutcomeLists, CAPACITY_FALLBACK_AFTER, isTransientEngineError, transientRetryDelayMs, DEFAULT_TRANSIENT_RETRIES } from "./orchestrate.mjs";
|
|
11
|
-
import { openBatch, fsTypeOf, assertDiskPath, isLaneAlive, writeAtomic, launchLane, detachedLanes, stackedOnOf } from "./batch.mjs";
|
|
11
|
+
import { openBatch, fsTypeOf, assertDiskPath, isLaneAlive, writeAtomic, launchLane, detachedLanes, stackedOnOf, keptSandboxes } from "./batch.mjs";
|
|
12
12
|
import { makeLedger } from "./ledger.mjs";
|
|
13
13
|
import { placeLane } from "./execution.mjs";
|
|
14
14
|
import { liveRemote } from "./live-execution.mjs";
|
|
@@ -273,9 +273,9 @@ await orchestrateFromCli(["1", "2", "3", "--parallel", "2", "--repo", "o/r", "--
|
|
|
273
273
|
assert.equal(isLaneAlive(42, "lane", { kill: () => true, procDir: proc }), false);
|
|
274
274
|
assert.deepEqual(stackedOnOf({ stacked: { 7: { dependency: 6, branch: "b", sha: "abcdef1" } } }, 7), { dependency: 6, branch: "b", sha: "abcdef1" }, "#5832: stackedOn read from batch state");
|
|
275
275
|
assert.equal(stackedOnOf({}, 7), null);
|
|
276
|
-
assert.deepEqual(readOrchestration(root), { breaker: { errors: 3, window_min: 30 }, maxDeferrals: 3, transientRetries: 4, blockedLabel: "blocked", globalParallel: null, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
|
|
276
|
+
assert.deepEqual(readOrchestration(root), { breaker: { errors: 3, window_min: 30 }, maxDeferrals: 3, transientRetries: 4, blockedLabel: "blocked", globalParallel: null, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4, maxAttemptsPerIssue: 4, maxIdenticalSignature: 2 });
|
|
277
277
|
writeFileSync(join(root, "forge.yaml"), "orchestration:\n breaker:\n errors: 5\n window_min: 10\n max_deferrals: 2\n global_parallel: 4\n transient_retries: 2\n");
|
|
278
|
-
assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4 });
|
|
278
|
+
assert.deepEqual(readOrchestration(root), { breaker: { errors: 5, window_min: 10 }, maxDeferrals: 2, transientRetries: 2, blockedLabel: "blocked", globalParallel: 4, stacking: "off", recovery: { maxAttempts: 1, mechanicalMaxAttempts: 2 }, baseSync: { enabled: true, unionGlobs: [] }, mergeTrain: "off", mergeTrainBatch: 4, maxAttemptsPerIssue: 4, maxIdenticalSignature: 2 });
|
|
279
279
|
});
|
|
280
280
|
|
|
281
281
|
it("run-issue --result-file writes the lane result, also when the run throws", async () => {
|
|
@@ -2080,3 +2080,119 @@ 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
|
+
});
|
|
2148
|
+
|
|
2149
|
+
describe("#5992: base.red is a batch hold, not a per-issue capped deferral", () => {
|
|
2150
|
+
it("base.red is uncapped; other codes still cap", () => {
|
|
2151
|
+
assert.deepEqual(deferPolicy({ code: "base.red", retryInSeconds: 900 }, { now: 0, deferrals: 99, maxDeferrals: 3 }), { delayMs: 900000, host: true });
|
|
2152
|
+
assert.deepEqual(deferPolicy({ code: "merge.transient", retryInSeconds: 60 }, { now: 0, deferrals: 3, maxDeferrals: 3 }), { capped: true });
|
|
2153
|
+
});
|
|
2154
|
+
|
|
2155
|
+
it("10 lanes + red base: 1 probe run, only the fixer launches, no 'gave up'; a sha move resumes admission in one pass", async () => {
|
|
2156
|
+
const { c, now, sleep } = fakeClock();
|
|
2157
|
+
const issues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
|
2158
|
+
const launches = [], updates = [];
|
|
2159
|
+
let sha = "a".repeat(40), probes = 0;
|
|
2160
|
+
const baseProbe = async () => { probes++; return sha === "a".repeat(40) ? { red: true, sha, commands: ["guard"], att: { sha: "f".repeat(40), issue: 10 } } : { red: false, sha }; };
|
|
2161
|
+
let passes = 0;
|
|
2162
|
+
const rows = await orchestrate({ issues, parallel: 10, maxDeferrals: 3, now, readBody: async () => "", baseProbe, pollMs: 10,
|
|
2163
|
+
onUpdate: (u) => updates.push(u),
|
|
2164
|
+
sleep: async (ms) => { await sleep(ms); if (++passes === 3) sha = "b".repeat(40); },
|
|
2165
|
+
runOne: async (n) => { launches.push([n, sha === "a".repeat(40) ? "red" : "green"]); return { terminalReason: "merged", pr: 100 + n }; } });
|
|
2166
|
+
const redLaunches = launches.filter((l) => l[1] === "red").map((l) => l[0]);
|
|
2167
|
+
assert.deepEqual(redLaunches, [10], "only the attributed fixer is admitted while the base is red");
|
|
2168
|
+
assert.equal(launches.length, 10, "every lane runs once after the base moves");
|
|
2169
|
+
assert.ok(rows.every((r) => r.outcome === "merged"));
|
|
2170
|
+
assert.ok(!rows.some((r) => /gave up/.test(r.detail ?? "")));
|
|
2171
|
+
assert.equal(updates.filter((u) => u.code === "base.red").length, 1, "one batch-level hold row");
|
|
2172
|
+
assert.ok(updates.some((u) => /base\.red cleared/.test(u.detail ?? "")));
|
|
2173
|
+
assert.ok(c.t >= 1_000_000);
|
|
2174
|
+
});
|
|
2175
|
+
});
|
|
2176
|
+
|
|
2177
|
+
// #5978: the selector is kept in the batch plan argv/state; coverage classifies every matching open issue.
|
|
2178
|
+
import { coverage as coverage5978 } from "./batch.mjs";
|
|
2179
|
+
describe("coverage (#5978)", () => {
|
|
2180
|
+
it("every open match lands in exactly one class; human-blocked is the only unscheduled-allowed class", () => {
|
|
2181
|
+
const state = { pending: [2], running: { 1: {} }, results: { 3: { outcome: "needs-human", detail: "needs a product decision" } } };
|
|
2182
|
+
const c = coverage5978({ state, open: [1, 2, 3].map((number) => ({ number })) });
|
|
2183
|
+
assert.deepEqual([c.running, c.queued, c.humanBlocked, c.unscheduled], [[1], [2], [3], []]);
|
|
2184
|
+
});
|
|
2185
|
+
it("a human label blocks an issue with no row; an unknown one is unscheduled", () => {
|
|
2186
|
+
const c = coverage5978({ state: { pending: [] }, open: [{ number: 4, labels: ["human:credentials"] }, { number: 5, labels: ["bug"] }] });
|
|
2187
|
+
assert.deepEqual([c.humanBlocked, c.unscheduled], [[4], [5]]);
|
|
2188
|
+
});
|
|
2189
|
+
});
|
|
2190
|
+
|
|
2191
|
+
describe("#6008 kept-sandbox listing", () => {
|
|
2192
|
+
it("lists issue, age and phase from state.kept and, with no live dispatcher, from remote run records", () => {
|
|
2193
|
+
const state = { kept: { 5: { issue: 5, since: 1_000, phase: "review", id: "sbx-5" } }, running: { 6: { startedAt: 4_000, remote: true, handle: { id: "sbx-6" } }, 7: { startedAt: 4_000, pid: 99 } } };
|
|
2194
|
+
const rows = keptSandboxes(state, { now: 61_000 });
|
|
2195
|
+
assert.deepEqual(rows.map((r) => [r.issue, r.ageMs, r.phase]), [[5, 60_000, "review"], [6, 57_000, null]]);
|
|
2196
|
+
assert.deepEqual(keptSandboxes(state, { now: 61_000, live: true }).map((r) => r.issue), [5], "a live dispatcher's running lanes are not kept");
|
|
2197
|
+
});
|
|
2198
|
+
});
|
package/bin/lean/capwait.mjs
CHANGED
|
@@ -4,22 +4,33 @@
|
|
|
4
4
|
* Capacity wait (#4909): a lane whose sandbox launch was refused for capacity (`sandbox.capacity`) is admitted again only
|
|
5
5
|
* once the pool reports a free slot (`capacity() -> {free}`), not on a blind timer retry; the wait is recorded as queue
|
|
6
6
|
* time (`waits.queue`, ms). A pool that does not report `free` is unknown: the provider's retry-in applies as before.
|
|
7
|
+
* #5985: a refusal that names its reason (`pool.host_load`, `pool.host_mem`) waits on that condition clearing (load below
|
|
8
|
+
* 1.0, free memory above the floor) instead; with no figures for it the slot count above is the fallback.
|
|
7
9
|
*/
|
|
10
|
+
import { conditionCleared } from "./concurrency.mjs";
|
|
11
|
+
|
|
8
12
|
export function makeCapWait({ now = Date.now } = {}) {
|
|
9
13
|
const since = new Map(); // issue -> when its launch was refused for capacity
|
|
14
|
+
const reasons = new Map(); // issue -> the pool reason of its refusal (#5985)
|
|
10
15
|
const waited = new Map(); // issue -> queue ms accumulated, not yet recorded on a row
|
|
11
16
|
const isFree = (cap) => Boolean(cap) && Number.isInteger(cap.free) && cap.free > 0;
|
|
12
17
|
const isFull = (cap) => Boolean(cap) && Number.isInteger(cap.free) && cap.free <= 0;
|
|
13
18
|
return {
|
|
14
19
|
/** A launch of `issue` was refused for capacity. */
|
|
15
|
-
refused(issue) { if (!since.has(issue)) since.set(issue, now()); },
|
|
20
|
+
refused(issue, reason = null) { if (!since.has(issue)) since.set(issue, now()); if (reason) reasons.set(issue, reason); else reasons.delete(issue); },
|
|
16
21
|
/** True while a refused `issue` must keep waiting: the sampled pool reports no free slot. */
|
|
17
|
-
blocked(issue, cap) {
|
|
22
|
+
blocked(issue, cap) {
|
|
23
|
+
if (!since.has(issue)) return false;
|
|
24
|
+
const c = conditionCleared(reasons.get(issue), cap);
|
|
25
|
+
return c === null ? isFull(cap) : !c;
|
|
26
|
+
},
|
|
27
|
+
/** True when `cap` has the figures the refusal's named condition needs (the timer is not the wake). */
|
|
28
|
+
conditional(issue, cap) { return since.has(issue) && conditionCleared(reasons.get(issue), cap) !== null; },
|
|
18
29
|
/** `issue` was admitted: bank its wait as queue time. Returns the ms waited (0 when it was not refused). */
|
|
19
30
|
admitted(issue) {
|
|
20
31
|
if (!since.has(issue)) return 0;
|
|
21
32
|
const ms = Math.max(0, now() - since.get(issue));
|
|
22
|
-
since.delete(issue);
|
|
33
|
+
since.delete(issue); reasons.delete(issue);
|
|
23
34
|
waited.set(issue, (waited.get(issue) ?? 0) + ms);
|
|
24
35
|
return ms;
|
|
25
36
|
},
|
|
@@ -46,3 +46,23 @@ describe("at pool capacity a lane waits for a free slot (#4909)", () => {
|
|
|
46
46
|
assert.ok(Number.isFinite(rows[0].waits?.queue) && rows[0].waits.queue >= 0, "wait recorded as queue time");
|
|
47
47
|
});
|
|
48
48
|
});
|
|
49
|
+
|
|
50
|
+
describe("capwait wakes on the named condition (#5985)", () => {
|
|
51
|
+
it("a host_load refusal holds until load < 1.0 whatever the slots say; host_mem until free mem > floor; no figures: slot fallback", () => {
|
|
52
|
+
let t = 0;
|
|
53
|
+
const w = makeCapWait({ now: () => t });
|
|
54
|
+
w.refused(1, "host_load");
|
|
55
|
+
assert.equal(w.blocked(1, { free: 5, load_per_core: 1.2 }), true, "free slots do not wake a load refusal");
|
|
56
|
+
t += 1000;
|
|
57
|
+
assert.equal(w.blocked(1, { free: 0, load_per_core: 0.8 }), false, "wakes the moment load clears, not on a timer");
|
|
58
|
+
w.refused(2, "pool.host_mem");
|
|
59
|
+
assert.equal(w.blocked(2, { mem_available_gb: 2 }), true);
|
|
60
|
+
assert.equal(w.blocked(2, { mem_available_gb: 9 }), false);
|
|
61
|
+
w.refused(3, "host_load");
|
|
62
|
+
assert.equal(w.blocked(3, { free: 0 }), true, "no load figure: the slot count is the fallback");
|
|
63
|
+
assert.equal(w.conditional(3, { free: 0 }), false);
|
|
64
|
+
assert.equal(w.conditional(1, { load_per_core: 0.5 }), true);
|
|
65
|
+
w.refused(4);
|
|
66
|
+
assert.equal(w.blocked(4, { free: 1, load_per_core: 3 }), false, "no reason: slot gate only");
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -13,3 +13,17 @@ export function decideClear({ tripped, requestAt }) {
|
|
|
13
13
|
if (tripped && Number.isFinite(tripped.at) && tripped.at > requestAt) return { clear: false, stale: true };
|
|
14
14
|
return { clear: true, stale: false };
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* #5978: the runner's own reset of a tripped breaker. It closes after `cooldownMs` when the failures were environmental
|
|
19
|
+
* (VM restart, mirror, network: `environmental`) and the pool is healthy again (#5947 classes); anything else needs `--clear-breaker`.
|
|
20
|
+
* @param {{tripped: ({at?: number}|null|undefined), now: number, cooldownMs: number, environmental: boolean, poolHealthy: boolean}} p
|
|
21
|
+
* @returns {{reset: boolean, why: string}}
|
|
22
|
+
*/
|
|
23
|
+
export function decideAutoReset({ tripped, now, cooldownMs, environmental, poolHealthy }) {
|
|
24
|
+
if (!tripped || !Number.isFinite(tripped.at)) return { reset: false, why: "not tripped" };
|
|
25
|
+
if (!environmental) return { reset: false, why: "failure signature is not environmental" };
|
|
26
|
+
if (now - tripped.at < cooldownMs) return { reset: false, why: "cooldown not elapsed" };
|
|
27
|
+
if (!poolHealthy) return { reset: false, why: "pool not healthy" };
|
|
28
|
+
return { reset: true, why: "environmental signature, cooldown elapsed, pool healthy" };
|
|
29
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* #5979: post a machine comment only on a state change. A scheduler pass that re-derives the same DEPENDENCY, FACTS, or
|
|
5
|
+
* NEEDS_HUMAN text posts nothing; a changed FACTS or DEPENDENCY is edited in place; a changed NEEDS_HUMAN is a new comment
|
|
6
|
+
* (statuscomment.mjs header: a new comment notifies a person, an edit does not, and issuewatch keys on the newest one). Pure.
|
|
7
|
+
*/
|
|
8
|
+
import { IN_PLACE_MARKERS } from "./statuscomment.mjs";
|
|
9
|
+
|
|
10
|
+
/** Markers whose changed state is PATCHed rather than posted again. */
|
|
11
|
+
export const PATCH_MARKERS = Object.freeze(IN_PLACE_MARKERS.filter((m) => m !== "FORGE:NEEDS_HUMAN"));
|
|
12
|
+
|
|
13
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
14
|
+
|
|
15
|
+
/** The body without what changes between identical states: the cost/usage line, comment urls and ids, shas, whitespace. */
|
|
16
|
+
export function normalizeState(body) {
|
|
17
|
+
return String(body ?? "")
|
|
18
|
+
.split("\n")
|
|
19
|
+
.filter((l) => !/^\s*_?\s*cost \$[\d.]+/i.test(l))
|
|
20
|
+
.join("\n")
|
|
21
|
+
.replace(/https?:\/\/\S*#issuecomment-\d+/g, "")
|
|
22
|
+
.replace(/\b[0-9a-f]{7,40}\b/g, "")
|
|
23
|
+
.replace(/\s+/g, " ")
|
|
24
|
+
.trim();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The newest trusted comment carrying `marker` (a `<!-- marker` line anywhere in the body), or null. */
|
|
28
|
+
export function findLast(comments, marker, trusted = () => true) {
|
|
29
|
+
const re = new RegExp(`<!--\\s*${esc(marker)}(?![A-Za-z0-9_])`);
|
|
30
|
+
const list = Array.isArray(comments) ? comments : [];
|
|
31
|
+
for (let i = list.length - 1; i >= 0; i--) if (re.test(String(list[i]?.body ?? "")) && trusted(list[i])) return list[i];
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `{action: "skip"|"patch"|"create", prior}` for posting `body` under `marker` given the issue's comments. */
|
|
36
|
+
export function decidePost({ marker, body, comments, trusted }) {
|
|
37
|
+
const prior = findLast(comments, marker, trusted);
|
|
38
|
+
if (!prior) return { action: "create", prior: null };
|
|
39
|
+
if (normalizeState(prior.body) === normalizeState(body)) return { action: "skip", prior };
|
|
40
|
+
return { action: PATCH_MARKERS.includes(marker) ? "patch" : "create", prior };
|
|
41
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { normalizeState, findLast, decidePost } from "./commentstate.mjs";
|
|
6
|
+
import { IN_PLACE_MARKERS } from "./statuscomment.mjs";
|
|
7
|
+
|
|
8
|
+
const body = (m, text, cost = "0.10") => `<!-- ${m} -->\n${text}\n\n_cost $${cost}, tokens 1 in / 2 out_`;
|
|
9
|
+
const url = "https://github.com/o/r/issues/1#issuecomment-5";
|
|
10
|
+
|
|
11
|
+
describe("post only on a state change (#5979)", () => {
|
|
12
|
+
for (const m of IN_PLACE_MARKERS) {
|
|
13
|
+
it(`a second identical ${m} post is skipped, even when only the usage line differs`, () => {
|
|
14
|
+
const comments = [{ body: body(m, "same state"), url }];
|
|
15
|
+
assert.equal(decidePost({ marker: m, body: body(m, "same state", "9.99"), comments }).action, "skip");
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
it("a changed DEPENDENCY or FACTS is patched in place; a changed NEEDS_HUMAN is a new comment", () => {
|
|
19
|
+
const comments = (m) => [{ body: body(m, "old"), url }];
|
|
20
|
+
assert.equal(decidePost({ marker: "FORGE:DEPENDENCY", body: body("FORGE:DEPENDENCY", "new"), comments: comments("FORGE:DEPENDENCY") }).action, "patch");
|
|
21
|
+
assert.equal(decidePost({ marker: "FORGE:FACTS", body: body("FORGE:FACTS", "new"), comments: comments("FORGE:FACTS") }).action, "patch");
|
|
22
|
+
assert.equal(decidePost({ marker: "FORGE:NEEDS_HUMAN", body: body("FORGE:NEEDS_HUMAN", "new"), comments: comments("FORGE:NEEDS_HUMAN") }).action, "create");
|
|
23
|
+
});
|
|
24
|
+
it("no earlier comment creates; an untrusted one is ignored", () => {
|
|
25
|
+
assert.equal(decidePost({ marker: "FORGE:DEPENDENCY", body: "x", comments: [] }).action, "create");
|
|
26
|
+
assert.equal(decidePost({ marker: "FORGE:DEPENDENCY", body: "x", comments: [{ body: body("FORGE:DEPENDENCY", "x") }], trusted: () => false }).action, "create");
|
|
27
|
+
});
|
|
28
|
+
it("findLast returns the newest; normalizeState drops usage, ids and shas", () => {
|
|
29
|
+
assert.equal(findLast([{ body: "<!-- FORGE:FACTS -->\na" }, { body: "<!-- FORGE:FACTS -->\nb" }], "FORGE:FACTS").body.endsWith("b"), true);
|
|
30
|
+
assert.equal(normalizeState(body("M", "a b 1e0c3e45")), normalizeState(body("M", "a b", "5")));
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Closed-loop lane concurrency (#5985). K (`getParallel`/`--parallel`) is the ceiling; the operating point moves under it:
|
|
5
|
+
* additive increase while the pool reports headroom and has refused nothing lately, multiplicative decrease (halve) on a
|
|
6
|
+
* `pool.*` refusal or load above 1.5/core. A lane the pool refused is held for REFUSAL_HOLD_MS unless the named condition
|
|
7
|
+
* (load below 1.0, free memory above the floor) clears first. Pure: no I/O, the caller feeds samples and persists events.
|
|
8
|
+
*/
|
|
9
|
+
export const REFUSAL_HOLD_MS = 5 * 60_000;
|
|
10
|
+
export const HEAVY_CPU_AVG = 1.5;
|
|
11
|
+
export const LOAD_HALVE = 1.5;
|
|
12
|
+
export const LOAD_GREEN = 1.0;
|
|
13
|
+
export const MEM_FLOOR_GB = 4;
|
|
14
|
+
export const MEM_HEADROOM_GB = 2;
|
|
15
|
+
|
|
16
|
+
const fin = (v) => typeof v === "number" && Number.isFinite(v);
|
|
17
|
+
/** `host_load` from a refusal reason/code (`pool.host_load` or `host_load`); "" when it is not a pool reason. */
|
|
18
|
+
export const poolReason = (v) => { const m = /^(?:pool\.)?(host_load|host_mem|projected_peak|disk(?:_low|_cap)?)$/.exec(String(v ?? "")); return m ? m[1].replace(/^disk_.*/, "disk") : ""; };
|
|
19
|
+
|
|
20
|
+
/** The named condition a refusal waits on: true = cleared, false = still holding, null = unknown (no figures, or no named condition). */
|
|
21
|
+
export function conditionCleared(reason, cap, { memFloorGb = MEM_FLOOR_GB } = {}) {
|
|
22
|
+
const r = poolReason(reason);
|
|
23
|
+
if (r === "host_load") return fin(cap?.load_per_core) ? cap.load_per_core < LOAD_GREEN : null;
|
|
24
|
+
if (r === "host_mem") return fin(cap?.mem_available_gb) ? cap.mem_available_gb > memFloorGb : null;
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A repo is heavy when its recent finished lanes average more than 1.5 cpus (`usage-history.jsonl` rows `{repo, cpu_avg}`). */
|
|
29
|
+
export function classifyRepo(rows, repo, { window = 20 } = {}) {
|
|
30
|
+
const v = (rows ?? []).filter((x) => x && x.repo === repo && fin(x.cpu_avg)).slice(-window).map((x) => x.cpu_avg);
|
|
31
|
+
return v.length > 0 && v.reduce((a, b) => a + b, 0) / v.length > HEAVY_CPU_AVG ? "heavy" : "light";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function makeController({ ceiling, heavyCap = null, now = Date.now, memFloorGb = MEM_FLOOR_GB, holdMs = REFUSAL_HOLD_MS, start = null } = {}) {
|
|
35
|
+
let top = Math.max(1, Number.isInteger(ceiling) ? ceiling : 1);
|
|
36
|
+
let k = Math.min(top, Math.max(1, Number.isInteger(start) ? start : top)); // no signal yet: run at the ceiling, as before
|
|
37
|
+
let factor = "ceiling";
|
|
38
|
+
let lastRefusal = -Infinity;
|
|
39
|
+
const held = new Map(); // issue -> { at, reason }
|
|
40
|
+
const hcap = () => Math.max(1, Math.min(top, Number.isInteger(heavyCap) ? heavyCap : Math.ceil(top / 3)));
|
|
41
|
+
const ev = (change, inputs) => ({ event: "concurrency", change, k, ceiling: top, factor, inputs });
|
|
42
|
+
return {
|
|
43
|
+
setCeiling(c) { if (Number.isInteger(c) && c >= 1) { const was = top; top = c; k = k >= was ? top : Math.min(k, top); } },
|
|
44
|
+
/** The operating point under the ceiling; a heavy lane class has its own, lower cap. */
|
|
45
|
+
operating(klass = "light") { return Math.min(top, k, klass === "heavy" ? hcap() : Infinity); },
|
|
46
|
+
ceiling: () => top,
|
|
47
|
+
/** Concurrent heavy lanes allowed, separate from light lanes. */
|
|
48
|
+
heavyLimit: () => hcap(),
|
|
49
|
+
limiting(klass = "light") { return klass === "heavy" && hcap() < Math.min(top, k) ? "heavy cap" : k < top ? factor : "ceiling"; },
|
|
50
|
+
/** A launch was refused. Halves on a `pool.*` reason or load above 1.5/core. Returns the event, or null when nothing moved. */
|
|
51
|
+
refused({ issue = null, code = "", reason = "", live = null } = {}) {
|
|
52
|
+
const r = poolReason(reason) || poolReason(code);
|
|
53
|
+
const hot = fin(live?.load_per_core) && live.load_per_core > LOAD_HALVE;
|
|
54
|
+
if (issue !== null && r) held.set(issue, { at: now(), reason: r });
|
|
55
|
+
if (!r && !hot) return null;
|
|
56
|
+
const t = now();
|
|
57
|
+
if (t - lastRefusal < 1000) return null; // one storm of simultaneous refusals is one halving
|
|
58
|
+
lastRefusal = t;
|
|
59
|
+
const before = k;
|
|
60
|
+
k = Math.max(1, Math.floor(k / 2));
|
|
61
|
+
factor = r || "host_load";
|
|
62
|
+
return k === before ? null : ev("decrease", { from: before, reason: r || "load", live });
|
|
63
|
+
},
|
|
64
|
+
/** One pool sample: +1 while memory is above floor+headroom, load below 1 and nothing was refused for `holdMs`. */
|
|
65
|
+
observe(cap) {
|
|
66
|
+
if (!cap || !fin(cap.load_per_core) || !fin(cap.mem_available_gb)) return null; // unknown pool: K applies unchanged
|
|
67
|
+
if (k >= top) { factor = "ceiling"; return null; }
|
|
68
|
+
if (cap.mem_available_gb > memFloorGb + MEM_HEADROOM_GB && cap.load_per_core < LOAD_GREEN && now() - lastRefusal >= holdMs) {
|
|
69
|
+
const before = k; k += 1;
|
|
70
|
+
if (k >= top) factor = "ceiling";
|
|
71
|
+
return ev("increase", { from: before, load_per_core: cap.load_per_core, mem_available_gb: cap.mem_available_gb });
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
},
|
|
75
|
+
/** True while `issue` must not be launched: refused within holdMs and its named condition has not cleared. */
|
|
76
|
+
holding(issue, cap) {
|
|
77
|
+
const h = held.get(issue);
|
|
78
|
+
if (!h) return false;
|
|
79
|
+
if (conditionCleared(h.reason, cap, { memFloorGb }) === true || now() - h.at >= holdMs) { held.delete(issue); return false; }
|
|
80
|
+
return true;
|
|
81
|
+
},
|
|
82
|
+
release(issue) { held.delete(issue); },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `running/K/ceiling (limiting factor)`, with the configured ceiling as the achieved-vs-configured reference. */
|
|
87
|
+
export function formatConcurrency({ running, k, ceiling, factor = "ceiling" } = {}) {
|
|
88
|
+
return `concurrency: ${running ?? 0}/${k ?? ceiling}/${ceiling} (${factor})`;
|
|
89
|
+
}
|