forgedock 1.52.0 → 1.53.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/outcome-codes.mjs +3 -0
- package/bin/engine/telemetry-seam.mjs +4 -2
- package/bin/engine-cli.mjs +53 -16
- package/bin/experiment.mjs +58 -6
- package/bin/forge-utils.mjs +6 -2
- package/bin/forgedock.mjs +15 -1
- package/bin/lean/account-watch.mjs +28 -0
- package/bin/lean/account-watch.test.mjs +30 -0
- package/bin/lean/activation.mjs +20 -0
- package/bin/lean/activation.test.mjs +14 -1
- package/bin/lean/basered.mjs +115 -0
- package/bin/lean/basered.test.mjs +66 -0
- package/bin/lean/batch-health.mjs +40 -6
- package/bin/lean/batch-health.test.mjs +34 -1
- package/bin/lean/batch.mjs +41 -2
- package/bin/lean/batch.test.mjs +104 -2
- package/bin/lean/checkpoint-reconcile.mjs +43 -0
- package/bin/lean/checkpoint-reconcile.test.mjs +95 -0
- package/bin/lean/conformance.e2e.test.mjs +1 -1
- package/bin/lean/conformance.mjs +195 -22
- package/bin/lean/conformance.test.mjs +152 -5
- package/bin/lean/effects.mjs +8 -4
- package/bin/lean/execution.mjs +19 -3
- package/bin/lean/execution.test.mjs +39 -0
- package/bin/lean/findinglabel.mjs +16 -0
- package/bin/lean/findinglabel.test.mjs +39 -0
- package/bin/lean/issuewatch-release.mjs +6 -2
- package/bin/lean/issuewatch-release.test.mjs +16 -0
- package/bin/lean/issuewatch.mjs +11 -1
- package/bin/lean/lanelock.mjs +14 -0
- package/bin/lean/lean.mjs +165 -34
- package/bin/lean/lean.test.mjs +289 -9
- package/bin/lean/light.mjs +48 -7
- package/bin/lean/light.test.mjs +37 -3
- package/bin/lean/limits.test.mjs +142 -9
- package/bin/lean/orchestrate-cancel.test.mjs +143 -0
- package/bin/lean/orchestrate.mjs +96 -26
- package/bin/lean/postdeploy-check.test.mjs +39 -0
- package/bin/lean/prompts.mjs +8 -7
- package/bin/lean/quota.mjs +39 -0
- package/bin/lean/recovery.test.mjs +10 -0
- package/bin/lean/relaxation.mjs +73 -0
- package/bin/lean/relaxation.test.mjs +54 -0
- package/bin/lean/release-postmerge.mjs +119 -0
- package/bin/lean/release-rehearsal.mjs +63 -0
- package/bin/lean/release-rehearsal.test.mjs +93 -0
- package/bin/lean/release-review.e2e.test.mjs +77 -0
- package/bin/lean/release-review.mjs +198 -0
- package/bin/lean/release-review.test.mjs +180 -0
- package/bin/lean/release.mjs +228 -0
- package/bin/lean/release.test.mjs +292 -0
- package/bin/lean/rotator.mjs +150 -31
- package/bin/lean/rotator.test.mjs +105 -2
- package/bin/lean/sandbox-remote.mjs +9 -2
- package/bin/lean/schedd.mjs +49 -4
- package/bin/lean/schedd.test.mjs +87 -6
- package/bin/lean/verifier.mjs +3 -2
- package/bin/lean/verify.mjs +2 -1
- package/bin/lean/verify.test.mjs +6 -0
- package/bin/pool/agent.mjs +18 -4
- package/bin/pool/router.mjs +66 -24
- package/bin/review-staging.mjs +23 -0
- package/bin/stats/conformance-outcomes.mjs +208 -0
- package/bin/stats/conformance-outcomes.test.mjs +188 -0
- package/bin/stats/depth.mjs +218 -0
- package/bin/stats/depth.test.mjs +133 -0
- package/bin/stats/experiment.mjs +7 -5
- package/bin/stats/github-source.mjs +2 -2
- package/bin/stats/index.mjs +64 -2
- package/bin/stats/local-source.mjs +11 -0
- package/bin/stats/query.mjs +69 -0
- package/bin/stats/selffiled.mjs +52 -0
- package/bin/stats/selffiled.test.mjs +71 -0
- package/commands/orchestrate.md +1 -1
- package/commands/review-pr-agents/security.md +4 -0
- package/commands/review-pr-staging.md +2 -0
- package/commands/work-on/build.md +4 -6
- package/docs/CONFIG.md +65 -8
- package/docs/ISSUE-WATCH.md +2 -0
- package/docs/OUTCOME-CODES.md +3 -0
- package/docs/STATS.md +44 -0
- package/docs/TELEMETRY.md +1 -1
- package/package.json +1 -1
- package/pool/README.md +1 -1
- package/pool/image/cs-cred +14 -1
- package/scripts/backfill-finding-labels.mjs +50 -0
- package/scripts/backfill-finding-labels.test.mjs +36 -0
- package/scripts/doctor-pipeline-state.sh +21 -6
- package/scripts/file-deferred-followups.sh +59 -251
- package/scripts/file-deferred-followups.test.sh +85 -206
- package/scripts/followup-route.mjs +12 -0
- package/scripts/owner-route-parity.test.sh +17 -1
- package/scripts/review-pr-side-effects.test.sh +40 -0
package/bin/lean/rotator.mjs
CHANGED
|
@@ -6,13 +6,21 @@
|
|
|
6
6
|
* exhausted host. This adapter reads tokenbaton's per-account quota state: `~/.tokenbaton/current` (the account number)
|
|
7
7
|
* and `~/.tokenbaton/live.<n>` (`"<5h used %> <5h reset epoch s> <weekly used %> <weekly reset epoch s> <updated s>"`).
|
|
8
8
|
* Every method re-reads the files (no cache), never writes, and fails open: unreadable state behaves as no rotator.
|
|
9
|
+
* #5205: detected without config when TOKENBATON_HOME is set or the shim is the first `claude` on PATH; a sample whose
|
|
10
|
+
* reset has passed is stale (unknown, never 0%); callers pass the accounts that just hit a limit as `exclude`; a rotation
|
|
11
|
+
* relaunch pins an account picked here (tokenbaton#3 `--pick --json --exclude` when the CLI has it, else live.N).
|
|
9
12
|
*/
|
|
10
|
-
import {
|
|
13
|
+
import { spawnSync } from "node:child_process";
|
|
14
|
+
import { accessSync, constants, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
11
15
|
import { homedir } from "node:os";
|
|
12
|
-
import { join } from "node:path";
|
|
16
|
+
import { basename, delimiter, join } from "node:path";
|
|
13
17
|
import { backendIdentity } from "../engine.mjs";
|
|
14
18
|
|
|
15
19
|
export const ROTATOR_KINDS = ["tokenbaton"];
|
|
20
|
+
/** Env switch: `off` disables auto-detection (bin/tests/_tmp.mjs sets it for test processes, #5205). */
|
|
21
|
+
export const ROTATOR_ENV = "FORGEDOCK_ACCOUNT_ROTATOR";
|
|
22
|
+
/** Bound on every tokenbaton / tokenbaton-ctl call (ms). */
|
|
23
|
+
export const ROTATOR_CALL_TIMEOUT_MS = 5000;
|
|
16
24
|
/** An account has headroom below this 5-hour use (%), like the computeshare quota-aware picker. */
|
|
17
25
|
export const HEADROOM_PCT = 95;
|
|
18
26
|
|
|
@@ -20,16 +28,74 @@ export const HEADROOM_PCT = 95;
|
|
|
20
28
|
export function parseLive(text) {
|
|
21
29
|
const f = String(text ?? "").trim().split(/\s+/).map(Number);
|
|
22
30
|
if (f.length < 4 || !f.slice(0, 4).every(Number.isFinite)) return null;
|
|
23
|
-
return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000 };
|
|
31
|
+
return { fiveHourPct: f[0], fiveHourResetMs: f[1] * 1000, weeklyPct: f[2], weeklyResetMs: f[3] * 1000, updatedMs: Number.isFinite(f[4]) && f[4] > 0 ? f[4] * 1000 : 0 };
|
|
24
32
|
}
|
|
25
33
|
|
|
34
|
+
/** #5236: a sample older than this is unknown for the 5-hour window, whatever its reset says (0 or absent updated = age unknown). */
|
|
35
|
+
export const ROTATOR_SAMPLE_MAX_AGE_MS = 30 * 60000;
|
|
36
|
+
|
|
37
|
+
const isExec = (p) => { try { accessSync(p, constants.X_OK); return true; } catch { return false; } };
|
|
38
|
+
const real = (p) => { try { return realpathSync(p); } catch { return p; } };
|
|
39
|
+
/** True when `p` (resolved) is tokenbaton's shim: `tokenbaton-exec`, or a `.tokenbaton/shim/claude`. */
|
|
40
|
+
export const isShim = (p) => { const r = real(p); return basename(r) === "tokenbaton-exec" || /[\\/]\.tokenbaton[\\/]shim[\\/]claude$/.test(r); };
|
|
41
|
+
/** Every executable `claude` on env.PATH, in PATH order. */
|
|
42
|
+
const claudesOnPath = (env) => String(env?.PATH ?? "").split(delimiter).filter(Boolean).map((d) => join(d, "claude")).filter(isExec);
|
|
43
|
+
/** First `claude` on PATH, or null. */
|
|
44
|
+
export const firstClaude = (env = process.env) => claudesOnPath(env)[0] ?? null;
|
|
45
|
+
/** The real claude: the first `claude` on PATH that is not the shim (the shim's own rule), or null. */
|
|
46
|
+
export const realClaude = (env = process.env) => claudesOnPath(env).find((c) => !isShim(c)) ?? null;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The account rotator in use (#5205): explicit `execution.account_rotator: tokenbaton` wins; `off` (or env
|
|
50
|
+
* FORGEDOCK_ACCOUNT_ROTATOR=off) disables; unset auto-detects TOKENBATON_HOME or the shim first on PATH.
|
|
51
|
+
* @returns {"tokenbaton"|null}
|
|
52
|
+
*/
|
|
53
|
+
export function rotatorKind({ execution = null, env = process.env, which = firstClaude } = {}) {
|
|
54
|
+
const set = execution?.accountRotator;
|
|
55
|
+
if (ROTATOR_KINDS.includes(set)) return set;
|
|
56
|
+
if (set === "off" || String(env?.[ROTATOR_ENV] ?? "").toLowerCase() === "off") return null;
|
|
57
|
+
if (env?.TOKENBATON_HOME) return "tokenbaton";
|
|
58
|
+
try { const c = which(env); return c && isShim(c) ? "tokenbaton" : null; } catch { return null; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The account a running claude uses, from /proc/<pid>/environ: TOKENBATON_ACCOUNT, else CLAUDE_CONFIG_DIR=<home>/.claude-<n>; null when unreadable. */
|
|
62
|
+
export function accountOfPid(pid, { procRoot = "/proc", readFile = (p) => readFileSync(p, "utf8") } = {}) {
|
|
63
|
+
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
64
|
+
let vars;
|
|
65
|
+
try { vars = String(readFile(join(procRoot, String(pid), "environ"))).split("\0"); } catch { return null; }
|
|
66
|
+
const get = (k) => { const v = vars.find((x) => x.startsWith(`${k}=`)); return v === undefined ? null : v.slice(k.length + 1); };
|
|
67
|
+
const t = Number(get("TOKENBATON_ACCOUNT"));
|
|
68
|
+
if (get("TOKENBATON_ACCOUNT") && Number.isInteger(t) && t > 0) return t;
|
|
69
|
+
const m = /[\\/]\.claude-(\d+)[\\/]?$/.exec(get("CLAUDE_CONFIG_DIR") ?? "");
|
|
70
|
+
return m ? Number(m[1]) : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `exclude` as a Map account -> until ms (null when unknown): accepts a Set/array of numbers, a Map, or a plain object. */
|
|
74
|
+
export function excludeMap(exclude) {
|
|
75
|
+
const out = new Map();
|
|
76
|
+
if (!exclude) return out;
|
|
77
|
+
const add = (n, until) => { const k = Number(n); if (Number.isInteger(k) && k > 0) out.set(k, Number.isFinite(Number(until)) && until !== null ? Number(until) : null); };
|
|
78
|
+
if (exclude instanceof Map) for (const [n, u] of exclude) add(n, u);
|
|
79
|
+
else if (Array.isArray(exclude) || exclude instanceof Set) for (const n of exclude) add(n, null);
|
|
80
|
+
else if (typeof exclude === "object") for (const [n, u] of Object.entries(exclude)) add(n, u);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const defaultExec = (cmd, args, { env, timeout = ROTATOR_CALL_TIMEOUT_MS } = {}) => {
|
|
85
|
+
const r = spawnSync(cmd, args, { encoding: "utf8", timeout, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], env });
|
|
86
|
+
return { status: r.error ? null : r.status, stdout: String(r.stdout ?? "") };
|
|
87
|
+
};
|
|
88
|
+
|
|
26
89
|
/**
|
|
27
|
-
* Handle on an account rotator, or null (unknown kind, or no readable state).
|
|
28
|
-
*
|
|
90
|
+
* Handle on an account rotator, or null (unknown kind, or no readable state). The state dir is env.TOKENBATON_HOME
|
|
91
|
+
* (as-is) unless `home` is passed, else ~/.tokenbaton.
|
|
92
|
+
* @returns {null | {kind, accounts, current(), headroom(exclude), resumeAt(exclude), pick({exclude}), markLimited(n, untilMs),
|
|
93
|
+
* accountOfPid(pid), realClaude(env), accountIdentity(n), currentIdentity(), isAccount(id)}}
|
|
29
94
|
*/
|
|
30
|
-
export function openRotator({ kind, home =
|
|
95
|
+
export function openRotator({ kind, home = undefined, env = process.env, now = () => Date.now(), readFile = (p) => readFileSync(p, "utf8"), listDir = (d) => readdirSync(d), exec = defaultExec, stat = (p) => statSync(p).mtimeMs } = {}) {
|
|
31
96
|
if (!ROTATOR_KINDS.includes(kind)) return null;
|
|
32
|
-
const dir = join(home, ".tokenbaton");
|
|
97
|
+
const dir = home === undefined && env?.TOKENBATON_HOME ? String(env.TOKENBATON_HOME) : join(home ?? homedir(), ".tokenbaton");
|
|
98
|
+
const userHome = home ?? homedir();
|
|
33
99
|
const current = () => { try { const n = Number(String(readFile(join(dir, "current"))).trim()); return Number.isInteger(n) && n > 0 ? n : null; } catch { return null; } };
|
|
34
100
|
const accounts = () => {
|
|
35
101
|
let names = [];
|
|
@@ -40,32 +106,83 @@ export function openRotator({ kind, home = homedir(), env = process.env, now = (
|
|
|
40
106
|
if (!m) continue;
|
|
41
107
|
let live = null;
|
|
42
108
|
try { live = parseLive(readFile(join(dir, name))); } catch { live = null; }
|
|
43
|
-
if (live)
|
|
109
|
+
if (!live) continue;
|
|
110
|
+
const aged = live.updatedMs > 0 && now() - live.updatedMs > ROTATOR_SAMPLE_MAX_AGE_MS;
|
|
111
|
+
// #5236: the polled `used.N` percent, when newer than the sample and itself fresh, replaces the 5-hour figure.
|
|
112
|
+
let polled = null;
|
|
113
|
+
try {
|
|
114
|
+
const p = Number(String(readFile(join(dir, `used.${m[1]}`))).trim().split(/\s+/)[0]), at = stat(join(dir, `used.${m[1]}`));
|
|
115
|
+
if (Number.isFinite(p) && p >= 0 && Number.isFinite(at) && at > live.updatedMs && now() - at <= ROTATOR_SAMPLE_MAX_AGE_MS) polled = p;
|
|
116
|
+
} catch { polled = null; }
|
|
117
|
+
out.push({ n: Number(m[1]), ...live, polledPct: polled, aged: aged && polled === null, stale: live.fiveHourResetMs <= now() || live.weeklyResetMs <= now() || (aged && polled === null) });
|
|
44
118
|
}
|
|
45
119
|
return out.sort((a, b) => a.n - b.n);
|
|
46
120
|
};
|
|
47
121
|
if (current() === null || !accounts().length) return null;
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
const
|
|
122
|
+
// #5205: a window whose reset has passed is unknown (null), never 0%.
|
|
123
|
+
const used = (pct, resetMs) => (resetMs <= now() ? null : pct);
|
|
124
|
+
const full = (a) => { const r = []; const f = a.polledPct !== null && a.polledPct !== undefined ? a.polledPct : a.aged ? null : used(a.fiveHourPct, a.fiveHourResetMs), w = used(a.weeklyPct, a.weeklyResetMs);
|
|
125
|
+
if (f !== null && f >= HEADROOM_PCT) r.push(a.fiveHourResetMs); if (w !== null && w >= 100) r.push(a.weeklyResetMs); return r; };
|
|
126
|
+
/** "room" (fresh, under the caps), "stale" (a window unknown, none known full: worth one try), or "full". */
|
|
127
|
+
const state = (a) => (full(a).length ? "full" : a.stale ? "stale" : "room");
|
|
128
|
+
const resumeAt = (exclude) => {
|
|
129
|
+
const ex = excludeMap(exclude), t = now();
|
|
130
|
+
const at = accounts().map((a) => {
|
|
131
|
+
if (ex.has(a.n)) { const r = [ex.get(a.n), ...full(a)].filter((x) => Number.isFinite(x) && x > t); return r.length ? Math.max(...r) : NaN; }
|
|
132
|
+
return state(a) === "full" ? Math.max(...full(a)) : t;
|
|
133
|
+
}).filter((x) => Number.isFinite(x) && x > 0);
|
|
134
|
+
return at.length ? Math.min(...at) : null;
|
|
135
|
+
};
|
|
136
|
+
const localPick = (exclude) => {
|
|
137
|
+
const ex = excludeMap(exclude), list = accounts().filter((a) => !ex.has(a.n));
|
|
138
|
+
const fresh = list.filter((a) => state(a) === "room").sort((a, b) => (a.polledPct ?? a.fiveHourPct) - (b.polledPct ?? b.fiveHourPct) || a.n - b.n);
|
|
139
|
+
if (fresh.length) return { account: fresh[0].n, stale: false };
|
|
140
|
+
const stale = list.filter((a) => state(a) === "stale");
|
|
141
|
+
if (stale.length) return { account: stale[0].n, stale: true };
|
|
142
|
+
return { account: null, earliestReset: resumeAt(ex) };
|
|
143
|
+
};
|
|
144
|
+
const childEnv = () => ({ ...process.env, ...env, TOKENBATON_HOME: dir });
|
|
145
|
+
const accountIdentity = (n) => backendIdentity({ backend: "cli", env: { ...env, CLAUDE_CONFIG_DIR: join(userHome, `.claude-${n}`) } });
|
|
51
146
|
return {
|
|
52
147
|
kind,
|
|
53
|
-
/** The accounts with readable `live.N` state, re-read on every access. */
|
|
148
|
+
/** The accounts with readable `live.N` state (`stale` when a window's reset has passed), re-read on every access. */
|
|
54
149
|
get accounts() { return accounts(); },
|
|
55
150
|
current,
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
151
|
+
/** The tokenbaton state dir read. */
|
|
152
|
+
dir,
|
|
153
|
+
/** True when any non-excluded account has headroom (a fresh sample under the caps, or a stale one: worth a try). */
|
|
154
|
+
headroom: (exclude) => { const ex = excludeMap(exclude); return accounts().some((a) => !ex.has(a.n) && state(a) !== "full"); },
|
|
155
|
+
/** Epoch ms at which the first account regains headroom (now when one has it), or null when unknown; excluded ones count from their until. */
|
|
156
|
+
resumeAt,
|
|
157
|
+
/**
|
|
158
|
+
* The account to run on next (#5205): tokenbaton#3 `--pick --json --exclude` when the CLI prints JSON (exit 2 = none),
|
|
159
|
+
* else from live.N (fresh lowest use first, then stale). {account, stale} | {account:null, earliestReset}.
|
|
160
|
+
*/
|
|
161
|
+
pick: ({ exclude } = {}) => {
|
|
162
|
+
const ex = excludeMap(exclude);
|
|
163
|
+
try {
|
|
164
|
+
const r = exec("tokenbaton", ["--pick", "--json", ...(ex.size ? ["--exclude", [...ex.keys()].join(",")] : [])], { env: childEnv() });
|
|
165
|
+
let j = null; try { j = JSON.parse(String(r?.stdout ?? "").trim()); } catch { j = null; }
|
|
166
|
+
if (j && typeof j === "object") {
|
|
167
|
+
const n = Number(j.account);
|
|
168
|
+
if (r.status === 0 && Number.isInteger(n) && n > 0 && !ex.has(n)) return { account: n, stale: Boolean(j.stale) };
|
|
169
|
+
if (r.status === 2) { const e = Number(j.earliest_reset); return { account: null, earliestReset: Number.isFinite(e) && e > 0 ? e * 1000 : resumeAt(ex) }; }
|
|
170
|
+
}
|
|
171
|
+
} catch { /* fall back to live.N */ }
|
|
172
|
+
try { return localPick(ex); } catch { return { account: null, earliestReset: null }; }
|
|
173
|
+
},
|
|
174
|
+
/** Best-effort `tokenbaton-ctl mark-limited <n> --until <epoch s>`; false when unsupported. Never writes files itself. */
|
|
175
|
+
markLimited: (n, untilMs) => {
|
|
176
|
+
try {
|
|
177
|
+
if (!Number.isInteger(n) || n <= 0) return false;
|
|
178
|
+
const args = ["mark-limited", String(n), ...(Number.isFinite(untilMs) ? ["--until", String(Math.round(untilMs / 1000))] : [])];
|
|
179
|
+
return exec("tokenbaton-ctl", args, { env: childEnv() })?.status === 0;
|
|
180
|
+
} catch { return false; }
|
|
68
181
|
},
|
|
182
|
+
accountOfPid: (pid, opts) => { try { return accountOfPid(pid, opts); } catch { return null; } },
|
|
183
|
+
realClaude: (e = env) => { try { return realClaude(e); } catch { return null; } },
|
|
184
|
+
/** CLAUDE_CONFIG_DIR of account n. */
|
|
185
|
+
configDir: (n) => join(userHome, `.claude-${n}`),
|
|
69
186
|
accountIdentity,
|
|
70
187
|
/** Identity of the current account; null when `current` is unreadable. */
|
|
71
188
|
currentIdentity: () => { const n = current(); return n === null ? null : accountIdentity(n); },
|
|
@@ -74,23 +191,25 @@ export function openRotator({ kind, home = homedir(), env = process.env, now = (
|
|
|
74
191
|
};
|
|
75
192
|
}
|
|
76
193
|
|
|
77
|
-
/** True while a usage-limited call should be retried at once on the next account: headroom, and fewer tries than accounts. */
|
|
78
|
-
export function rotatorRetry(rotator, tries) {
|
|
79
|
-
try { return Boolean(rotator) && tries < rotator.accounts.length && rotator.headroom(); } catch { return false; }
|
|
194
|
+
/** True while a usage-limited call should be retried at once on the next account: headroom (outside `exclude`), and fewer tries than accounts. */
|
|
195
|
+
export function rotatorRetry(rotator, tries, exclude = null) {
|
|
196
|
+
try { return Boolean(rotator) && tries < rotator.accounts.length && rotator.headroom(exclude); } catch { return false; }
|
|
80
197
|
}
|
|
81
198
|
|
|
82
199
|
/**
|
|
83
200
|
* How orchestrate requeues a `rate_limited` lane under a rotator (#5094), or null when the host hold applies (no rotator,
|
|
84
|
-
* no account with headroom
|
|
201
|
+
* no account with headroom outside `exclude`, unreadable state). A lane that ran on one of the rotator's accounts (or reported none) is rerun
|
|
85
202
|
* at once, at most once per account; any other credential (a remote sandbox's) waits for its own reset. Neither sets a host hold.
|
|
203
|
+
* #5203: `poolId` (orchestrate's `remote.identity()`, the pool hold key) rotates like a rotator account: since #5165 the pool
|
|
204
|
+
* router hands each sandbox the lowest-usage tokenbaton login, so a rerun lands on another account.
|
|
86
205
|
* @returns {null | {delayMs:number, rotated:boolean}}
|
|
87
206
|
*/
|
|
88
|
-
export function quotaRequeue({ rotator, r, prior = null, delayMs }) {
|
|
207
|
+
export function quotaRequeue({ rotator, r, prior = null, delayMs, exclude = null, poolId = null }) {
|
|
89
208
|
if (!rotator) return null;
|
|
90
209
|
try {
|
|
91
|
-
if (!rotator.headroom()) return null;
|
|
210
|
+
if (!rotator.headroom(exclude)) return null;
|
|
92
211
|
const id = r?.backendId ?? null, rotations = Number(prior?.rotations) || 0;
|
|
93
|
-
if ((!id || rotator.isAccount(id)) && rotations < rotator.accounts.length) return { delayMs: 0, rotated: true };
|
|
212
|
+
if ((!id || (poolId && id === poolId) || rotator.isAccount(id)) && rotations < rotator.accounts.length) return { delayMs: 0, rotated: true };
|
|
94
213
|
return { delayMs, rotated: false };
|
|
95
214
|
} catch { return null; }
|
|
96
215
|
}
|
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { parseLive, openRotator, rotatorRetry, quotaRequeue, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
|
|
8
|
+
import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
|
|
9
9
|
import { laneBackendId, openLimits } from "./limits.mjs";
|
|
10
10
|
import { orchestrate, formatTable } from "./orchestrate.mjs";
|
|
11
11
|
import { parseExecution } from "./execution.mjs";
|
|
@@ -25,7 +25,7 @@ const H = 3_600_000;
|
|
|
25
25
|
|
|
26
26
|
describe("account rotator adapter (#5094)", () => {
|
|
27
27
|
it("parseLive reads the five fields and rejects malformed lines", () => {
|
|
28
|
-
assert.deepEqual(parseLive("42 1800000100 7 1800500000 1800000000"), { fiveHourPct: 42, fiveHourResetMs: 1_800_000_100_000, weeklyPct: 7, weeklyResetMs: 1_800_500_000_000 });
|
|
28
|
+
assert.deepEqual(parseLive("42 1800000100 7 1800500000 1800000000"), { fiveHourPct: 42, fiveHourResetMs: 1_800_000_100_000, weeklyPct: 7, weeklyResetMs: 1_800_500_000_000, updatedMs: 1_800_000_000_000 });
|
|
29
29
|
assert.equal(parseLive(""), null);
|
|
30
30
|
assert.equal(parseLive("12 abc 3 4"), null);
|
|
31
31
|
assert.equal(parseLive("1 2 3"), null);
|
|
@@ -83,6 +83,10 @@ describe("account rotator adapter (#5094)", () => {
|
|
|
83
83
|
assert.deepEqual(quotaRequeue({ rotator: rot, r: {}, delayMs: 600_000 }), { delayMs: 0, rotated: true });
|
|
84
84
|
assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "acct-1" }, prior: { rotations: 2 }, delayMs: 600_000 }), { delayMs: 600_000, rotated: false });
|
|
85
85
|
assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "sandbox-cred" }, delayMs: 600_000 }), { delayMs: 600_000, rotated: false }, "R6: remote credential");
|
|
86
|
+
assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "remote:pool" }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 0, rotated: true }, "#5203: the pool rotates");
|
|
87
|
+
assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "remote:pool" }, prior: { rotations: 2 }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 600_000, rotated: false }, "#5203: capped at the account count");
|
|
88
|
+
assert.deepEqual(quotaRequeue({ rotator: rot, r: { backendId: "sandbox-cred" }, delayMs: 600_000, poolId: "remote:pool" }), { delayMs: 600_000, rotated: false });
|
|
89
|
+
assert.equal(quotaRequeue({ rotator: { ...rot, headroom: () => false }, r: { backendId: "remote:pool" }, delayMs: 1, poolId: "remote:pool" }), null);
|
|
86
90
|
assert.equal(quotaRequeue({ rotator: { ...rot, headroom: () => false }, r: {}, delayMs: 1 }), null);
|
|
87
91
|
assert.equal(quotaRequeue({ rotator: null, r: {}, delayMs: 1 }), null);
|
|
88
92
|
});
|
|
@@ -141,3 +145,102 @@ describe("orchestrate with an account rotator (#5094)", () => {
|
|
|
141
145
|
assert.equal(starts[1], T0 + H);
|
|
142
146
|
});
|
|
143
147
|
});
|
|
148
|
+
|
|
149
|
+
describe("account rotator: detection, staleness, exclusion, pick (#5205)", () => {
|
|
150
|
+
const exe = (path, body = "#!/bin/sh\nexit 0\n") => { mkdirSync(join(path, ".."), { recursive: true }); writeFileSync(path, body, { mode: 0o755 }); return path; };
|
|
151
|
+
|
|
152
|
+
it("#5205 rotatorKind: explicit wins, off disables, TOKENBATON_HOME or the shim first on PATH detects, absent -> null", () => {
|
|
153
|
+
const root = tmpDir("kind-");
|
|
154
|
+
const shimDir = join(root, ".tokenbaton", "shim"), realDir = join(root, "bin");
|
|
155
|
+
exe(join(shimDir, "claude")); exe(join(realDir, "claude"));
|
|
156
|
+
assert.equal(rotatorKind({ execution: { accountRotator: "tokenbaton" }, env: { FORGEDOCK_ACCOUNT_ROTATOR: "off" } }), "tokenbaton");
|
|
157
|
+
assert.equal(rotatorKind({ execution: { accountRotator: "off" }, env: { TOKENBATON_HOME: root } }), null);
|
|
158
|
+
assert.equal(rotatorKind({ execution: {}, env: { TOKENBATON_HOME: root, FORGEDOCK_ACCOUNT_ROTATOR: "off" } }), null);
|
|
159
|
+
assert.equal(rotatorKind({ execution: null, env: { TOKENBATON_HOME: root } }), "tokenbaton");
|
|
160
|
+
assert.equal(rotatorKind({ env: { PATH: `${shimDir}:${realDir}` } }), "tokenbaton", "shim first on PATH");
|
|
161
|
+
assert.equal(rotatorKind({ env: { PATH: `${realDir}:${shimDir}` } }), null, "real claude first");
|
|
162
|
+
assert.equal(rotatorKind({ env: { PATH: "" } }), null, "absent");
|
|
163
|
+
assert.equal(realClaude({ PATH: `${shimDir}:${realDir}` }), join(realDir, "claude"));
|
|
164
|
+
assert.equal(parseExecution({ account_rotator: "off" }).accountRotator, "off");
|
|
165
|
+
assert.equal(parseExecution({ account_rotator: "none" }).accountRotator, "off");
|
|
166
|
+
assert.equal(parseExecution({}).accountRotator, undefined);
|
|
167
|
+
assert.equal(openRotator({ kind: "off", home: baton(1, { 1: [0, T0 + H, 0, T0 + H] }).home }), null);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("#5205 TOKENBATON_HOME is the state dir as-is", () => {
|
|
171
|
+
const b = baton(2, { 1: [10, T0 + H, 0, T0 + 9 * H], 2: [20, T0 + H, 0, T0 + 9 * H] });
|
|
172
|
+
const rot = openRotator({ kind: "tokenbaton", env: { TOKENBATON_HOME: join(b.home, ".tokenbaton") }, now: () => T0 });
|
|
173
|
+
assert.equal(rot.dir, join(b.home, ".tokenbaton"));
|
|
174
|
+
assert.deepEqual(rot.accounts.map((a) => a.n), [1, 2]);
|
|
175
|
+
assert.equal(rot.current(), 2);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("#5236 --pick fails and the only account is at its weekly limit: no account is picked (never the default profile)", () => {
|
|
179
|
+
const b = baton(1, { 1: [10, T0 + H, 100, T0 + 9 * H] });
|
|
180
|
+
const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: () => ({ status: 1, stdout: "" }) });
|
|
181
|
+
assert.equal(rot.pick().account, null);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("#5236 a sample older than the max age is unknown even with a future reset; a newer polled used.N replaces the 5h figure", () => {
|
|
185
|
+
const b = baton(1, { 1: [10, T0 + H, 0, T0 + 90 * H], 2: [50, T0 + H, 0, T0 + 90 * H] });
|
|
186
|
+
const dir = join(b.home, ".tokenbaton");
|
|
187
|
+
writeFileSync(join(dir, "live.1"), `10 ${Math.round((T0 + H) / 1000)} 0 ${Math.round((T0 + 90 * H) / 1000)} ${Math.round((T0 - 3 * H) / 1000)}\n`); // updated 3h ago
|
|
188
|
+
const noCli = () => ({ status: 1, stdout: "" });
|
|
189
|
+
const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: noCli, stat: () => T0 });
|
|
190
|
+
assert.equal(rot.accounts.find((a) => a.n === 1).stale, true);
|
|
191
|
+
assert.deepEqual(rot.pick(), { account: 2, stale: false }, "old 10% ranks after the fresh 50%");
|
|
192
|
+
writeFileSync(join(dir, "used.2"), "97\n"); // polled, newer than live.2's sample age
|
|
193
|
+
const rot2 = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0 + 1000, exec: noCli, stat: () => T0 + 500 });
|
|
194
|
+
assert.deepEqual(rot2.pick(), { account: 1, stale: true }, "polled 97% blocks account 2");
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("#5205 a stale sample is unknown, never 0%: ranked after a fresh one, and an excluded account never counts as room", () => {
|
|
198
|
+
// account 1: 99% with a passed reset (stale); account 4: fresh 47%; account 2: fresh 97% (full)
|
|
199
|
+
const b = baton(1, { 1: [99, T0 - H, 50, T0 + 90 * H], 2: [97, T0 + 2 * H, 10, T0 + 90 * H], 4: [47, T0 + H, 10, T0 + 90 * H] });
|
|
200
|
+
const noCli = () => ({ status: 1, stdout: "3\n" }); // installed tokenbaton without tokenbaton#3: a bare number
|
|
201
|
+
const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: noCli });
|
|
202
|
+
assert.equal(rot.accounts.find((a) => a.n === 1).stale, true);
|
|
203
|
+
assert.deepEqual(rot.pick(), { account: 4, stale: false }, "fresh 47% before stale");
|
|
204
|
+
assert.deepEqual(rot.pick({ exclude: [4] }), { account: 1, stale: true }, "stale is worth one try");
|
|
205
|
+
assert.equal(rot.headroom([4]), true);
|
|
206
|
+
assert.equal(rot.headroom([1, 4]), false, "excluded never counts as room; 2 is full");
|
|
207
|
+
const none = rot.pick({ exclude: new Map([[1, T0 + 3 * H], [4, T0 + 4 * H]]) });
|
|
208
|
+
assert.deepEqual(none, { account: null, earliestReset: T0 + 2 * H });
|
|
209
|
+
assert.equal(rot.resumeAt(new Map([[1, T0 + 3 * H], [4, T0 + 4 * H]])), T0 + 2 * H);
|
|
210
|
+
assert.equal(rotatorRetry(rot, 0, [1, 2, 4]), false);
|
|
211
|
+
assert.equal(quotaRequeue({ rotator: rot, r: {}, delayMs: 5, exclude: [1, 4] }), null);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("#5205 pick uses tokenbaton#3 --pick --json --exclude when it prints JSON (exit 2 = none, earliest_reset)", () => {
|
|
215
|
+
const b = baton(1, { 1: [10, T0 + H, 0, T0 + 9 * H], 2: [20, T0 + H, 0, T0 + 9 * H] });
|
|
216
|
+
const calls = [];
|
|
217
|
+
let reply = { status: 0, stdout: '{"account":2}' };
|
|
218
|
+
const exec = (cmd, args, opts) => { calls.push([cmd, args, opts.env.TOKENBATON_HOME]); return reply; };
|
|
219
|
+
const rot = openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec });
|
|
220
|
+
assert.deepEqual(rot.pick({ exclude: [1] }), { account: 2, stale: false });
|
|
221
|
+
assert.deepEqual(calls[0], ["tokenbaton", ["--pick", "--json", "--exclude", "1"], join(b.home, ".tokenbaton")]);
|
|
222
|
+
reply = { status: 2, stdout: JSON.stringify({ account: null, earliest_reset: Math.round((T0 + 5 * H) / 1000) }) };
|
|
223
|
+
assert.deepEqual(rot.pick({ exclude: [1, 2] }), { account: null, earliestReset: T0 + 5 * H });
|
|
224
|
+
reply = { status: 0, stdout: "1\n" }; // pre-#3 CLI: live.N fallback
|
|
225
|
+
assert.deepEqual(rot.pick({ exclude: [1] }), { account: 2, stale: false });
|
|
226
|
+
reply = { status: 0, stdout: "" };
|
|
227
|
+
assert.equal(rot.markLimited(1, T0 + H), true);
|
|
228
|
+
assert.deepEqual(calls.at(-1).slice(0, 2), ["tokenbaton-ctl", ["mark-limited", "1", "--until", String(Math.round((T0 + H) / 1000))]]);
|
|
229
|
+
reply = { status: 2, stdout: "unknown command" };
|
|
230
|
+
assert.equal(rot.markLimited(1, T0 + H), false, "unsupported: ignored");
|
|
231
|
+
assert.equal(openRotator({ kind: "tokenbaton", home: b.home, env: {}, now: () => T0, exec: () => { throw new Error("boom"); } }).pick().account, 1, "fails open to live.N");
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("#5205 accountOfPid reads TOKENBATON_ACCOUNT, else CLAUDE_CONFIG_DIR, from /proc/<pid>/environ; null when unreadable", () => {
|
|
235
|
+
const proc = tmpDir("proc-");
|
|
236
|
+
const env = (pid, vars) => { mkdirSync(join(proc, String(pid)), { recursive: true }); writeFileSync(join(proc, String(pid), "environ"), `${vars.join("\0")}\0`); };
|
|
237
|
+
env(11, ["PATH=/bin", "TOKENBATON_ACCOUNT=3", "CLAUDE_CONFIG_DIR=/home/x/.claude-1"]);
|
|
238
|
+
env(12, ["PATH=/bin", "CLAUDE_CONFIG_DIR=/home/x/.claude-2"]);
|
|
239
|
+
env(13, ["PATH=/bin", "CLAUDE_CONFIG_DIR=/home/x/.claude"]);
|
|
240
|
+
assert.equal(accountOfPid(11, { procRoot: proc }), 3);
|
|
241
|
+
assert.equal(accountOfPid(12, { procRoot: proc }), 2);
|
|
242
|
+
assert.equal(accountOfPid(13, { procRoot: proc }), null);
|
|
243
|
+
assert.equal(accountOfPid(99, { procRoot: proc }), null);
|
|
244
|
+
assert.equal(accountOfPid(undefined, { procRoot: proc }), null);
|
|
245
|
+
});
|
|
246
|
+
});
|
|
@@ -146,6 +146,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
146
146
|
if (!transport) throw new Error("remote provider needs a transport");
|
|
147
147
|
const idFor = (issue) => `fdrsbx-${safeSegment(batch.id)}-${issue}`;
|
|
148
148
|
const known = new Set(); // secret values seen this process, for redaction
|
|
149
|
+
const stopWhy = new Map(); // #5241: sandbox id -> why its last stop was not accepted
|
|
149
150
|
const remember = (v) => { if (typeof v === "string" && v.length >= 4) known.add(v); };
|
|
150
151
|
for (const k of settings.secrets ?? []) remember(credentials(k));
|
|
151
152
|
if (settings.tokenEnv) remember(credentials(settings.tokenEnv));
|
|
@@ -240,9 +241,15 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
240
241
|
},
|
|
241
242
|
/** #4612: a graceful stop at the lane's checkpoint; false when unsupported or failed. Never destroys the sandbox. */
|
|
242
243
|
async stop(h) {
|
|
243
|
-
if (typeof transport.stop !== "function") return false;
|
|
244
|
-
try {
|
|
244
|
+
if (typeof transport.stop !== "function") { stopWhy.set(h.id, "the transport has no stop"); return false; }
|
|
245
|
+
try {
|
|
246
|
+
const ok = (await transport.stop(h.id)) === true;
|
|
247
|
+
if (ok) stopWhy.delete(h.id); else stopWhy.set(h.id, "the pool does not support stop (404/405)");
|
|
248
|
+
return ok;
|
|
249
|
+
} catch (e) { stopWhy.set(h.id, `stop failed: ${e?.message ?? e}`); return false; }
|
|
245
250
|
},
|
|
251
|
+
/** #5241: why the last `stop(h)` returned false (null when it succeeded or never ran), so a cancel can report it. */
|
|
252
|
+
stopReason: (h) => stopWhy.get(h?.id) ?? null,
|
|
246
253
|
async teardown(h) {
|
|
247
254
|
await minutesOf(h);
|
|
248
255
|
try { return (await transport.destroy(h.id)) !== false; } catch { return false; }
|
package/bin/lean/schedd.mjs
CHANGED
|
@@ -33,6 +33,12 @@
|
|
|
33
33
|
* Exit reasons (#4503): every exit logs a line: `idle, exiting`, `exiting (<signal>|uncaught: …)`, `lost lock|socket …,
|
|
34
34
|
* exiting` (checked every `lockCheckMs`: the lock no longer holds this pid, or the socket is gone; nothing it does not own
|
|
35
35
|
* is removed), then `exited (code N)`. Taking over a dead owner's lock is logged, so a SIGKILLed daemon leaves a trace.
|
|
36
|
+
* Upgrade handover (#5204): the same `lockCheckMs` tick compares `installedVersion()` (the `version` of the package.json of
|
|
37
|
+
* this install) with the version loaded at start. When the install moved (`npm i -g`, `forgedock update`) it logs
|
|
38
|
+
* `schedd: install moved v<old> → v<new>; handing over` once, runs `close()` (no admission, lanes keep running, lock and
|
|
39
|
+
* socket released), then `respawn()`: a fresh daemon from the new install when no systemd unit runs it (`Restart=always`
|
|
40
|
+
* restarts an active unit). The new daemon resumes every batch; each lane it cannot adopt is requeued with an
|
|
41
|
+
* `interrupted: upgrade vX→vY` row (orchestrate.mjs).
|
|
36
42
|
* `runBatch({argv, cwd, env, sink, keepBreaker, signal})` is injected (engine-cli `runBatch`); `sink` gets `batch(b)`, `row(r)`, `line(text)`.
|
|
37
43
|
*/
|
|
38
44
|
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
@@ -148,8 +154,10 @@ function takeLock(lock, pid, alive) {
|
|
|
148
154
|
export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(process.env.FORGEDOCK_SCHEDD_IDLE_MS) || IDLE_MS,
|
|
149
155
|
root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
|
|
150
156
|
lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
|
|
151
|
-
hostLoad = liveOverload() } = {}) {
|
|
157
|
+
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined } = {}) {
|
|
152
158
|
const p = scheddPaths(dir);
|
|
159
|
+
// #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
|
|
160
|
+
const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
|
|
153
161
|
mkdirSync(dir, { recursive: true });
|
|
154
162
|
const lock = takeLock(p.lock, pid, alive);
|
|
155
163
|
if (lock?.took) log(`schedd: took over the lock of dead pid ${lock.took} (it exited without a clean shutdown)`);
|
|
@@ -176,7 +184,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
176
184
|
const ac = new AbortController();
|
|
177
185
|
const ent = { id: null, dir: null, subs: new Set(first ? [first] : []) };
|
|
178
186
|
const emit = (m) => { for (const s of ent.subs) s(m); };
|
|
179
|
-
let started = false;
|
|
187
|
+
let started = false, endedClean = false;
|
|
180
188
|
const sink = {
|
|
181
189
|
batch: (b) => { ent.id = b.id; ent.dir = b.dir; hosted.set(b.id, ent); started = true; resolve(ent); },
|
|
182
190
|
row: (row) => emit({ type: "row", row }),
|
|
@@ -186,12 +194,12 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
186
194
|
const run = Promise.resolve().then(() => runBatch({ argv, cwd, env, sink, keepBreaker, signal: ac.signal })).then((result) => {
|
|
187
195
|
const report = ent.dir ? openBatch(root, ent.id).readReport()?.report ?? null : null;
|
|
188
196
|
emit({ type: "done", result, report });
|
|
189
|
-
if (ent.id) rehostLater(ent.id); // #4917
|
|
197
|
+
if (ent.id) { rehostLater(ent.id); endedClean = true; } // #4917
|
|
190
198
|
}, (e) => {
|
|
191
199
|
const message = e?.message ?? String(e);
|
|
192
200
|
if (e?.code === "batch.stopped") { log(`schedd: batch ${ent.id ?? argv.join(" ")} stopped (lanes keep running; resumed by the next daemon)`); if (!started) reject(new Error(message)); return; }
|
|
193
201
|
if (!started) reject(new Error(message)); else { log(`schedd: batch ${ent.id} failed: ${message}`); emit({ type: "error", message }); }
|
|
194
|
-
}).finally(() => { if (ent.id) hosted.delete(ent.id); ent.subs.clear(); runs.delete(run); touch(); });
|
|
202
|
+
}).finally(() => { if (ent.id) hosted.delete(ent.id); ent.subs.clear(); runs.delete(run); touch(); if (ent.id && endedClean) rehostUnrun(ent.id); });
|
|
195
203
|
runs.set(run, ac);
|
|
196
204
|
});
|
|
197
205
|
|
|
@@ -217,6 +225,29 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
217
225
|
rehostTimers.add(t);
|
|
218
226
|
};
|
|
219
227
|
|
|
228
|
+
// #5242: an add/requeue that landed while the runner was past its dispatch loop (still "hosted", no longer draining) is
|
|
229
|
+
// dispatched by re-hosting the batch once the run has ended. Once per distinct set of unrun entries, so an add that cannot
|
|
230
|
+
// drain (a cancel, a tripped breaker) never loops.
|
|
231
|
+
const rehostedUnrun = new Map();
|
|
232
|
+
const rehostUnrun = (id) => {
|
|
233
|
+
if (closing || hosted.has(id) || starting.has(id)) return;
|
|
234
|
+
let sig;
|
|
235
|
+
try {
|
|
236
|
+
const b = openBatch(root, id);
|
|
237
|
+
if (b.readCancel()) return;
|
|
238
|
+
const st = b.store.load();
|
|
239
|
+
if (st?.breaker && !st.breaker.transport) return;
|
|
240
|
+
sig = JSON.stringify([b.unrunAdds(), b.unrunRequeues().map((e) => e.issue ?? e)]);
|
|
241
|
+
if (!b.unrunAdds().length && !b.unrunRequeues().length) { rehostedUnrun.delete(id); return; }
|
|
242
|
+
} catch { return; }
|
|
243
|
+
if (rehostedUnrun.get(id) === sig) return;
|
|
244
|
+
rehostedUnrun.set(id, sig);
|
|
245
|
+
log(`schedd: re-hosting batch ${id} (an add or requeue arrived after its runner stopped draining)`);
|
|
246
|
+
const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
|
|
247
|
+
starting.set(id, started);
|
|
248
|
+
started.catch((e) => log(`schedd: re-host ${id} failed: ${e?.message ?? e}`)).finally(() => starting.delete(id));
|
|
249
|
+
};
|
|
250
|
+
|
|
220
251
|
/** #4775: wait for a batch start at most `admitMs`; the start itself goes on (a second host() would duplicate the batch). */
|
|
221
252
|
const bound = (p, what) => {
|
|
222
253
|
let t;
|
|
@@ -383,9 +414,18 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
383
414
|
if (!hosted.size && !conns.size && Date.now() - lastActive >= idleMs) { log("schedd: idle, exiting"); close(); }
|
|
384
415
|
}, Math.min(idleMs, 30_000));
|
|
385
416
|
idleTimer.unref?.();
|
|
417
|
+
// #5204: the version this daemon runs; an install that moves under it hands over on the next tick.
|
|
418
|
+
const versionOf = () => { try { return installedVersion?.() ?? null; } catch { return null; } };
|
|
419
|
+
const loadedVersion = versionOf();
|
|
386
420
|
// #4503: a daemon whose lock or socket was taken stops (its batches stay resumable) instead of running unreachable.
|
|
387
421
|
const lockTimer = setInterval(() => {
|
|
388
422
|
if (closing) return;
|
|
423
|
+
const now = loadedVersion ? versionOf() : null;
|
|
424
|
+
if (now && now !== loadedVersion) {
|
|
425
|
+
log(`schedd: install moved v${loadedVersion} → v${now}; handing over`);
|
|
426
|
+
close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } });
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
389
429
|
let owner = NaN;
|
|
390
430
|
try { owner = parseInt(readFileSync(p.lock, "utf8"), 10); } catch { /* gone */ }
|
|
391
431
|
if (owner !== pid) { keepSock = true; log(`schedd: lost lock (owner ${Number.isInteger(owner) ? `pid ${owner}` : "none"}), exiting`); close(); }
|
|
@@ -433,6 +473,11 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
433
473
|
return { running: true, pid, sock: p.sock, close, closed };
|
|
434
474
|
}
|
|
435
475
|
|
|
476
|
+
/** #5204: `version` of the package.json of this install (../../package.json), null when it cannot be read. */
|
|
477
|
+
export function readInstalledVersion({ file = fileURLToPath(new URL("../../package.json", import.meta.url)) } = {}) {
|
|
478
|
+
try { return String(JSON.parse(readFileSync(file, "utf8")).version ?? "") || null; } catch { return null; }
|
|
479
|
+
}
|
|
480
|
+
|
|
436
481
|
/**
|
|
437
482
|
* #4454: on SIGTERM/SIGINT/SIGHUP stop the daemon (`close()`: batch loops first, then lock and socket), then exit 128+signo,
|
|
438
483
|
* once; an uncaught exception or unhandled rejection does the same and exits 1. #4503: each logs its reason first, and the
|