forgedock 1.72.0 → 1.72.1
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/lean/admit.mjs +45 -11
- package/bin/lean/admit.test.mjs +43 -1
- package/bin/lean/effects.mjs +18 -4
- package/bin/lean/heavy.mjs +20 -6
- package/bin/lean/heavy.test.mjs +24 -3
- package/bin/lean/lean.mjs +7 -4
- package/bin/pool/agent.mjs +36 -11
- package/bin/pool/docker-dns.mjs +29 -13
- package/bin/pool/docker.mjs +2 -0
- package/package.json +1 -1
package/bin/lean/admit.mjs
CHANGED
|
@@ -35,19 +35,39 @@ export function failingRequired({ checks = [], required = [] } = {}) {
|
|
|
35
35
|
.map((c) => ({ name: String(c.name), conclusion: String(c.conclusion ?? c.state), url: c.url ?? c.html_url ?? "", summary: String(c.summary ?? "").slice(0, 600) }));
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
38
|
+
const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
39
|
+
/** #6232: `needle` as a whole token of `text` (not inside a longer word, name or path): `test` does not match `latest` or `tests/foo`. Both lowercased by the caller. */
|
|
40
|
+
export const hasToken = (text, needle) => Boolean(needle) && new RegExp(`(?<![a-z0-9_./-])${esc(needle)}(?![a-z0-9_-]|\\.[a-z0-9])`).test(text);
|
|
41
|
+
const BASE_RED_LABEL = /^(base[-. _]?red|fix(es)?[-: ]base[-. _]?red)$/i;
|
|
42
|
+
const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* True when the issue is the fix for (or about) the failing check, not a bystander. `issue`: a string (title and body) or
|
|
46
|
+
* {text, contractText, labels, linkedBaseRed}. It is the fix when any of:
|
|
47
|
+
* - its text names the failing check as a whole token (substrings do not count: `test` is not in `latest`),
|
|
48
|
+
* - its text, frozen contract or deliverables name a file (or sit in the directory of a file) the check's output names,
|
|
49
|
+
* - it is labelled base-red, or linked as the base-red cause (a trusted FORGE:BASE_RED comment).
|
|
50
|
+
*/
|
|
51
|
+
export function touchedByIssue(fail, issue) {
|
|
52
|
+
const o = typeof issue === "string" || issue == null ? { text: issue } : issue;
|
|
53
|
+
if ((o.labels ?? []).some((l) => BASE_RED_LABEL.test(String(l?.name ?? l)))) return true;
|
|
54
|
+
if (o.linkedBaseRed) return true;
|
|
55
|
+
const text = String(o.text ?? "").toLowerCase(), contract = String(o.contractText ?? "").toLowerCase();
|
|
56
|
+
if (!text && !contract) return false;
|
|
57
|
+
if (hasToken(text, String(fail.name).toLowerCase())) return true;
|
|
43
58
|
const { src, tests } = baseRedPaths([{ command: "", output: fail.summary }]);
|
|
44
|
-
return [...src, ...tests].
|
|
59
|
+
return [...src, ...tests].map((p) => p.toLowerCase()).some((p) => {
|
|
60
|
+
if (hasToken(text, p) || hasToken(contract, p)) return true;
|
|
61
|
+
const d = dirOf(p); // the check's scope: a contract file in the same directory is the fix's territory
|
|
62
|
+
return d.includes("/") && (text.includes(`${d}/`) || contract.includes(`${d}/`));
|
|
63
|
+
});
|
|
45
64
|
}
|
|
46
65
|
|
|
47
66
|
/** Base health verdict: red only for a failing required check this issue does not touch. */
|
|
48
|
-
export function baseHealth({ checks, required, issueText } = {}) {
|
|
67
|
+
export function baseHealth({ checks, required, issueText, issue } = {}) {
|
|
49
68
|
const failing = failingRequired({ checks, required });
|
|
50
|
-
const
|
|
69
|
+
const who = issue ?? issueText;
|
|
70
|
+
const foreign = failing.filter((f) => !touchedByIssue(f, who));
|
|
51
71
|
return { red: foreign.length > 0, failing: foreign, touched: failing.filter((f) => !foreign.includes(f)) };
|
|
52
72
|
}
|
|
53
73
|
|
|
@@ -91,9 +111,23 @@ export function inputOf({ iss, comments = [], trusted = () => true, engineVersio
|
|
|
91
111
|
return computeInputHash({ title: iss?.title ?? "", body: iss?.body ?? "", labels: [], decisions, engineVersion, contractHash: frozenContractHash(comments, trusted) });
|
|
92
112
|
}
|
|
93
113
|
|
|
94
|
-
/**
|
|
95
|
-
|
|
96
|
-
|
|
114
|
+
/**
|
|
115
|
+
* #6231: codes a repeat cannot help or that are transient/infrastructure: the engine's own environment recovery, a human block, a deferral,
|
|
116
|
+
* the engine, the sandbox, the backend login, the network and gh. A park of these is never stamped and never stops admission or counts as a
|
|
117
|
+
* repeat: after the operator fixes the cause a rerun must be admitted. The ONE list, used by the stamp writer, the stop reader and lean.mjs.
|
|
118
|
+
*/
|
|
119
|
+
export const NON_STOPPABLE_CODES = Object.freeze(new Set([
|
|
120
|
+
...ENV_ENGINE_OWNED_CODES, OUTCOME_CODES.BUILDER_BLOCKED, OUTCOME_CODES.FAILURE_REPEATED, OUTCOME_CODES.BASE_RED, OUTCOME_CODES.BASE_CONFLICT,
|
|
121
|
+
OUTCOME_CODES.ENGINE_ERROR, OUTCOME_CODES.ENV_SETUP_FAILED, OUTCOME_CODES.ENV_LANE_LIMIT, OUTCOME_CODES.ENV_ENGINE_SKEW,
|
|
122
|
+
OUTCOME_CODES.BACKEND_AUTH, OUTCOME_CODES.BACKEND_CLI_FAILED, OUTCOME_CODES.QUOTA_EXHAUSTED, OUTCOME_CODES.RATE_LIMITED, OUTCOME_CODES.HOST_BUSY,
|
|
123
|
+
OUTCOME_CODES.GH_UNAVAILABLE, OUTCOME_CODES.GH_AUTH, OUTCOME_CODES.NET_TRANSIENT, OUTCOME_CODES.MERGE_TRANSIENT, OUTCOME_CODES.PUSH_TRANSIENT,
|
|
124
|
+
OUTCOME_CODES.RUN_INTERRUPTED, OUTCOME_CODES.LEASE_HELD, OUTCOME_CODES.CLI_IDLE, OUTCOME_CODES.CLI_TIMEOUT, OUTCOME_CODES.CLI_HOST_KILLED,
|
|
125
|
+
OUTCOME_CODES.PATH_SWITCH_CONFLICT,
|
|
126
|
+
]));
|
|
127
|
+
/** Families that are transient or infrastructure by prefix: sandbox.*, lane.*, engine.*, infra.*, backend.*, net.*, gh.*, and deferred/dependency holds. */
|
|
128
|
+
const NON_STOPPABLE_PREFIX = /^(sandbox|lane|engine|infra|backend|net|gh|dependency|pool|deferred)[.:_]/;
|
|
129
|
+
export const isNonStoppable = (code) => NON_STOPPABLE_CODES.has(code) || NON_STOPPABLE_PREFIX.test(String(code ?? ""));
|
|
130
|
+
export const stampable = (code) => Boolean(code) && !isNonStoppable(code);
|
|
97
131
|
|
|
98
132
|
/**
|
|
99
133
|
* The failure-fingerprint stop: the newest trusted NEEDS_HUMAN/PARKED comment (after the last trusted FORGE:DECISION) carries a stamp whose base head and
|
package/bin/lean/admit.test.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { test } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { failingRequired, baseHealth, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, inputOf, fingerprintStop, admitEvent, fetchBaseChecks } from "./admit.mjs";
|
|
5
|
+
import { failingRequired, baseHealth, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, isNonStoppable, NON_STOPPABLE_CODES, inputOf, fingerprintStop, admitEvent, fetchBaseChecks } from "./admit.mjs";
|
|
6
6
|
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
7
7
|
|
|
8
8
|
const run = (name, conclusion, extra = {}) => ({ name, conclusion, url: `https://x/${name}`, completed_at: "2026-11-28T10:00:00Z", ...extra });
|
|
@@ -76,3 +76,45 @@ test("inputOf ignores labels, follows title/body/decisions/contract", () => {
|
|
|
76
76
|
test("admitEvent always records zero builder spend", () => {
|
|
77
77
|
assert.equal(admitEvent({ outcome: "base_red", code: "base.red" }).builder_spend_usd, 0);
|
|
78
78
|
});
|
|
79
|
+
|
|
80
|
+
// #6231: one non-stoppable list for the stamp writer, the stop reader and lean.mjs.
|
|
81
|
+
test("transient and infrastructure codes are never stamped and never stop admission (#6231)", () => {
|
|
82
|
+
const input = "a".repeat(16), base = "b".repeat(40);
|
|
83
|
+
for (const code of ["engine.error", "sandbox.transient", "sandbox.lost", "sandbox.auth", "backend.auth", "env.setup_failed", "gh.unavailable", "net.transient", "lane.mismatch", "lease.held", "rate_limited", "base.red"]) {
|
|
84
|
+
assert.ok(isNonStoppable(code), code);
|
|
85
|
+
assert.ok(!stampable(code), code);
|
|
86
|
+
assert.equal(fingerprintStop({ comments: [stamped(code, base, input)], base, input }), null, code); // an old stamp of such a code (written by an earlier engine) never stops either
|
|
87
|
+
}
|
|
88
|
+
assert.ok(NON_STOPPABLE_CODES.has("engine.error"));
|
|
89
|
+
for (const code of ["ci.red", "review.failed", "build.acceptance_failed"]) assert.ok(stampable(code) && !isNonStoppable(code), code);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// #6232: whole-token check names, contract/deliverable files, label or link.
|
|
93
|
+
const redRow = [{ name: "test", conclusion: "failure", summary: "FAIL bin/lean/foo.test.mjs\n at bin/lean/foo.mjs:3" }];
|
|
94
|
+
const req = ["test"];
|
|
95
|
+
test("base.red: a check name matches as a whole token, not a substring (#6232)", () => {
|
|
96
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issueText: "handle the latest contest of attestation" }).red, true);
|
|
97
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issueText: "the test check is red" }).red, false);
|
|
98
|
+
});
|
|
99
|
+
test("base.red: an issue whose frozen contract touches the failing files, or is labelled or linked as the fix, is admitted (#6232)", () => {
|
|
100
|
+
const issue = (x) => ({ text: "refactor the planner", ...x });
|
|
101
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({}) }).red, true); // a bystander is still deferred
|
|
102
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ deliverables: ["bin/lean/foo.mjs"] }) }) }).red, false);
|
|
103
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ files: ["bin/lean/other.mjs"] }) }) }).red, false); // same directory: the check's scope
|
|
104
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ contractText: JSON.stringify({ files: ["docs/readme.md"] }) }) }).red, true);
|
|
105
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ labels: [{ name: "base-red" }] }) }).red, false);
|
|
106
|
+
assert.equal(baseHealth({ checks: redRow, required: req, issue: issue({ linkedBaseRed: true }) }).red, false);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// #6233: only the documented logged-out signal is a login failure; anything else unknown fails open with a warning.
|
|
110
|
+
import { classifyAuthStatus } from "./effects.mjs";
|
|
111
|
+
test("classifyAuthStatus: logged-out is ok:false, success ok:true, other non-zero or no run is unknown (#6233)", () => {
|
|
112
|
+
assert.equal(classifyAuthStatus({ status: 0, out: '{"loggedIn": true}' }).ok, true);
|
|
113
|
+
assert.equal(classifyAuthStatus({ status: 1, out: '{"loggedIn": false}' }).ok, false);
|
|
114
|
+
assert.equal(classifyAuthStatus({ status: 1, out: "Not logged in. Run claude login" }).ok, false);
|
|
115
|
+
const other = classifyAuthStatus({ status: 2, out: "unexpected flag" });
|
|
116
|
+
assert.equal(other.ok, null); assert.match(other.warning, /exited 2/);
|
|
117
|
+
assert.equal(classifyAuthStatus({ status: 1, out: "ECONNREFUSED proxy" }).ok, null); // a non-logged-out failure is not backend.auth
|
|
118
|
+
assert.equal(classifyAuthStatus({ error: Object.assign(new Error("x"), { code: "ENOENT" }), status: null }).ok, null);
|
|
119
|
+
assert.equal(classifyAuthStatus({ status: null }).ok, null);
|
|
120
|
+
});
|
package/bin/lean/effects.mjs
CHANGED
|
@@ -526,6 +526,15 @@ export function makeGhCache({ root = null, tmp = tmpdir() } = {}) {
|
|
|
526
526
|
};
|
|
527
527
|
}
|
|
528
528
|
|
|
529
|
+
/** #6233: classify a `claude auth status` result. Only the documented logged-out signal is `ok:false`; everything else that is not success is unknown. */
|
|
530
|
+
export function classifyAuthStatus({ error = null, status = null, out = "" } = {}) {
|
|
531
|
+
if (error || status === null) return { ok: null, warning: `claude auth status did not run (${String(error?.code ?? error?.message ?? "timeout or signal").slice(0, 80)})` };
|
|
532
|
+
const text = String(out ?? "");
|
|
533
|
+
if (/"loggedIn"\s*:\s*false/i.test(text) || (status === 1 && /\bnot logged in\b/i.test(text))) return { ok: false };
|
|
534
|
+
if (status === 0) return { ok: true };
|
|
535
|
+
return { ok: null, warning: `claude auth status exited ${status} without the logged-out signal; treated as unknown, not as a login failure: ${text.trim().split("\n")[0].slice(0, 120)}` };
|
|
536
|
+
}
|
|
537
|
+
|
|
529
538
|
export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
530
539
|
const base = makeIo();
|
|
531
540
|
const seqLeaseIo = makeSequenceLeaseIo(); // #5340: one instance: sequence leases, surface leases and declarations
|
|
@@ -543,11 +552,16 @@ export function makeLeanIo({ repo, subagentModel = readSubagentModel() }) {
|
|
|
543
552
|
gh: run("gh"), git: run("git"), docker: run("docker"), killGroup: async (pid, marker) => killLedgerPid(pid, marker), ledger: (opts) => makeLedger(opts), runTmp: makeRunTmp(), host: makeHostProbe(), heavy: guardHeavyDisk(makeHeavyIo({ host: makeHostProbe() }), { host: makeHostProbe(), minFreeGb: async () => (await import("../gc.mjs")).readHygiene(process.cwd()).min_free_gb, gc: async () => { const g = await import("../gc.mjs"); return g.runOwnedGc({ probes: g.makeGcProbes({ cwd: process.cwd() }), hygiene: g.readHygiene(process.cwd()), budgetMs: 60000 }); } }), projector: makeProjector({ gh: base.gh }, { repo }), runner: makeLeanRunner({ subagentModel }), waitCiGreen: base.waitCiGreen,
|
|
544
553
|
/** Shared dependency cache (#4220): the repo's own package manager, argv only, bounded by the cache's timeout. */
|
|
545
554
|
deps: makeDepCache({ exec: async (cmd, args, { cwd, env, timeoutMs } = {}) => String((await pexec(cmd, args, { cwd, env: { ...process.env, ...(env ?? {}) }, timeout: timeoutMs ?? 0, maxBuffer: 100 * 1024 * 1024 })).stdout) }),
|
|
546
|
-
/**
|
|
547
|
-
|
|
555
|
+
/**
|
|
556
|
+
* #6206/#6233: the cheap login probe (`claude auth status`, no model call) the admit probe runs before any builder session. It runs with the
|
|
557
|
+
* lane's own env (`env`: CLAUDE_CONFIG_DIR, API-key vars), so a pinned-profile or API-key lane is probed as itself. `ok` false only for the
|
|
558
|
+
* documented logged-out signal (exit 1 with "Not logged in" or loggedIn:false); any other non-zero exit, a missing binary or a timeout is unknown
|
|
559
|
+
* (`ok` null, `warning` set): the caller fails open and records the warning.
|
|
560
|
+
*/
|
|
561
|
+
async claudeAuthProbe({ env = null } = {}) {
|
|
548
562
|
const { spawnSync } = await import("node:child_process");
|
|
549
|
-
const r = spawnSync("claude", ["auth", "status"], { timeout: 15000, stdio: "ignore" });
|
|
550
|
-
return r.error
|
|
563
|
+
const r = spawnSync("claude", ["auth", "status"], { timeout: 15000, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ...(env ?? {}) } });
|
|
564
|
+
return classifyAuthStatus({ error: r.error, status: r.status, out: `${r.stdout ?? ""}\n${r.stderr ?? ""}` });
|
|
551
565
|
},
|
|
552
566
|
/** #6206: the admit probe's own read of the required checks (a separate seam, so the precheck's and the merge policy's reads are unchanged). */
|
|
553
567
|
async baseRequiredChecks(lane) { return requiredChecksFor({ gh: run("gh"), repo, lane }); },
|
package/bin/lean/heavy.mjs
CHANGED
|
@@ -30,6 +30,8 @@ import { lowerPriority } from "./hostload.mjs";
|
|
|
30
30
|
|
|
31
31
|
export const HEAVY_DEFAULTS = Object.freeze({ enabled: true, max: null, step_mem_mb: 2048, reserve_mb: 1024, ramp_s: 60, max_wait_s: 1800 });
|
|
32
32
|
export const HEAVY_POLL_MS = 2000;
|
|
33
|
+
export const HEAVY_ERROR_BUDGET_MS = 120000; // #6235: how long an erroring or unreachable agent is retried before the step is deferred
|
|
34
|
+
export const HEAVY_DEFER_CODE = 75; // EX_TEMPFAIL: the step did not run because no heavy token could be leased
|
|
33
35
|
const LOCK_WAIT_MS = 2000, EMPTY_LOCK_STALE_MS = 5000;
|
|
34
36
|
|
|
35
37
|
const PMS = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
@@ -255,26 +257,34 @@ export async function acquireHeavy(h, entry = {}, { pollMs = HEAVY_POLL_MS, slee
|
|
|
255
257
|
|
|
256
258
|
/**
|
|
257
259
|
* #6047: remote-token backend, chosen when CS_HEAVY_BASE (the pool agent's per-sandbox /heavy route) is set. Acquire polls
|
|
258
|
-
* while the agent denies
|
|
259
|
-
*
|
|
260
|
+
* while the agent denies and renews the lease on a timer; release is best effort. #6235: fails CLOSED. Under elastic accounting a
|
|
261
|
+
* lane is charged only its base, so a step that runs without a token can overcommit host memory. An unreachable or erroring agent is
|
|
262
|
+
* retried with backoff for `errorBudgetMs`; that budget, or a wait past `maxWaitMs`, returns `{denied: true, reason}` and the
|
|
263
|
+
* caller defers the step (it does not run). `fetchFn` returns {status, json()}.
|
|
260
264
|
*/
|
|
261
|
-
export async function acquireRemote({ base, credToken = "", fetchFn = (u, o) => fetch(u, o), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), pollMs = 5000, renewMs = 60000, maxWaitMs = HEAVY_DEFAULTS.max_wait_s * 1000, setTimer = setInterval, clearTimer = clearInterval } = {}) {
|
|
265
|
+
export async function acquireRemote({ base, credToken = "", fetchFn = (u, o) => fetch(u, o), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), pollMs = 5000, renewMs = 60000, maxWaitMs = HEAVY_DEFAULTS.max_wait_s * 1000, errorBudgetMs = HEAVY_ERROR_BUDGET_MS, setTimer = setInterval, clearTimer = clearInterval } = {}) {
|
|
262
266
|
const call = async (action, body) => {
|
|
263
267
|
const r = await fetchFn(`${base}/${action}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${credToken}` }, body: JSON.stringify(body ?? {}), signal: AbortSignal.timeout(10000) });
|
|
264
268
|
if (r.status !== 200) throw new Error(`heavy ${action}: HTTP ${r.status}`);
|
|
265
269
|
return r.json();
|
|
266
270
|
};
|
|
267
271
|
const t0 = now(), open = { waitMs: 0, queued: 0, holders: 1, release: () => {} };
|
|
272
|
+
let errSince = null, errN = 0;
|
|
268
273
|
for (;;) {
|
|
269
274
|
let r;
|
|
270
|
-
try { r = await call("acquire");
|
|
275
|
+
try { r = await call("acquire"); errSince = null; errN = 0; } catch (e) {
|
|
276
|
+
errSince ??= now();
|
|
277
|
+
if (now() - errSince >= errorBudgetMs || now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, denied: true, reason: `heavy gate unavailable: ${e?.message ?? e}` };
|
|
278
|
+
await sleep(Math.min(15000, 1000 * 2 ** Math.min(errN++, 4)));
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
271
281
|
if (r?.granted && r.token) {
|
|
272
282
|
const token = r.token, timer = setTimer(() => { call("renew", { token }).catch(() => {}); }, renewMs);
|
|
273
283
|
timer?.unref?.();
|
|
274
284
|
let released = false;
|
|
275
285
|
return { ...open, waitMs: now() - t0, token, release: () => { if (released) return; released = true; clearTimer(timer); call("release", { token }).catch(() => {}); } };
|
|
276
286
|
}
|
|
277
|
-
if (now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0,
|
|
287
|
+
if (now() - t0 >= maxWaitMs) return { ...open, waitMs: now() - t0, denied: true, timedOut: true, reason: `no heavy token after ${Math.round((now() - t0) / 1000)}s` };
|
|
278
288
|
await sleep(Math.min(pollMs, Math.max(1, Number(r?.retry_after_s) * 1000 || pollMs)));
|
|
279
289
|
}
|
|
280
290
|
}
|
|
@@ -427,9 +437,13 @@ export async function runWrapped(argv, { env: env0 = process.env, open = openHea
|
|
|
427
437
|
const hostP = host ?? defaultHost();
|
|
428
438
|
const priority = Number.isFinite(Number(env.FORGE_LANE_PRIORITY)) && String(env.FORGE_LANE_PRIORITY).trim() !== "" ? Number(env.FORGE_LANE_PRIORITY) : DEFAULT_PRIORITY;
|
|
429
439
|
const phase = env.FORGE_LANE_PHASE || "step";
|
|
430
|
-
const useRemote = Boolean(env.CS_HEAVY_BASE); // #6047: the pool agent's token semaphore
|
|
440
|
+
const useRemote = Boolean(env.CS_HEAVY_BASE); // #6047: the pool agent's token semaphore (#6235: fail closed), else the local file semaphore
|
|
431
441
|
const g = useRemote ? await remote({ base: env.CS_HEAVY_BASE, credToken: env.CS_CRED_TOKEN ?? "", maxWaitMs: c.max_wait_s * 1000 })
|
|
432
442
|
: await acquireHeavy(open(env.FORGEDOCK_SCHED_DIR || schedDir(env), { env, host: hostP }), { issue: Number(env.FORGE_LANE_ISSUE) || null, phase, priority, mb: c.step_mem_mb });
|
|
443
|
+
if (g.denied && env.FORGE_HEAVY_FAIL_OPEN !== "1") { // #6235: never run a heavy step ungated under elastic accounting; the caller retries or defers
|
|
444
|
+
process.stderr.write(`forgedock heavy: ${name} deferred, ${g.reason ?? "no heavy token"} (exit ${HEAVY_DEFER_CODE}; FORGE_HEAVY_FAIL_OPEN=1 runs it ungated)\n`);
|
|
445
|
+
return { code: HEAVY_DEFER_CODE, signal: null };
|
|
446
|
+
}
|
|
433
447
|
if (env.FORGE_HEAVY_WAITS) { try { appendFileSync(env.FORGE_HEAVY_WAITS, JSON.stringify({ phase, name, waitMs: g.waitMs, queued: g.queued }) + "\n"); } catch { /* metrics are best effort */ } }
|
|
434
448
|
let cores = 1; try { cores = hostP.cores() || 1; } catch { /* 1 */ }
|
|
435
449
|
cores = quotaCores({ cores, read, env }); // #6047: the container's CPU quota, never the VM
|
package/bin/lean/heavy.test.mjs
CHANGED
|
@@ -504,9 +504,30 @@ describe("remote token backend (#6047)", () => {
|
|
|
504
504
|
const calls = [], g = await acquireRemote(opts(calls, [resp(200, { granted: false, retry_after_s: 1 }), resp(200, { granted: false }), resp(200, { granted: true, token: "t2" })]));
|
|
505
505
|
assert.equal(g.token, "t2"); assert.equal(calls.filter((c) => c === "acquire").length, 3);
|
|
506
506
|
});
|
|
507
|
-
it("fails
|
|
508
|
-
|
|
509
|
-
|
|
507
|
+
it("fails closed (#6235): an unreachable or erroring agent is retried with backoff, then denies", async () => {
|
|
508
|
+
let t = 0; const clock = { now: () => t, sleep: async (ms) => { t += ms; } };
|
|
509
|
+
const calls = [], g = await acquireRemote({ ...opts(calls, [new Error("ECONNREFUSED")]), ...clock, errorBudgetMs: 20000, fetchFn: async (u) => { calls.push(u); throw new Error("ECONNREFUSED"); } });
|
|
510
|
+
assert.equal(g.denied, true); assert.ok(!g.failOpen); assert.match(g.reason, /ECONNREFUSED/); assert.ok(calls.length > 2, "retried before giving up");
|
|
511
|
+
const h = await acquireRemote({ ...opts([], [resp(500, {})]), ...clock, errorBudgetMs: 1000, fetchFn: async () => resp(500, {}) });
|
|
512
|
+
assert.equal(h.denied, true);
|
|
513
|
+
});
|
|
514
|
+
it("a transient agent error recovers into a grant", async () => {
|
|
515
|
+
const calls = [], g = await acquireRemote(opts(calls, [new Error("reset"), resp(502, {}), resp(200, { granted: true, token: "t3" })]));
|
|
516
|
+
assert.equal(g.token, "t3"); assert.ok(!g.denied);
|
|
517
|
+
});
|
|
518
|
+
it("a wait past maxWaitMs denies instead of running the step", async () => {
|
|
519
|
+
let t = 0;
|
|
520
|
+
const g = await acquireRemote({ ...opts([], []), now: () => t, sleep: async (ms) => { t += ms; }, maxWaitMs: 3000, fetchFn: async () => resp(200, { granted: false, retry_after_s: 1 }) });
|
|
521
|
+
assert.equal(g.denied, true); assert.equal(g.timedOut, true);
|
|
522
|
+
});
|
|
523
|
+
it("runWrapped defers (exit 75) a denied step and never runs it; FORGE_HEAVY_FAIL_OPEN=1 is the explicit escape", async () => {
|
|
524
|
+
const ran = [], run = async (cmd, args, env) => { ran.push(env); return { code: 0, signal: null }; };
|
|
525
|
+
const remote = async () => ({ waitMs: 0, holders: 1, denied: true, reason: "heavy gate unavailable: x", release() {} });
|
|
526
|
+
const host = { memAvailableMb: () => 12000, cores: () => 4 }, dir = tmpDir("heavy-rw-");
|
|
527
|
+
const r = await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { CS_HEAVY_BASE: "http://h/x", FORGEDOCK_SCHED_DIR: dir }, run, remote, host, read: () => { throw new Error("none"); } });
|
|
528
|
+
assert.equal(r.code, 75); assert.equal(ran.length, 0);
|
|
529
|
+
const o = await runWrapped(["run", "--name", "pnpm", "--", "pnpm", "install"], { env: { CS_HEAVY_BASE: "http://h/x", FORGEDOCK_SCHED_DIR: dir, FORGE_HEAVY_FAIL_OPEN: "1" }, run, remote, host, read: () => { throw new Error("none"); } });
|
|
530
|
+
assert.equal(o.code, 0); assert.equal(ran.length, 1);
|
|
510
531
|
});
|
|
511
532
|
it("runWrapped uses the remote backend only when CS_HEAVY_BASE is set; otherwise the local file semaphore", async () => {
|
|
512
533
|
const ran = [], run = async (cmd, args, env) => { ran.push(env); return { code: 0, signal: null }; };
|
package/bin/lean/lean.mjs
CHANGED
|
@@ -31,7 +31,7 @@ import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilte
|
|
|
31
31
|
import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId, contractKey } from "./statuscomment.mjs";
|
|
32
32
|
import { decidePost } from "./commentstate.mjs"; // #5979
|
|
33
33
|
import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs"; // #5979
|
|
34
|
-
import { baseHealth, fetchBaseChecks, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, inputOf, fingerprintStop, stopReason, admitEvent } from "./admit.mjs"; // #6206
|
|
34
|
+
import { baseHealth, fetchBaseChecks, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, isNonStoppable, inputOf, fingerprintStop, stopReason, admitEvent } from "./admit.mjs"; // #6206
|
|
35
35
|
import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
|
|
36
36
|
import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
|
|
37
37
|
import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
|
|
@@ -899,7 +899,7 @@ export async function runCore(o) {
|
|
|
899
899
|
}
|
|
900
900
|
// #5979: the second identical failure (same code and normalised detail as an earlier NEEDS_HUMAN/PARKED of this issue) parks with one summary, no recovery
|
|
901
901
|
const sig = repeatSignature(code, why);
|
|
902
|
-
const stoppable = code
|
|
902
|
+
const stoppable = !isNonStoppable(code); // #6231: the one non-stoppable list (admit.mjs)
|
|
903
903
|
const identical = stoppable ? countIdentical(allComments(), sig, (c) => c?.__mine === true || isTrustedIssueComment(c)) + 1 : 1;
|
|
904
904
|
if (shouldPark(identical)) {
|
|
905
905
|
try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig: `${sig}${await admitStamp(code)}` })); } catch (e) { labelFailed("comment", e); }
|
|
@@ -2363,7 +2363,9 @@ export async function runCore(o) {
|
|
|
2363
2363
|
try { required = (await io.baseRequiredChecks(lane)) ?? []; } catch { /* unreadable: no evidence */ }
|
|
2364
2364
|
if (required.length) { try { rows = await fetchBaseChecks({ gh: ghc, repo, sha: head }); } catch { rows = null; } }
|
|
2365
2365
|
if (rows) {
|
|
2366
|
-
const
|
|
2366
|
+
const cs = allComments().filter(trustedC);
|
|
2367
|
+
const contractText = cs.filter((c) => String(c?.body ?? "").startsWith("<!-- FORGE:CONTRACT -->")).map((c) => parseContractComment(String(c.body))?.text ?? "").pop() ?? "";
|
|
2368
|
+
const h = baseHealth({ checks: rows, required, issue: { text: `${iss?.title ?? ""}\n${iss?.body ?? ""}`, contractText, labels: iss?.labels ?? [], linkedBaseRed: cs.some((c) => /<!--\s*FORGE:BASE_RED\b/.test(String(c?.body ?? ""))) } }); // #6232: whole-token name, contract files, label or link
|
|
2367
2369
|
if (h.red) {
|
|
2368
2370
|
const key = `base.red ${base}@${head.slice(0, 12)}`;
|
|
2369
2371
|
if (!hasAdmitComment(allComments(), key)) { try { await post("FORGE:ADMIT_PROBE", baseRedComment({ base, sha: head, failing: h.failing })); } catch (e) { T.anomalies.push(`Admit probe comment not posted: ${String(e?.message ?? e).slice(0, 160)}`); } }
|
|
@@ -2375,7 +2377,8 @@ export async function runCore(o) {
|
|
|
2375
2377
|
}
|
|
2376
2378
|
}
|
|
2377
2379
|
if (io.claudeAuthProbe && !smartRotator && !sandboxCred) { // 2. environment: the claude login answers (`claude auth status`, no model call)
|
|
2378
|
-
let a = null; try { a = await io.claudeAuthProbe({}); } catch { /* no verdict */ }
|
|
2380
|
+
let a = null; try { a = await io.claudeAuthProbe({ env: { ...(io.env ?? process.env) } }); } catch { /* no verdict */ } // #6233: the lane's own env (CLAUDE_CONFIG_DIR, API key)
|
|
2381
|
+
if (a?.warning) T.anomalies.push(`Admit probe: ${a.warning}`); // unknown verdict: fail open, record it
|
|
2379
2382
|
if (a && a.ok === false) {
|
|
2380
2383
|
const detail = "claude CLI login does not answer (expired or invalid); deferred before any builder session until the login is fixed";
|
|
2381
2384
|
await rec({ outcome: "env_auth", code: OUTCOME_CODES.BACKEND_AUTH, detail });
|
package/bin/pool/agent.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatS
|
|
|
10
10
|
import { basename, dirname, join } from "node:path";
|
|
11
11
|
import { cpus, hostname } from "node:os";
|
|
12
12
|
import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
13
|
-
import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs";
|
|
13
|
+
import { repoRoot, versionOf, laneImageTag, laneBuildArgs, cmpVersion } from "./version.mjs";
|
|
14
14
|
import { provideLaneImage, pullVariantImage, withIpv4Fallback, fetchLaneDigest } from "./lane-image.mjs";
|
|
15
15
|
import { ensureDaemonDns } from "./docker-dns.mjs";
|
|
16
16
|
import { jsonStore } from "./store.mjs";
|
|
@@ -184,8 +184,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
184
184
|
const agentId = String(cfg.agent_id ?? cfg.name ?? hostname()).toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
|
|
185
185
|
const AGENT = agentLabel(agentId);
|
|
186
186
|
const OWN = [LABEL, AGENT];
|
|
187
|
-
// #6195: a dockerd DNS failure triggers a daemon.json dns repair;
|
|
188
|
-
|
|
187
|
+
// #6195/#6234: a dockerd DNS failure triggers a daemon.json dns repair. Admission is held across the idle check and the restart; the restart runs only with no sandbox and no container at all (co-tenants included) on the daemon. Lane containers use per-container --dns (netArgs).
|
|
188
|
+
let dnsHold = 0;
|
|
189
|
+
const noOtherContainers = async () => { if (typeof docker.listRunning !== "function") return false; try { return (await docker.listRunning()).length === 0; } catch { return false; } };
|
|
190
|
+
const pinOpts = { ensureDns: () => ensureDaemonDns({ hold: () => { dnsHold++; return () => { dnsHold--; }; }, idle: async () => activeRecs().length === 0 && await noOtherContainers() && activeRecs().length === 0, restart: () => run("systemctl", ["restart", "docker"], { timeout: 120000 }), log }) };
|
|
189
191
|
/** Images a sandbox may need are pulled ahead of time, never inside a launch request (which has a short timeout). */
|
|
190
192
|
async function prepullImages() {
|
|
191
193
|
if (await docker.hasImage?.(dindImage)) { prepull.error = null; return; }
|
|
@@ -347,8 +349,28 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
347
349
|
const mean = (k) => us.reduce((a, u) => a + u[k] / u.samples, 0) / us.length;
|
|
348
350
|
return { cpus: Math.max(fl.cpus, mean("cpu_sum")), mem: Math.max(fl.mem, mean("mem_sum")) };
|
|
349
351
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
+
// #6235: only a lane whose image carries the remote heavy backend (`remote`) is charged the elastic base: its heavy steps lease tokens.
|
|
353
|
+
// Any other lane (a pre-1.72 image, an unlabelled image, a record from before this field) gates nothing, so it is charged what it asked for.
|
|
354
|
+
const charge = (cpus, mem, base = elastic() ? elasticBase() : null, remote = false) => (base && remote ? { cpus: Math.min(cpus, base.cpus), mem: Math.min(mem, base.mem) } : { cpus, mem });
|
|
355
|
+
const HEAVY_REMOTE_MIN = "1.72.0"; // first engine version whose bin/lean/heavy.mjs speaks the pool agent's /heavy route (#6047, default #6204)
|
|
356
|
+
/** #6235: does this lane image carry the remote heavy backend? Read its version label (derived tools/project images inherit it); unknown fails closed. */
|
|
357
|
+
const heavyCapCache = new Map(); // image -> {at, v}: launches are frequent, the label is not
|
|
358
|
+
async function laneHasRemoteHeavy(img) {
|
|
359
|
+
const hit = heavyCapCache.get(img);
|
|
360
|
+
if (hit && now() - hit.at < 60000) return hit.v;
|
|
361
|
+
const v = await laneHasRemoteHeavyNow(img);
|
|
362
|
+
heavyCapCache.set(img, { at: now(), v });
|
|
363
|
+
return v;
|
|
364
|
+
}
|
|
365
|
+
async function laneHasRemoteHeavyNow(img) {
|
|
366
|
+
try {
|
|
367
|
+
const v = String((await docker.imageLabel?.(img, "org.opencontainers.image.version")) ?? "").trim();
|
|
368
|
+
const c = cmpVersion(v, HEAVY_REMOTE_MIN);
|
|
369
|
+
if (c === null) { log.warn?.(`lane image ${img} has no engine version label; charging its lanes worst-case`); return false; }
|
|
370
|
+
return c >= 0;
|
|
371
|
+
} catch { return false; }
|
|
372
|
+
}
|
|
373
|
+
const baseUse = () => { const b = elastic() ? elasticBase() : null; return activeRecs().reduce((a, r) => { const c = charge(r.cpus, r.mem_gb, b, r.heavyRemote === true); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); };
|
|
352
374
|
/** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
|
|
353
375
|
const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
|
|
354
376
|
/** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
|
|
@@ -360,6 +382,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
360
382
|
const held = heavyHeld(), mine = Object.entries(heavyTokens()).find(([, t]) => t.sandbox === r.id);
|
|
361
383
|
const ttl = Math.round(heavyTtlMs() / 1000);
|
|
362
384
|
if (mine) { mine[1].refs = (mine[1].refs ?? 1) + 1; mine[1].expires = now() + heavyTtlMs(); store.save(); return { status: 200, body: { granted: true, token: mine[0], ttl_s: ttl } }; }
|
|
385
|
+
const hm = hostMemView(); // #5967/#6235: below the floor no NEW lease is granted (a lane already holding one keeps it above), so heavy work stops before the host OOMs
|
|
386
|
+
if (hm.host_mem_low) return { status: 200, body: { granted: false, retry_after_s: cfg.host_mem_retry_after_s ?? 30, reason: "host_mem", host_mem_free_gb: hm.host_mem_free_gb, floor_gb: hm.host_mem_floor_gb, held: held.n } };
|
|
363
387
|
const est = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }), d = heavyDefault();
|
|
364
388
|
const w = { cpus: Math.max(d.cpus, est.cpus - r.cpus), mem: Math.max(d.mem, est.mem - r.mem_gb) };
|
|
365
389
|
const e = effectiveCapacity(), b = baseUse(), live_ = live(cfg), ram = Number.isFinite(live_?.mem_available_gb) ? live_.mem_available_gb : Infinity;
|
|
@@ -383,7 +407,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
383
407
|
const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
|
|
384
408
|
return { elastic_lanes: true, elastic_base: { cpus: r2(elasticBase().cpus), mem_gb: r2(elasticBase().mem) }, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
|
|
385
409
|
}
|
|
386
|
-
const sumRecs = (rs) => { const b = elastic() ? elasticBase() : null; return rs.reduce((a, s) => { const c = charge(s.cpus, s.mem_gb, b); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); }; // #6204: elastic lanes are charged their measured base
|
|
410
|
+
const sumRecs = (rs) => { const b = elastic() ? elasticBase() : null; return rs.reduce((a, s) => { const c = charge(s.cpus, s.mem_gb, b, s.heavyRemote === true); return { cpus: a.cpus + c.cpus, mem: a.mem + c.mem }; }, { cpus: 0, mem: 0 }); }; // #6204: elastic lanes are charged their measured base
|
|
387
411
|
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
388
412
|
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
389
413
|
/** Admission headroom per class: free = physical, unreserved_free = space outside every reservation, borrowable = what `borrow` may take. */
|
|
@@ -497,7 +521,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
497
521
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
498
522
|
const e = effectiveCapacity();
|
|
499
523
|
const h = live(cfg);
|
|
500
|
-
return { host: cfg.name ?? hostname(), usage_summary: usageSummary(Object.values(sb()).filter((r) => r.state !== "exited").map(usageView)), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
524
|
+
return { host: cfg.name ?? hostname(), usage_summary: usageSummary(Object.values(sb()).filter((r) => r.state !== "exited").map(usageView)), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused || dnsHold > 0), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
501
525
|
}
|
|
502
526
|
|
|
503
527
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
@@ -570,7 +594,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
570
594
|
const reservation = prio === "reserved" ? (spec.reservation ?? (reservations().length === 1 ? reservations()[0].name : null)) : null;
|
|
571
595
|
const c = capacity();
|
|
572
596
|
const h = live(cfg);
|
|
573
|
-
const
|
|
597
|
+
const heavyRemote = elastic() ? await laneHasRemoteHeavy(spec.image ?? image) : false; // #6235
|
|
598
|
+
const adm = admit({ prio, cpus: charge(cpus, mem_gb, undefined, heavyRemote).cpus, mem_gb: charge(cpus, mem_gb, undefined, heavyRemote).mem, reservation, h }); // #6204
|
|
574
599
|
if (c.draining && !c.paused) return { status: 503, body: { error: `draining: ${c.draining_reason}`, code: "pool.draining", capacity: c }, retryAfter: 60 }; // #6061: finish running lanes, accept none
|
|
575
600
|
if (laneTargetOn() && !c.paused && c.active >= laneNow()) return { status: 503, body: { error: `lane target ${laneNow()} reached (${c.active} running)`, code: "pool.lane_target", lane_target: laneNow(), capacity: c }, retryAfter: 60 };
|
|
576
601
|
if (c.paused || adm.refuse) {
|
|
@@ -581,7 +606,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
581
606
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
582
607
|
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
583
608
|
if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
|
|
584
|
-
const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), ch = charge(cpus, mem_gb), nm = elastic() ? ch.mem : Math.max(mem_gb, est.mem), nc = elastic() ? ch.cpus : Math.max(cpus, est.cpus);
|
|
609
|
+
const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), ch = charge(cpus, mem_gb, undefined, heavyRemote), nm = elastic() ? ch.mem : Math.max(mem_gb, est.mem), nc = elastic() ? ch.cpus : Math.max(cpus, est.cpus);
|
|
585
610
|
const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
|
|
586
611
|
if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
|
|
587
612
|
}
|
|
@@ -626,10 +651,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
626
651
|
const envFile = join(dir, "env");
|
|
627
652
|
const credToken = randomBytes(24).toString("hex");
|
|
628
653
|
const withDocker = Boolean(spec.docker);
|
|
629
|
-
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
654
|
+
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() && heavyRemote ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
630
655
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
631
656
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
632
|
-
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
|
|
657
|
+
const rec = { heavyRemote, id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
|
|
633
658
|
sb()[spec.id] = rec;
|
|
634
659
|
store.save();
|
|
635
660
|
rec.cacheVolume = cacheVolumeOf(spec.cache?.key ?? spec.repo?.slug); // an explicit agent_id gives this agent its own volume: a shared one would let its work sweep delete a co-resident agent's worktrees
|
package/bin/pool/docker-dns.mjs
CHANGED
|
@@ -1,23 +1,39 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
-
// #6195: on WSL2 mirrored networking dockerd's resolver (the WSL proxy, 10.255.255.254) can fail while the host resolver works.
|
|
3
|
+
// #6195/#6234: on WSL2 mirrored networking dockerd's resolver (the WSL proxy, 10.255.255.254) can fail while the host resolver works.
|
|
4
|
+
// Lane containers get a per-container `--dns` (agent netArgs), which never touches the shared daemon. Only the daemon's own pulls need the
|
|
5
|
+
// daemon-wide fallback, and a dockerd restart kills every container on it, so it runs only when provably nothing else is on the daemon.
|
|
4
6
|
import { readFileSync, writeFileSync } from "node:fs";
|
|
5
7
|
|
|
6
8
|
/** dockerd's own resolver failing: "lookup ghcr.io on 10.255.255.254:53: no such host" / "server misbehaving". */
|
|
7
9
|
export const DNS_FAIL_RE = /lookup \S+ on [0-9a-f.:]+:53: (no such host|server misbehaving)/i;
|
|
8
10
|
|
|
9
11
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
+
* Repair dockerd's resolver for the agent's own pulls. Order matters and is atomic against admission:
|
|
13
|
+
* 1. `hold()` pauses admission on the agent (returns a release function; called in a finally),
|
|
14
|
+
* 2. `idle()` (sync or async) must say that no sandbox is active AND no container at all (co-tenants included) runs on the daemon,
|
|
15
|
+
* 3. only then daemon.json `dns` is written (other keys kept; a `dns` already set is left alone) and docker restarted.
|
|
16
|
+
* Not idle, an unreadable file or a failed restart: daemon.json is left (or put back) as it was, so no resolver is pinned without a restart.
|
|
17
|
+
* Returns {changed, restarted, reason?}. Never throws.
|
|
12
18
|
*/
|
|
13
|
-
export async function ensureDaemonDns({ file = "/etc/docker/daemon.json", dns = ["1.1.1.1", "8.8.8.8"], restart = async () => {}, idle = () => false, log = null } = {}) {
|
|
14
|
-
let
|
|
15
|
-
try {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
export async function ensureDaemonDns({ file = "/etc/docker/daemon.json", dns = ["1.1.1.1", "8.8.8.8"], restart = async () => {}, idle = () => false, hold = () => () => {}, log = null } = {}) {
|
|
20
|
+
let release = () => {};
|
|
21
|
+
try { release = hold() ?? release; } catch (e) { log?.warn?.(`docker DNS repair: cannot pause admission: ${e.message}`); return { changed: false, restarted: false, reason: "hold" }; }
|
|
22
|
+
try {
|
|
23
|
+
let raw = "", cfg = {};
|
|
24
|
+
try { raw = readFileSync(file, "utf8"); cfg = JSON.parse(raw || "{}"); } catch (e) { if (e?.code !== "ENOENT") { log?.warn?.(`daemon.json unreadable: ${e.message}`); return { changed: false, restarted: false, reason: "unreadable" }; } raw = ""; }
|
|
25
|
+
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) return { changed: false, restarted: false, reason: "unreadable" };
|
|
26
|
+
if (Array.isArray(cfg.dns) && cfg.dns.length) return { changed: false, restarted: false, reason: "dns-set" };
|
|
27
|
+
let quiet = false;
|
|
28
|
+
try { quiet = (await idle()) === true; } catch { quiet = false; }
|
|
29
|
+
if (!quiet) { log?.warn?.("docker not restarted: sandboxes or other containers are running; lane containers use per-container --dns, daemon.json is untouched"); return { changed: false, restarted: false, reason: "busy" }; }
|
|
30
|
+
try { writeFileSync(file, `${JSON.stringify({ ...cfg, dns }, null, 2)}\n`); } catch (e) { log?.warn?.(`cannot write ${file}: ${e.message}`); return { changed: false, restarted: false, reason: "unwritable" }; }
|
|
31
|
+
try { await restart(); } catch (e) {
|
|
32
|
+
log?.warn?.(`docker restart failed: ${e.message}; daemon.json restored`);
|
|
33
|
+
try { writeFileSync(file, raw || "{}\n"); } catch { /* best effort */ }
|
|
34
|
+
return { changed: false, restarted: false, reason: "restart-failed" };
|
|
35
|
+
}
|
|
36
|
+
log?.info?.(`docker daemon DNS set to ${dns.join(", ")} in ${file}; docker restarted while idle`);
|
|
37
|
+
return { changed: true, restarted: true };
|
|
38
|
+
} finally { try { release(); } catch { /* ignore */ } }
|
|
23
39
|
}
|
package/bin/pool/docker.mjs
CHANGED
|
@@ -48,6 +48,8 @@ export const dockerCli = {
|
|
|
48
48
|
const out = await docker(["ps", "-a", ...[].concat(label).flatMap((l) => ["--filter", `label=${l}`]), "--format", "{{.Names}}"], { timeoutMs: 20000 });
|
|
49
49
|
return out ? out.split("\n").filter(Boolean) : [];
|
|
50
50
|
},
|
|
51
|
+
/** #6234: names of every running container on the daemon (any owner); the DNS repair restarts dockerd only when this is empty. */
|
|
52
|
+
async listRunning() { const out = await docker(["ps", "--format", "{{.Names}}"], { timeoutMs: 20000 }); return out ? out.split("\n").filter(Boolean) : []; },
|
|
51
53
|
async removeVolume(name) { try { await docker(["volume", "rm", "-f", name], { timeoutMs: 120000 }); } catch (e) { if (!/no such volume/i.test(e.stderr ?? "")) throw e; } },
|
|
52
54
|
/** #5881: `label` (one or a list) restricts the list to volumes carrying it, e.g. this agent's. */
|
|
53
55
|
async listVolumes(prefix, label = []) {
|