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
|
@@ -275,6 +275,23 @@ describe("#5859 agent restart: correlated sandbox loss is sandbox.lost, not engi
|
|
|
275
275
|
assert.ok(probes >= 3, "admission waited for the agent's healthy probe");
|
|
276
276
|
});
|
|
277
277
|
|
|
278
|
+
// #5967 R5/R8: a host-memory OOM restart of the agent VM ends N sandboxes together; the VM-restart class is sandbox.lost (not a second pool.vm_restart code).
|
|
279
|
+
it("N sandboxes ending together on an agent VM restart are sandbox.lost deferrals, no breaker trip (#5967)", async () => {
|
|
280
|
+
const issues = [1, 2, 3, 4, 5];
|
|
281
|
+
const script = Object.fromEntries(issues.map((n) => [n, [LOST(n), MERGED]]));
|
|
282
|
+
const store = memStore();
|
|
283
|
+
let probes = 0;
|
|
284
|
+
const r = await harness({ script, issues, parallel: 5, store, envHold: undefined,
|
|
285
|
+
extra: { envHold: null, breaker: BREAKER, remote: { agentHealthy: async () => ++probes > 1 } } });
|
|
286
|
+
assert.ok(!r.updates.some((u) => u.outcome === "breaker"));
|
|
287
|
+
assert.deepEqual([...new Set(r.updates.filter((u) => u.code === "sandbox.lost").map((u) => u.issue))].sort((x, y) => x - y), issues);
|
|
288
|
+
assert.ok(!r.updates.some((u) => u.code === "engine-error"));
|
|
289
|
+
const st = store.load();
|
|
290
|
+
assert.deepEqual(st.errorTimes, []);
|
|
291
|
+
assert.equal(st.breaker, null);
|
|
292
|
+
for (const n of issues) assert.equal(r.byIssue[n].outcome, "merged");
|
|
293
|
+
});
|
|
294
|
+
|
|
278
295
|
it("agent restart: failure after healthy is an ordinary engine-error", async () => {
|
|
279
296
|
const store = memStore();
|
|
280
297
|
const r = await harness({ script: { 1: [LOST(1), LOST(1), MERGED], 2: [LOST(2), MERGED], 3: [LOST(3), MERGED] }, issues: [1, 2, 3], parallel: 3, store,
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5975: a batch-level pause stops admission for every issue (dependency merge, engine/env re-admit, expiry), never a running lane.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { orchestrate } from "./orchestrate.mjs";
|
|
7
|
+
|
|
8
|
+
const memStore = () => { let st = null; return { load: () => (st ? JSON.parse(JSON.stringify(st)) : null), save: (s) => { st = JSON.parse(JSON.stringify(s)); }, log: () => {} }; };
|
|
9
|
+
const EE = (detail) => ({ terminalReason: "engine-error", detail });
|
|
10
|
+
const MERGED = { terminalReason: "merged", pr: 9 };
|
|
11
|
+
const REC = { owner: "op@h", since: "2026-01-01T00:00:00.000Z", expiresAt: null, reason: "release cut", ownerPid: null, ownerHost: null };
|
|
12
|
+
|
|
13
|
+
// A fake clock: every sleep advances it, so polls and expiry run instantly.
|
|
14
|
+
const run = ({ script, issues, store = memStore(), pause = { v: null }, extra = {}, onStart = () => {}, onRow = () => {}, clock = { t: 1_000_000 } }) => {
|
|
15
|
+
const calls = [], updates = [], decisions = [];
|
|
16
|
+
const p = orchestrate({ issues, parallel: 1, pollMs: 1000, readBody: async (n) => (n === 2 ? "Blocked by #1" : ""), trusted: () => true, now: () => clock.t, store,
|
|
17
|
+
sleep: async (ms) => { clock.t += Math.max(1, Number(ms) || 0); },
|
|
18
|
+
getPause: () => pause.v, recovery: { maxAttempts: 1, mechanicalMaxAttempts: 3 },
|
|
19
|
+
runOne: async (n) => { calls.push(n); clock.t += 1000; onStart(n); const l = script[n] ?? [MERGED]; return l[Math.min(calls.filter((c) => c === n).length - 1, l.length - 1)]; },
|
|
20
|
+
decide: (d) => decisions.push(d), onUpdate: (r) => { updates.push(r); onRow(r); }, ...extra });
|
|
21
|
+
return p.then((rows) => ({ rows, calls, updates, decisions, byIssue: Object.fromEntries(rows.map((r) => [r.issue, r])) }));
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
describe("#5975: batch pause", () => {
|
|
25
|
+
it("paused batch: a dependency merge does not dispatch the re-admitted dependent; after --unpause it does; the running lane completes", async () => {
|
|
26
|
+
const store = memStore(), pause = { v: null };
|
|
27
|
+
const a = await run({ script: {}, issues: [2, 1], store, pause, onStart: (n) => { if (n === 1) pause.v = REC; } });
|
|
28
|
+
assert.deepEqual(a.calls, [1], "the lane already running finishes through the pause; its dependent is not admitted");
|
|
29
|
+
assert.equal(a.byIssue[1].outcome, "merged");
|
|
30
|
+
assert.equal(a.byIssue[2].outcome, "held");
|
|
31
|
+
assert.match(a.byIssue[2].detail, /paused \(release cut, until unpause\)/);
|
|
32
|
+
assert.ok(a.updates.some((r) => r.outcome === "pause"), "a pause row");
|
|
33
|
+
pause.v = null; // --unpause, then --resume
|
|
34
|
+
const b = await run({ script: {}, issues: [2, 1], store, pause });
|
|
35
|
+
assert.deepEqual(b.calls, [2]);
|
|
36
|
+
assert.equal(b.byIssue[2].outcome, "merged");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("an engine upgrade re-admit of a held (engine/env) issue in a paused batch stays pending", async () => {
|
|
40
|
+
let v = "1.0.0"; const pause = { v: null };
|
|
41
|
+
const r = await run({ script: { 1: [EE("boom"), EE("boom"), MERGED] }, issues: [1], pause,
|
|
42
|
+
extra: { envHold: { maxMs: 120_000, watchMs: 30_000, version: () => v } },
|
|
43
|
+
onRow: (row) => { if (row.issue === 1 && row.outcome === "held") { v = "1.0.1"; pause.v = REC; } } });
|
|
44
|
+
assert.deepEqual(r.calls, [1, 1], "the upgrade would re-admit it, the pause keeps it pending");
|
|
45
|
+
assert.equal(r.byIssue[1].outcome, "held");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("a timed pause expires on its own (injected clock) and admission resumes", async () => {
|
|
49
|
+
const pause = { v: { ...REC, expiresAt: new Date(1_000_000 + 600_000).toISOString() } };
|
|
50
|
+
const clock = { t: 1_000_000 };
|
|
51
|
+
const r = await run({ script: {}, issues: [2, 1], pause, clock, extra: { expirePause: () => { const p = pause.v; if (p && Date.parse(p.expiresAt) <= clock.t) { pause.v = null; return { ...p, ownerGone: false }; } return null; } } });
|
|
52
|
+
assert.deepEqual(r.calls, [1, 2]);
|
|
53
|
+
assert.ok(r.updates.some((x) => x.outcome === "pause-expired"));
|
|
54
|
+
assert.ok(r.decisions.some((d) => /pause expired/.test(d.what)));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("without getPause (or with no pause set) admission is unchanged", async () => {
|
|
58
|
+
const r = await run({ script: {}, issues: [2, 1], extra: { getPause: null } });
|
|
59
|
+
assert.deepEqual(r.calls, [1, 2]);
|
|
60
|
+
});
|
|
61
|
+
});
|
package/bin/lean/orchestrate.mjs
CHANGED
|
@@ -124,6 +124,7 @@
|
|
|
124
124
|
* then queue order. A sub-issue's estimate is the parent's ÷ N, floored at the M default. Without `estimate` the order is
|
|
125
125
|
* the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
|
|
126
126
|
*/
|
|
127
|
+
import { decideClear } from "./clear-breaker.mjs";
|
|
127
128
|
import { parseDependsOn } from "../engine/phases.mjs";
|
|
128
129
|
import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
|
|
129
130
|
import { detectGateDeadlock, formatGateDeadlock } from "./gatewatch.mjs";
|
|
@@ -335,9 +336,9 @@ const toMap = (o) => new Map(Object.entries(o ?? {}).map(([k, v]) => [Number(k),
|
|
|
335
336
|
* @returns {Promise<Array<{issue:number, outcome:string, pr:?number, cost_usd:number, minutes:number, detail?:string}>>}
|
|
336
337
|
*/
|
|
337
338
|
export async function orchestrate({ issues, parallel = 3, runOne, readBody, prefilter = null, resolveLane = null, now = () => Date.now(), blockedRefreshMs = 60000, onUpdate = () => {}, onCrossLane = () => {},
|
|
338
|
-
store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, ackClearBreaker = null,
|
|
339
|
+
store = null, adopt = null, getParallel = null, getAdded = null, getRequeued = null, breaker = null, maxDeferrals = DEFAULT_MAX_DEFERRALS, sleep = cancellableSleep, pollMs = 5000, getClearBreaker = null, consumeClearBreaker = null, ackClearBreaker = null,
|
|
339
340
|
classify = null, maintenance = null, limits = null, identity = () => "default", batchId = null, drift = null, integration = null, sched = null, priorityOf = null, remote = null, beforeAdmit = null, preflight = null,
|
|
340
|
-
recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
|
|
341
|
+
recovery = null, decide = () => {}, conflicting = null, relabelNeedsHuman = null, markRecovering = null, onExit = null, issueLabels = null, issueState = null, getCancelled = null, getHeld = null, expireHolds = null, getPause = null, expirePause = null, getHoldInfo = null, getBlocked = null, trusted = null, getGates = null, stopLane = null, releaseLease = null, stopRetryMs = STOP_RETRY_MS, stopTimeoutMs = STOP_TIMEOUT_MS,
|
|
341
342
|
estimate = null, starveMs = DEFAULT_STARVE_MS, setupConcurrency = DEFAULT_SETUP_CONCURRENCY, signal = null, dispatchCheck = null, syncParked = null, syncEveryMs = DEFAULT_SYNC_EVERY_MS, lifecycle = null,
|
|
342
343
|
getChildren = null, autoChildren = null, baseWait = null, rotator = null, stacking = "off", readPrReady = null, transientRetries = DEFAULT_TRANSIENT_RETRIES, overload = null, version = null, onInterrupted = null, envHold = null, envIssue = null, logicalDeps = null,
|
|
343
344
|
train = null, trainEveryMs = DEFAULT_TRAIN_EVERY_MS }) {
|
|
@@ -406,6 +407,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
406
407
|
let pfAll = false, pfRemote = false, pfNoted = new Set(); // #4866: lane preflight holds
|
|
407
408
|
let opHeld = new Set(); // #4592: operator-held issues this pass (the batch `hold` file is the authority)
|
|
408
409
|
const opHeldHit = new Set(); // held issues that were pending this pass
|
|
410
|
+
let opPause = null, pauseHit = false; // #5975: the batch-level pause (the `pause` file is the authority); pauseHit: an issue was pending behind it this pass
|
|
409
411
|
// #4376: operator cancel (the batch `cancel` file through `getCancelled`); persisted, but the file stays the authority.
|
|
410
412
|
let cancelled = getCancelled ? (saved?.cancelled ?? null) : null;
|
|
411
413
|
const budget = maintenance && Number(maintenance.share) > 0 ? { share: Number(maintenance.share), whenIdle: !!maintenance.whenIdle } : null;
|
|
@@ -1310,7 +1312,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1310
1312
|
if (!["merged", "invalid", "deferred"].includes(gone?.outcome)) gone = null; // #4920: deferred = another lane owns the issue (lease or open PR on GitHub)
|
|
1311
1313
|
}
|
|
1312
1314
|
// #5526: a hold placed since the pass read is honoured at launch: the issue goes back to pending, no lane
|
|
1313
|
-
if (!cancelled && !halted) { refreshHeld(); if (opHeld.has(n)) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
|
|
1315
|
+
if (!cancelled && !halted) { refreshHeld(); refreshPause(); if (opHeld.has(n) || opPause) { running.delete(n); runRecs.delete(n); releaseSlot(n); endRemote(n); requeue(n, 0); save(); return; } }
|
|
1314
1316
|
if (halted) return; // #4454: stopped before launch; no pid, so a resume queues it again
|
|
1315
1317
|
let r;
|
|
1316
1318
|
if (cancelled) r = { terminalReason: "deferred", code: "run.interrupted", cost_usd: 0, detail: "cancelled before launch" }; // #4376
|
|
@@ -1395,7 +1397,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1395
1397
|
|
|
1396
1398
|
// #5469: a final held row names the owner and since when the hold recorded them (`forgedock orchestrate --hold ... --for`)
|
|
1397
1399
|
const heldByOperator = (n) => { let e = null; try { e = getHoldInfo?.()?.[n] ?? null; } catch { e = null; } return e ? `held by operator (${e.owner}, since ${e.since})` : "held by operator"; };
|
|
1398
|
-
const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? heldByOperator(n) : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
|
|
1400
|
+
const heldDetail = (n) => cancelled ? "cancelled by operator" : opHeld.has(n) ? heldByOperator(n) : opPause ? pauseText() : baseHeld.has(n) ? baseHeld.get(n) : tripped?.detail ?? (integHeld.has(n) ? `integration: ${integHeld.get(n)}` : (driftHeld.has(n) ? `drift: ${driftHeld.get(n)} flagged` : budgetStop ? `execution budget: ${budgetStop}` : budgetHeld ? "maintenance share" : "not run"));
|
|
1399
1401
|
// #4315: a recovery queued but never launched (the batch stopped: breaker, budget, hold; or a resume that did not relaunch a
|
|
1400
1402
|
// lost run) left the issue without needs-human, since a non-final attempt does not relabel. Relabel it once, with the full reason.
|
|
1401
1403
|
// #4318: also on a throw out of the loop and on a signal (`onExit`); `cause` overrides the held reason. Runs once per process.
|
|
@@ -1548,6 +1550,29 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1548
1550
|
s.at = t;
|
|
1549
1551
|
try { Promise.resolve(stopLane(n, rec)).then((ok) => { if (ok !== false) s.accepted = true; }, () => {}); } catch { /* best effort */ }
|
|
1550
1552
|
}
|
|
1553
|
+
// #5975: the batch pause. `paused (reason, until …)`, the one text every surface shows.
|
|
1554
|
+
function pauseText(p = opPause) { return `paused (${p?.reason ?? "no reason given"}, until ${p?.expiresAt ?? "unpause"})`; }
|
|
1555
|
+
function refreshPause() {
|
|
1556
|
+
if (!getPause) return;
|
|
1557
|
+
if (expirePause) { // like #5469 holds: a pause past its expiry is lifted here, with a row and a decision
|
|
1558
|
+
let e = null; try { e = expirePause() ?? null; } catch { e = null; }
|
|
1559
|
+
if (e) {
|
|
1560
|
+
decided({ issue: null, what: `pause expired (paused by ${e.owner} since ${e.since}${e.reason ? `: ${e.reason}` : ""}); admission resumed`, why: "pause expiry (--pause --for)", alternative: "pause it again" });
|
|
1561
|
+
update({ issue: null, outcome: "pause-expired", detail: `${e.owner}, since ${e.since}` });
|
|
1562
|
+
if (e.ownerGone) update({ issue: null, outcome: "hold-alert", detail: `the pause owner session (${e.owner}) is gone; the pause expired and admission resumed` });
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
let got = null; try { got = getPause() ?? null; } catch { got = opPause; }
|
|
1566
|
+
const next = got && typeof got === "object" ? got : null;
|
|
1567
|
+
if (next && !opPause) {
|
|
1568
|
+
decided({ issue: null, what: `batch ${pauseText(next)} (forgedock orchestrate --pause); running lanes continue`, why: "operator request", alternative: "cancel the batch" });
|
|
1569
|
+
update({ issue: null, outcome: "pause", detail: pauseText(next) });
|
|
1570
|
+
} else if (!next && opPause) {
|
|
1571
|
+
decided({ issue: null, what: "batch unpaused (forgedock orchestrate --unpause); admission resumed", why: "operator request", alternative: "resume the batch" });
|
|
1572
|
+
update({ issue: null, outcome: "unpause", detail: "admission resumed" });
|
|
1573
|
+
}
|
|
1574
|
+
opPause = next;
|
|
1575
|
+
}
|
|
1551
1576
|
// #4592: re-read the hold set; one decision and one row when it changes.
|
|
1552
1577
|
const holdExpiring = (list) => { let info = null; try { info = getHoldInfo?.() ?? null; } catch { info = null; } return !!expireHolds && list.some((n) => Number.isFinite(Date.parse(info?.[n]?.expiresAt))); }; // #5469
|
|
1553
1578
|
// #5632: a function declaration (hoisted): finish/recovery callbacks of a resumed batch can call it before this line runs
|
|
@@ -1857,9 +1882,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1857
1882
|
driftHeld.clear();
|
|
1858
1883
|
integHeld.clear();
|
|
1859
1884
|
opHeldHit.clear();
|
|
1885
|
+
pauseHit = false;
|
|
1860
1886
|
blockedHit.clear();
|
|
1861
1887
|
baseHit.clear();
|
|
1862
1888
|
refreshHeld();
|
|
1889
|
+
refreshPause();
|
|
1863
1890
|
await refreshBlocked();
|
|
1864
1891
|
await refreshBaseWaits();
|
|
1865
1892
|
checkGates();
|
|
@@ -1879,6 +1906,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1879
1906
|
await gateEnvSigs(); // #5755
|
|
1880
1907
|
const isReady = (n) => {
|
|
1881
1908
|
if (pfAll || (pfRemote && isRemote(n))) return false;
|
|
1909
|
+
if (opPause) { pauseHit = true; return false; } // #5975: every admission path (dependency merge, env/engine re-admit, requeue, add, recovery) ends here
|
|
1882
1910
|
if (opHeld.has(n)) { opHeldHit.add(n); return false; }
|
|
1883
1911
|
if (blocked.has(n)) { blockedHit.add(n); return false; } // #4773
|
|
1884
1912
|
if (baseHeld.has(n)) { baseHit.add(n); return false; } // #5031
|
|
@@ -1983,7 +2011,17 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1983
2011
|
// #4685: a breaker tripped only by link failures (a router restart) closes itself after a cooldown
|
|
1984
2012
|
if (tripped?.transport && now() - tripped.at >= TRANSPORT_COOLDOWN_MS) { tripped = null; errorTimes = []; transportErrors = 0; save(); }
|
|
1985
2013
|
// #5947: --clear-breaker on a schedd-hosted batch reaches this runner through the batch's request file
|
|
1986
|
-
if (getClearBreaker) {
|
|
2014
|
+
if (getClearBreaker) { // #5964: time-scoped; the request is consumed only after the decision, so a long pass never loses it
|
|
2015
|
+
let req = null; try { req = getClearBreaker(); } catch { req = null; }
|
|
2016
|
+
if (req) {
|
|
2017
|
+
const d = decideClear({ tripped, requestAt: req });
|
|
2018
|
+
const wasTripped = Boolean(tripped);
|
|
2019
|
+
if (d.clear) { const was = wasTripped; tripped = null; errorTimes = []; transportErrors = 0; save(); try { ackClearBreaker?.({ cleared: was }); } catch { /* advisory */ } }
|
|
2020
|
+
else if (d.stale) { try { ackClearBreaker?.({ cleared: false }); } catch { /* advisory */ } }
|
|
2021
|
+
try { consumeClearBreaker?.(); } catch { /* advisory */ }
|
|
2022
|
+
if (d.clear && wasTripped) continue; // admission ran before this check: re-run the pass so the cleared batch resumes instead of falling to the "nothing runnable" skip
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
1987
2025
|
if (tripped && !running.size) { await drainAdds(); break; } // breaker: let running lanes finish, keep the rest pending for a resume
|
|
1988
2026
|
if (cancelled && !running.size) { await drainAdds(); break; } // #4376: cancel: the rest end held for a resume
|
|
1989
2027
|
if (budgetStop && !running.size) { await drainAdds(); break; } // execution budget (stop): the same, the rest end held
|
|
@@ -2006,6 +2044,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
2006
2044
|
if (holdUntil) waits.push(holdUntil);
|
|
2007
2045
|
let wake = waits.length ? Math.max(0, Math.min(...waits) - t) : null;
|
|
2008
2046
|
if (holdUntil && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4446: a cleared hold (forgedock limits clear) admits on the next poll
|
|
2047
|
+
if (getPause && pending.length && (opPause || running.size)) wake = Math.min(wake ?? pollMs, pollMs); // #5975: an --unpause or expiry
|
|
2009
2048
|
if ((getParallel || getHeld) && pending.length) wake = Math.min(wake ?? pollMs, pollMs);
|
|
2010
2049
|
if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
|
|
2011
2050
|
if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
|
|
@@ -2032,6 +2071,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
2032
2071
|
else if (pending.length && baseHit.size) await nap(wake ?? pollMs); // #5031: only issues waiting for a base commit: poll for it
|
|
2033
2072
|
else if (pending.length && waits.length) await nap(Math.min(wake, getCancelled ? pollMs : Infinity)); // wake is poll-capped by a hold or a live K; #4454: nap wakes on a stop
|
|
2034
2073
|
else if (pending.length && budgetHeld) { if (await drainAdds()) continue; break; } // maintenance the budget does not admit now: held for a later batch
|
|
2074
|
+
else if (pending.length && opPause && pauseHit && Number.isFinite(Date.parse(opPause.expiresAt)) && !cancelled) await nap(wake ?? pollMs); // #5975: a timed pause keeps the batch open until it expires, not finalised silently
|
|
2075
|
+
else if (pending.length && opPause && pauseHit) { if (await drainAdds()) continue; break; } // #5975: paused with no expiry: pending for a --resume after --unpause
|
|
2035
2076
|
else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n)) && holdExpiring([...opHeldHit]) && !cancelled) await nap(wake ?? pollMs); // #5469: a hold with an expiry keeps the batch open until it expires (re-admit or alert), not finalised silently
|
|
2036
2077
|
else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n))) { if (await drainAdds()) continue; break; } // #4592: held by the operator: pending for a --resume
|
|
2037
2078
|
else if (pending.length && (driftHeld.size || integHeld.size)) { if (await drainAdds()) continue; break; } // held by a drift flag (block_dispatch) or a red integration streak (#4667): pending for a later batch
|
|
@@ -25,8 +25,11 @@ import { scopedEnv } from "./execution.mjs";
|
|
|
25
25
|
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
26
26
|
import { laneEnvFor, readEnvSnapshots } from "../env/env.mjs";
|
|
27
27
|
import { resolveCredential } from "./credentials.mjs";
|
|
28
|
+
import { seedMirror } from "./mirror-bundle.mjs";
|
|
28
29
|
import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
|
|
29
30
|
|
|
31
|
+
/** #5949: one log line for a launch's seed stats: bytes sent, and the time saved against shipping the whole repo at the same rate. */
|
|
32
|
+
const seedLine = (s) => (s.fallback ? `fell back to GitHub (${s.reason})` : s.upToDate ? "mirror already up to date, nothing sent" : `${s.full ? "full" : "incremental"} bundle, ${s.bytes} bytes in ${s.chunks} chunks, ${s.ms} ms${Number.isFinite(s.saved_ms) ? `, about ${Math.round(s.saved_ms / 1000)} s saved` : ""}`);
|
|
30
33
|
const REDACTED = "[redacted]";
|
|
31
34
|
const PREFETCH_MAX_B64 = 96 * 1024; // one env string stays under Linux MAX_ARG_STRLEN (128 KB)
|
|
32
35
|
/** Replace every value of `secrets` (4+ chars, longest first) in `text`. */
|
|
@@ -114,6 +117,20 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
114
117
|
if (!Array.isArray(r.data?.agents)) throw new Error("agent disk: malformed router answer");
|
|
115
118
|
return r.data.agents.map((a) => ({ name: String(a?.name ?? "?"), disk_free_gb: Number.isFinite(a?.disk_free_gb) ? a.disk_free_gb : null }));
|
|
116
119
|
},
|
|
120
|
+
/** #5949: the agent mirror's ref tips for a repo ({mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}); 404/405 = an older router/agent (unsupported). */
|
|
121
|
+
async mirrors(id, q) {
|
|
122
|
+
const r = await call("GET", `${p(id)}/mirrors?${new URLSearchParams(Object.entries(q).filter(([, v]) => v !== null && v !== undefined).map(([k, v]) => [k, String(v)]))}`);
|
|
123
|
+
if (r.status === 404 || r.status === 405) throw Object.assign(fail("mirrors", r), { unsupported: true });
|
|
124
|
+
if (!r.ok) throw fail("mirrors", r);
|
|
125
|
+
return r.data ?? {};
|
|
126
|
+
},
|
|
127
|
+
/** #5949: one bundle chunk or the finish call; a 409 carries the agent's resume offset. */
|
|
128
|
+
async seed(id, body) {
|
|
129
|
+
const r = await call("POST", `${p(id)}/seed`, body);
|
|
130
|
+
if (r.status === 404 || r.status === 405) throw Object.assign(fail("seed", r), { unsupported: true });
|
|
131
|
+
if (!r.ok) throw Object.assign(fail("seed", r), Number.isInteger(r.data?.offset) ? { offset: r.data.offset } : {});
|
|
132
|
+
return r.data ?? {};
|
|
133
|
+
},
|
|
117
134
|
/** #5735: lane sandboxes per pool agent (`GET /agents` -> `agents[].lanes {used, ceiling}`) and across all batches (`remote_lanes`; else the `fdrsbx-` keys of `sandboxes`). A bad answer throws. */
|
|
118
135
|
async agentLanes() {
|
|
119
136
|
const r = await call("GET", "/agents");
|
|
@@ -253,8 +270,21 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
253
270
|
// #4912: a ready warm sandbox first; none, an error or a transport without claim is the cold start.
|
|
254
271
|
let claimed = null;
|
|
255
272
|
if (warm && typeof transport.claim === "function") { try { claimed = await transport.claim(spec); } catch { claimed = null; } }
|
|
273
|
+
// #5949: seed the pool agent's mirror from this host first (repo_source dispatcher|github|auto); failure falls back to GitHub, or fails under `dispatcher`.
|
|
274
|
+
let seed = null;
|
|
275
|
+
const source = ["dispatcher", "github"].includes(settings.repoSource) ? settings.repoSource : "auto";
|
|
276
|
+
if (!claimed && repo && settings.repoDir && source !== "github" && typeof transport.seed === "function") {
|
|
277
|
+
try { seed = await seedMirror({ transport, id, slug: repo, cacheKey: spec.cache?.key ?? repo, repoDir: settings.repoDir, now }); }
|
|
278
|
+
catch (e) {
|
|
279
|
+
if (source === "dispatcher") throw Object.assign(new Error(`repo seeding failed (repo_source=dispatcher): ${redact(e?.message ?? e, [...known]).slice(0, 200)}`), { code: "pool.seed_failed", transient: e?.transient === true });
|
|
280
|
+
seed = { sent: false, fallback: true, reason: redact(e?.message ?? e, [...known]).slice(0, 160) };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
256
283
|
if (!claimed) await transport.launch(spec);
|
|
257
|
-
|
|
284
|
+
if (seed) {
|
|
285
|
+
try { const f = batch.logFile(issue); mkdirSync(dirname(f), { recursive: true }); appendFileSync(f, `[seed] ${seedLine(seed)}\n`); } catch { /* logging only */ }
|
|
286
|
+
}
|
|
287
|
+
return { provider: name, id, issue, startedAt, minutes: 0, ...(seed ? { seed } : {}) };
|
|
258
288
|
},
|
|
259
289
|
async status(h) {
|
|
260
290
|
let s;
|
|
@@ -55,9 +55,16 @@ export function tickText(c) {
|
|
|
55
55
|
* @returns the check, plus `killed` (and `started` when it started one)
|
|
56
56
|
*/
|
|
57
57
|
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
58
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null } = {}) {
|
|
58
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null, unit = null, emit = null } = {}) {
|
|
59
59
|
const c = stallCheck({ dir, stallMs, now, alive });
|
|
60
60
|
if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
|
|
61
|
+
// #5966: the unit says active but no daemon answers (no live pid/heartbeat): alert and restart it, whether or not batches are unfinished
|
|
62
|
+
if (c.status === "down" && start && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
|
|
63
|
+
log(`schedd watchdog: ALERT unit is active but no daemon answers (schedd status: not running); restarting the unit`);
|
|
64
|
+
try { emit?.({ type: "schedd.unit-no-daemon", at: now() }); } catch { /* advisory */ }
|
|
65
|
+
try { await start(); } catch (e) { log(`schedd watchdog: start failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false }; }
|
|
66
|
+
return { ...c, killed: null, alerted: true, started: true };
|
|
67
|
+
}
|
|
61
68
|
if (c.status === "down" && start) {
|
|
62
69
|
let ids = [];
|
|
63
70
|
try { ids = unfinished() ?? []; } catch { ids = []; }
|
|
@@ -68,4 +68,19 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
|
68
68
|
assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
|
|
69
69
|
assert.equal(bestEffortRenice(() => {}), true);
|
|
70
70
|
});
|
|
71
|
+
|
|
72
|
+
it("#5966: a down daemon while the unit is active alerts, emits an event and restarts the unit, even with no unfinished batches", async () => {
|
|
73
|
+
const dir = tmpDir("schedd-wd-unit-"), lines = [], events = [];
|
|
74
|
+
let starts = 0;
|
|
75
|
+
const run = (unit) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
|
|
76
|
+
const r = await run(() => "active");
|
|
77
|
+
assert.equal(r.started, true);
|
|
78
|
+
assert.equal(r.alerted, true);
|
|
79
|
+
assert.equal(starts, 1);
|
|
80
|
+
assert.equal(events[0].type, "schedd.unit-no-daemon");
|
|
81
|
+
assert.ok(lines.some((l) => l.includes("ALERT")));
|
|
82
|
+
await run(() => "inactive");
|
|
83
|
+
await run(() => null);
|
|
84
|
+
assert.equal(starts, 1, "an inactive or absent unit with nothing unfinished is left down");
|
|
85
|
+
});
|
|
71
86
|
});
|
package/bin/lean/schedd.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* {op:"attach", id, resume?} → (`resume` also clears a pending cancel, #4592) log.jsonl rows replayed, then live rows/lines and done; a finished batch replays report.json
|
|
12
12
|
* ({type:"done", replay:true}) unless it has unrun added issues; a batch nobody hosts is resumed here
|
|
13
13
|
* {op:"set-parallel", id, k} → {type:"ok", parallel}
|
|
14
|
-
* {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack); otherwise state.json is rewritten
|
|
14
|
+
* {op:"clear-breaker", id} → {type:"ok", cleared, acknowledged, hosted} (#5947): a hosted runner resets its in-memory breaker (request file + ack, #5964: the request is never dropped; no ack within waitMs → pending:true); otherwise state.json is rewritten
|
|
15
15
|
* {op:"set-execution", id, maxRemote?, mode?} → {type:"ok", execution} (#5138): live max_remote / placement (remote|hybrid|local); remote/hybrid refused for a batch with no provider
|
|
16
16
|
* {op:"requeue", id, issues, reason, by} → {type:"ok", requeued, refused, hosted, reopened} (#4550): see batch.requeue; a finished batch is hosted again
|
|
17
17
|
* {op:"add", id, issues} → {type:"ok", added, skipped, hosted} (#4408): merged into the batch's `add` file, which a
|
|
@@ -72,7 +72,7 @@ export function batchVerdicts(root, { now = Date.now(), windowMin = DEFAULT_STAL
|
|
|
72
72
|
try {
|
|
73
73
|
const b = openBatch(root, id);
|
|
74
74
|
if (!b.readPlan()?.daemon || b.isTerminal()) continue;
|
|
75
|
-
const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
|
|
75
|
+
const state = b.store.peek(), stall = evaluateDispatchStall(state, { held: b.readHeld(), parallel: b.readParallel(), hosted: false, paused: b.readPause?.() ?? null, lastProgressMs: b.lastProgressMs(), now, windowMin, lanesAliveMs: lanesAlive(b, state) });
|
|
76
76
|
const decision = stall ? decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, hosted: false }) : null;
|
|
77
77
|
out.push(batchVerdict(id, stall, decision));
|
|
78
78
|
} catch { /* one unreadable batch has no verdict */ }
|
|
@@ -90,6 +90,8 @@ export function sharedPendingLines(batches) {
|
|
|
90
90
|
export const ORPHAN_AGE_MS = 7 * 24 * 3600 * 1000; // #5469: an unhosted batch idle this long with pending issues is orphaned
|
|
91
91
|
export const IDLE_MS = 10 * 60 * 1000;
|
|
92
92
|
export const STOP_MS = 10 * 1000;
|
|
93
|
+
export const HARD_EXIT_MS = 30 * 1000; // #5966: a self-initiated stop exits by then even if close() hangs
|
|
94
|
+
export const SUCCESSOR_MS = 10 * 1000; // #5966: how long a handover waits for the successor to listen
|
|
93
95
|
export const LOCK_CHECK_MS = 5 * 1000;
|
|
94
96
|
export const ADMIT_MS = 120 * 1000; // #4775: how long one add/requeue/attach/resume waits for its batch to start before answering an error
|
|
95
97
|
export const LAG_MS = 5 * 1000; // #4775: an event-loop stall longer than this is logged
|
|
@@ -218,7 +220,9 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
218
220
|
root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
|
|
219
221
|
lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
|
|
220
222
|
abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
|
|
221
|
-
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined
|
|
223
|
+
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined,
|
|
224
|
+
exit = null, hardExitMs = HARD_EXIT_MS, unit = unitState, probe = undefined, successorMs = SUCCESSOR_MS, successorPollMs = 200, rehost = undefined } = {}) {
|
|
225
|
+
const startOpts = arguments[0] ?? {};
|
|
222
226
|
const p = scheddPaths(dir);
|
|
223
227
|
// #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
|
|
224
228
|
const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
|
|
@@ -237,7 +241,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
237
241
|
const conns = new Set();
|
|
238
242
|
const runs = new Map(); // every runBatch in flight (hosted or not yet started) -> its AbortController (#4454)
|
|
239
243
|
const starting = new Map(); // batch id -> host() promise of a start-up resume not yet hosted (#4503: an attach waits for it)
|
|
240
|
-
let closing = null, resolveClosed, keepSock = false;
|
|
244
|
+
let closing = null, resolveClosed, keepSock = false, stopCode = null, rehosted = null;
|
|
241
245
|
let idleTimer, lockTimer, lagTimer, stallTimer, dueTimer; // assigned below; close() clears them
|
|
242
246
|
let lastActive = Date.now();
|
|
243
247
|
const touch = () => { lastActive = Date.now(); };
|
|
@@ -370,10 +374,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
370
374
|
let acknowledged = false, cleared = false;
|
|
371
375
|
if (isHosted) {
|
|
372
376
|
const at = b.requestClearBreaker();
|
|
373
|
-
|
|
377
|
+
// #5964: never drop the request: the runner consumes it on its next pass (time-scoped against the trip)
|
|
378
|
+
const budget = Math.min(Number.isFinite(req.waitMs) && req.waitMs > 0 ? req.waitMs : 7000, 60000);
|
|
379
|
+
for (let i = 0, n = Math.ceil(budget / 50); i < n && !acknowledged; i++) {
|
|
374
380
|
const a = b.readClearBreakerAck();
|
|
375
381
|
if (a && a.at >= at) { acknowledged = true; cleared = Boolean(a.cleared); } else await new Promise((r) => setTimeout(r, 50));
|
|
376
382
|
}
|
|
383
|
+
if (!acknowledged) return send({ type: "ok", cleared: false, acknowledged: false, pending: true, hosted: true }, true);
|
|
377
384
|
}
|
|
378
385
|
if (!acknowledged) {
|
|
379
386
|
b.readClearBreaker(); // drop an unconsumed request so it cannot clear a later trip
|
|
@@ -415,6 +422,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
415
422
|
const changed = req.op === "hold" ? b.holdIssues(req.issues ?? [], req.meta ?? null) : b.releaseIssues(req.issues ?? []);
|
|
416
423
|
return send({ type: "ok", changed, held: b.readHeld(), hosted: hosted.has(req.id) }, true);
|
|
417
424
|
}
|
|
425
|
+
if (req.op === "pause" || req.op === "unpause") { // #5975: batch-level admission pause
|
|
426
|
+
const b = openBatch(root, req.id);
|
|
427
|
+
if (!b.exists()) throw new Error(`no batch ${req.id} in ${root}`);
|
|
428
|
+
if (req.op === "pause" && !req.meta?.reason) throw new Error("--pause needs --reason <text>");
|
|
429
|
+
const res = req.op === "pause" ? { pause: b.setPause(req.meta ?? {}) } : { changed: b.clearPause() };
|
|
430
|
+
return send({ type: "ok", ...res, hosted: hosted.has(req.id) }, true);
|
|
431
|
+
}
|
|
418
432
|
if (req.op === "gc-orphans") { // #5469: cancel every orphaned batch (unhosted, pending issues, idle past the threshold)
|
|
419
433
|
const { orphaned } = unhostedBatches(Date.now(), Number.isFinite(req.minAgeMs) ? req.minAgeMs : ORPHAN_AGE_MS);
|
|
420
434
|
for (const o of orphaned) openBatch(root, o.id).requestCancel({ reason: "gc-orphans" });
|
|
@@ -512,6 +526,50 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
512
526
|
});
|
|
513
527
|
return closing;
|
|
514
528
|
};
|
|
529
|
+
// #5966: a self-initiated stop (version handover, stall recovery). Under a systemd unit the process exits non-zero after a bounded
|
|
530
|
+
// drain so `Restart=` starts the successor (a hard timer fires even if close() hangs); without a unit it starts the successor and
|
|
531
|
+
// waits for it to listen, retrying once, then exits non-zero instead of lingering as an unreachable zombie.
|
|
532
|
+
const defaultProbe = () => new Promise((r) => {
|
|
533
|
+
if (process.platform === "win32") return r(true);
|
|
534
|
+
const c = createConnection(p.sock);
|
|
535
|
+
c.once("connect", () => { c.destroy(); r(true); });
|
|
536
|
+
c.once("error", () => r(false));
|
|
537
|
+
});
|
|
538
|
+
const probeFn = probe !== undefined ? probe : respawn === undefined ? defaultProbe : null;
|
|
539
|
+
const waitListening = async () => {
|
|
540
|
+
const end = Date.now() + successorMs;
|
|
541
|
+
for (;;) {
|
|
542
|
+
try { if (await probeFn()) return true; } catch { /* not yet */ }
|
|
543
|
+
if (Date.now() >= end) return false;
|
|
544
|
+
await new Promise((r) => setTimeout(r, successorPollMs));
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
let selfStopping = null;
|
|
548
|
+
const selfStop = () => (selfStopping ??= (async () => {
|
|
549
|
+
stopCode = 1;
|
|
550
|
+
const underUnit = ["active", "activating"].includes(unit());
|
|
551
|
+
let hard;
|
|
552
|
+
if (exit) { hard = setTimeout(() => { log(`schedd: stop did not finish within ${hardExitMs} ms, exiting`); exit(1); }, hardExitMs); hard.unref?.(); }
|
|
553
|
+
try {
|
|
554
|
+
await close();
|
|
555
|
+
const spawnOnce = () => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } };
|
|
556
|
+
spawnOnce();
|
|
557
|
+
if (probeFn && !underUnit) {
|
|
558
|
+
let ok = await waitListening();
|
|
559
|
+
if (!ok) { log("schedd: successor not listening; retrying"); spawnOnce(); ok = await waitListening(); }
|
|
560
|
+
if (!ok) {
|
|
561
|
+
// R1 (#5966): no successor came up: keep hosting by resuming the batches in this process (the lock is free again)
|
|
562
|
+
log(`schedd: no successor listening after ${successorMs} ms; hosting the batches again`);
|
|
563
|
+
try { rehosted = await (rehost !== undefined ? rehost() : startDaemon({ ...startOpts })); } catch (e) { log(`schedd: re-host failed: ${e?.message ?? e}`); }
|
|
564
|
+
if (rehosted?.running) { clearTimeout(hard); return; }
|
|
565
|
+
rehosted = null;
|
|
566
|
+
log("schedd: could not host again; exiting non-zero");
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
} catch (e) { log(`schedd: stop failed: ${e?.message ?? e}`); }
|
|
570
|
+
clearTimeout(hard);
|
|
571
|
+
if (exit) exit(1);
|
|
572
|
+
})());
|
|
515
573
|
idleTimer = setInterval(() => {
|
|
516
574
|
if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
|
|
517
575
|
}, Math.min(idleMs, 30_000));
|
|
@@ -525,13 +583,13 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
525
583
|
const now = loadedVersion ? versionOf() : null;
|
|
526
584
|
if (now && now !== loadedVersion) {
|
|
527
585
|
log(`schedd: install moved v${loadedVersion} → v${now}; handing over`);
|
|
528
|
-
|
|
586
|
+
selfStop();
|
|
529
587
|
return;
|
|
530
588
|
}
|
|
531
589
|
let owner = NaN;
|
|
532
590
|
try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
|
|
533
591
|
if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
|
|
534
|
-
else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); close(); }
|
|
592
|
+
else if (process.platform !== "win32" && !existsSync(p.sock)) { log(`schedd: lost socket ${p.sock}, exiting`); stopCode = 1; close(); }
|
|
535
593
|
}, lockCheckMs);
|
|
536
594
|
lockTimer.unref?.();
|
|
537
595
|
// #4775: an event loop starved by host load leaves sockets unanswered and children unreaped; leave a trace of it.
|
|
@@ -549,7 +607,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
549
607
|
// upgrade handover path (#5204): close() aborts every runner and kills the daemon's own children (lanes keep running), then a
|
|
550
608
|
// fresh daemon resumes every batch. Once per batch and ready set (recorded in health.json before the restart).
|
|
551
609
|
const restartStall = restartForStall !== undefined ? (id) => restartForStall(id)
|
|
552
|
-
: (id) => { log(`schedd: restarting to recover stalled batch ${id}`);
|
|
610
|
+
: (id) => { log(`schedd: restarting to recover stalled batch ${id}`); selfStop(); };
|
|
553
611
|
let watching = false;
|
|
554
612
|
const watchBatches = async () => {
|
|
555
613
|
if (closing || watching) return;
|
|
@@ -568,7 +626,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
568
626
|
const created = Date.parse(plan.created ?? "");
|
|
569
627
|
if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
|
|
570
628
|
const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
|
|
571
|
-
const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
|
|
629
|
+
const stallOpts = { held: b.readHeld(), paused: b.readPause?.() ?? null, parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported, lanesAliveMs: lanesAlive(b, state) };
|
|
572
630
|
let stall = evaluateDispatchStall(state, stallOpts);
|
|
573
631
|
if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
|
|
574
632
|
let gates = [];
|
|
@@ -576,7 +634,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
576
634
|
if (gates.length) stall = evaluateDispatchStall(state, { ...stallOpts, gates }) ?? stall;
|
|
577
635
|
}
|
|
578
636
|
if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
|
|
579
|
-
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
637
|
+
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, paused: b.readPause?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
580
638
|
}
|
|
581
639
|
const sig = stall ? stall.ready.join(",") : "";
|
|
582
640
|
const last = b.lastProgressMs();
|
|
@@ -642,7 +700,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
642
700
|
started.catch((e) => log(`schedd: resume ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
|
|
643
701
|
}
|
|
644
702
|
}
|
|
645
|
-
return { running: true, pid, sock: p.sock, close, closed };
|
|
703
|
+
return { running: true, pid, sock: p.sock, close: () => (rehosted ? rehosted.close() : close()), closed, stopCode: () => stopCode, rehosted: () => rehosted, settled: () => selfStopping ?? closed };
|
|
646
704
|
}
|
|
647
705
|
|
|
648
706
|
/** #5204: `version` of the package.json of this install (../../package.json), null when it cannot be read. */
|