forgedock 1.61.1 → 1.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +10 -1
- package/bin/engine/outcome-codes.mjs +4 -0
- package/bin/engine-cli.mjs +160 -18
- package/bin/env/env.mjs +6 -4
- package/bin/forge-home-check.mjs +91 -0
- package/bin/forgedock.mjs +50 -7
- package/bin/gc.mjs +2 -0
- package/bin/hooks/pre-tool-use.mjs +4 -0
- package/bin/journey.mjs +55 -5
- package/bin/lean/admission.mjs +16 -5
- package/bin/lean/batch-health.mjs +55 -16
- package/bin/lean/batch-health.test.mjs +67 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +5 -0
- package/bin/lean/ceiling.mjs +20 -0
- package/bin/lean/ceiling.test.mjs +33 -2
- package/bin/lean/ci-gate.mjs +240 -0
- package/bin/lean/ci-gate.test.mjs +227 -0
- package/bin/lean/ci-precheck.mjs +178 -0
- package/bin/lean/ci-precheck.test.mjs +149 -0
- package/bin/lean/conformance.mjs +118 -20
- package/bin/lean/conformance.test.mjs +193 -3
- package/bin/lean/context.test.mjs +7 -6
- package/bin/lean/dag.mjs +128 -0
- package/bin/lean/dag.test.mjs +131 -0
- package/bin/lean/decisions.mjs +5 -4
- package/bin/lean/decisions.test.mjs +11 -0
- package/bin/lean/delguard.mjs +84 -0
- package/bin/lean/delguard.test.mjs +104 -0
- package/bin/lean/depcache.mjs +125 -17
- package/bin/lean/depcache.test.mjs +111 -0
- package/bin/lean/design-gate.mjs +5 -5
- package/bin/lean/design-gate.test.mjs +14 -0
- package/bin/lean/effects.mjs +81 -7
- package/bin/lean/execution.mjs +81 -15
- package/bin/lean/execution.test.mjs +156 -3
- package/bin/lean/forgedock-lane-workflow.test.mjs +35 -0
- package/bin/lean/guardgate.mjs +30 -7
- package/bin/lean/guardgate.test.mjs +44 -1
- package/bin/lean/guards.test.mjs +1 -1
- package/bin/lean/heavy.test.mjs +87 -0
- package/bin/lean/hotarea.mjs +73 -0
- package/bin/lean/hotarea.test.mjs +73 -0
- package/bin/lean/issuewatch-reconcile.mjs +20 -1
- package/bin/lean/issuewatch-reconcile.test.mjs +30 -0
- package/bin/lean/lanecheck.mjs +27 -3
- package/bin/lean/lanecheck.test.mjs +47 -5
- package/bin/lean/laneconfine.mjs +83 -0
- package/bin/lean/laneconfine.test.mjs +113 -0
- package/bin/lean/lean.mjs +398 -91
- package/bin/lean/lean.test.mjs +792 -26
- package/bin/lean/live-reconcile.mjs +169 -0
- package/bin/lean/live-reconcile.test.mjs +176 -0
- package/bin/lean/orchestrate-envhold.test.mjs +245 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +39 -0
- package/bin/lean/orchestrate.mjs +207 -17
- package/bin/lean/outcomeevidence.mjs +104 -0
- package/bin/lean/outcomeevidence.test.mjs +78 -0
- package/bin/lean/page-capture.mjs +68 -0
- package/bin/lean/page-capture.test.mjs +44 -0
- package/bin/lean/pagegate.mjs +46 -7
- package/bin/lean/pagegate.test.mjs +66 -1
- package/bin/lean/postdeploy-check.mjs +18 -4
- package/bin/lean/postdeploy-check.test.mjs +32 -1
- package/bin/lean/prefilter.mjs +36 -4
- package/bin/lean/prefilter.test.mjs +31 -1
- package/bin/lean/preflight.mjs +22 -0
- package/bin/lean/preflight.test.mjs +19 -1
- package/bin/lean/probe.mjs +18 -0
- package/bin/lean/probe.test.mjs +40 -0
- package/bin/lean/prompts.mjs +41 -4
- package/bin/lean/recovery.test.mjs +20 -0
- package/bin/lean/recurrence.mjs +133 -0
- package/bin/lean/recurrence.test.mjs +99 -0
- package/bin/lean/release-config.mjs +2 -1
- package/bin/lean/release-config.test.mjs +18 -0
- package/bin/lean/release-control.mjs +4 -2
- package/bin/lean/release-control.test.mjs +15 -0
- package/bin/lean/release-merge-hold.mjs +65 -0
- package/bin/lean/release-merge-hold.test.mjs +69 -0
- package/bin/lean/release-review.mjs +26 -9
- package/bin/lean/release-review.test.mjs +53 -0
- package/bin/lean/release-status.mjs +3 -1
- package/bin/lean/release-status.test.mjs +11 -0
- package/bin/lean/release.test.mjs +26 -1
- package/bin/lean/render.mjs +8 -7
- package/bin/lean/repro-output.test.mjs +45 -0
- package/bin/lean/routing.mjs +49 -0
- package/bin/lean/routing.test.mjs +54 -1
- package/bin/lean/run-issue-placement.test.mjs +30 -1
- package/bin/lean/sandbox-actions.mjs +121 -0
- package/bin/lean/sandbox-actions.test.mjs +94 -0
- package/bin/lean/sandbox-provider.contract.test.mjs +22 -1
- package/bin/lean/sandbox-remote.mjs +3 -1
- package/bin/lean/schedd-health.mjs +14 -2
- package/bin/lean/schedd-health.test.mjs +13 -0
- package/bin/lean/schedd.mjs +43 -17
- package/bin/lean/schedd.test.mjs +61 -1
- package/bin/lean/toolchain.mjs +16 -6
- package/bin/lean/toolplace.mjs +12 -0
- package/bin/lean/weakguard.mjs +105 -0
- package/bin/lean/weakguard.test.mjs +59 -0
- package/bin/lean/winspawn.mjs +61 -0
- package/bin/lean/winspawn.test.mjs +45 -0
- package/bin/lean/worktree.mjs +3 -1
- package/bin/lean/worktree.test.mjs +11 -0
- package/bin/pool/agent.mjs +215 -15
- package/bin/pool/cache-sweep.mjs +74 -0
- package/bin/pool/cli.mjs +11 -3
- package/bin/pool/docker.mjs +33 -2
- package/bin/pool/health.mjs +38 -0
- package/bin/pool/lane-tools.mjs +23 -4
- package/bin/pool/lane-tools.test.mjs +12 -1
- package/bin/pool/router.mjs +21 -3
- package/bin/runner.mjs +37 -0
- package/bin/splash-scene.mjs +356 -0
- package/bin/win-hide-children.mjs +114 -0
- package/commands/orchestrate.md +18 -27
- package/commands/review-pr-agents/infra.md +1 -0
- package/commands/review-pr-staging.md +2 -2
- package/docs/CONFIG.md +60 -3
- package/docs/OUTCOME-CODES.md +3 -0
- package/package.json +1 -1
- package/plugins/forgedock-splash/.claude-plugin/plugin.json +1 -1
- package/plugins/forgedock-splash/README.md +1 -1
- package/plugins/forgedock-splash/hooks/scene.ts +142 -8
- package/pool/README.md +6 -0
- package/pool/image/entrypoint.sh +1 -0
- package/scripts/acceptance-red-green.sh +8 -3
- package/scripts/acceptance-red-green.test.sh +8 -0
- package/scripts/check-spec-size.sh +3 -1
- package/scripts/gen-splash-scene.mjs +24 -0
- package/scripts/review-staging-pre.sh +8 -3
- package/scripts/review-staging-pre.test.sh +2 -0
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// #5542: `run-issue` follows forge.yaml `execution:` like `orchestrate`, and `--local` keeps the lane on this host.
|
|
4
4
|
import { describe, it } from "node:test";
|
|
5
5
|
import assert from "node:assert/strict";
|
|
6
|
-
import { readFileSync } from "node:fs";
|
|
6
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
9
9
|
import { parseExecution, openExecutionBudget } from "./execution.mjs";
|
|
@@ -80,3 +80,32 @@ describe("run-issue placement (#5542)", () => {
|
|
|
80
80
|
assert.match(String(r.pr), /8$/);
|
|
81
81
|
});
|
|
82
82
|
});
|
|
83
|
+
|
|
84
|
+
describe("run-issue public-repo default placement (#5748)", () => {
|
|
85
|
+
const inEmptyDir = async (fn) => { const prev = process.cwd(); process.chdir(tmpDir("nocfg-")); try { return await fn(); } finally { process.chdir(prev); } };
|
|
86
|
+
it("a public repo with no execution config places the lane on the actions provider", async () => {
|
|
87
|
+
const prov = fakeProvider((n) => ({ terminalReason: "merged", pr: 100 + n, cost_usd: 0 }));
|
|
88
|
+
const { deps } = setup("pubdef", prov, { execution: undefined, repoPublic: true });
|
|
89
|
+
const { res, out } = await inEmptyDir(() => logs(() => runFromCli(["7", "--repo", "o/r", "--no-prefilter"], deps)));
|
|
90
|
+
assert.deepEqual(prov.calls.filter((c) => c[0] === "start").map((c) => c[1]), [7]);
|
|
91
|
+
assert.equal(res.res?.terminalReason ?? res.terminalReason, "merged");
|
|
92
|
+
assert.ok(out.some((l) => /^placement: remote execution \(actions\)/.test(l)), out.join("\n"));
|
|
93
|
+
});
|
|
94
|
+
it("an explicit execution.mode: local in forge.yaml opts a public repo out", async () => {
|
|
95
|
+
const prov = fakeProvider(() => ({ terminalReason: "merged" }));
|
|
96
|
+
const { deps, ran } = setup("explicit", prov, { execution: undefined, repoPublic: true });
|
|
97
|
+
const dir = tmpDir("cfg-"); writeFileSync(join(dir, "forge.yaml"), "execution:\n mode: local\n");
|
|
98
|
+
const prev = process.cwd(); process.chdir(dir);
|
|
99
|
+
try { await logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging"], { ...deps, leanModule: core(ran) })); } finally { process.chdir(prev); }
|
|
100
|
+
assert.equal(ran.length, 1); assert.deepEqual(prov.calls, []);
|
|
101
|
+
});
|
|
102
|
+
it("a private repo, or a failed visibility lookup, keeps the local default", async () => {
|
|
103
|
+
for (const repoPublic of [false, undefined]) {
|
|
104
|
+
const prov = fakeProvider(() => ({ terminalReason: "merged" }));
|
|
105
|
+
const { deps, ran } = setup(`privdef-${repoPublic}`, prov, { execution: undefined, ...(repoPublic === undefined ? {} : { repoPublic }) });
|
|
106
|
+
await inEmptyDir(() => logs(() => runFromCli(["7", "--repo", "o/r", "--lane", "staging"], { ...deps, leanModule: core(ran) })));
|
|
107
|
+
assert.equal(ran.length, 1); assert.deepEqual(prov.calls, []);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* GitHub Actions lane provider (#5748) on the remote provider seam (sandbox-remote.mjs). A lane is a `workflow_dispatch`
|
|
5
|
+
* run of `.github/workflows/forgedock-lane.yml` on a hosted runner (free for public repos). The transport is the only
|
|
6
|
+
* Actions-specific part:
|
|
7
|
+
* launch dispatches the workflow with non-secret inputs only (lane_id, issue, batch, ref = the base lane, args); the Claude credential
|
|
8
|
+
* lives in the workflow's `forgedock-lane` environment and the spec's env is never sent (inputs are public)
|
|
9
|
+
* status finds the run by its run-name `forgedock-lane <lane_id>`: queued or in_progress is running, completed exited
|
|
10
|
+
* result the lane posts its result as an issue comment `<!-- FORGE:LANE-RESULT <lane_id> -->` + a json fence; only a
|
|
11
|
+
* comment by github-actions[bot] counts (anyone can comment on a public repo). A run that hit the 6 h limit
|
|
12
|
+
* without a result is a retryable deferral: run-issue pushes checkpoints and the retry resumes from them
|
|
13
|
+
* capacity the plan's concurrent-job limit minus a CI reserve minus the lane runs in flight
|
|
14
|
+
* GitHub stays the register: a lane id is `fdrsbx-<batch>-<issue>`, so a restarted dispatcher re-finds its run.
|
|
15
|
+
*/
|
|
16
|
+
import { spawn } from "node:child_process";
|
|
17
|
+
import { remoteProvider, redact } from "./sandbox-remote.mjs";
|
|
18
|
+
|
|
19
|
+
export const LANE_WORKFLOW = "forgedock-lane.yml";
|
|
20
|
+
export const LANE_ENVIRONMENT = "forgedock-lane";
|
|
21
|
+
export const LANE_RESULT_MARKER = (id) => `<!-- FORGE:LANE-RESULT ${id} -->`;
|
|
22
|
+
export const ACTIONS_TIMEOUT_CODE = "sandbox.actions_timeout";
|
|
23
|
+
const ACTIONS_TIMEOUT_RETRY_S = 60;
|
|
24
|
+
/** Standard concurrent-job limits per plan (docs.github.com Actions limits); an unknown plan is the smallest. */
|
|
25
|
+
export const PLAN_JOB_LIMITS = Object.freeze({ free: 20, pro: 40, team: 60, enterprise: 500 });
|
|
26
|
+
export const DEFAULT_CI_RESERVE = 5;
|
|
27
|
+
const SAFE_REF = /^[A-Za-z0-9][A-Za-z0-9._\/-]*$/;
|
|
28
|
+
const RESULT_BOT = "github-actions[bot]";
|
|
29
|
+
const typedError = (code, message) => Object.assign(new Error(message), { code });
|
|
30
|
+
|
|
31
|
+
/** The lane-run limit: an explicit `job_limit`, else the plan's, minus the CI reserve; never below 0. */
|
|
32
|
+
export function laneCap({ jobLimit = null, plan = null, ciReserve = DEFAULT_CI_RESERVE } = {}) {
|
|
33
|
+
const limit = Number.isInteger(jobLimit) && jobLimit > 0 ? jobLimit : PLAN_JOB_LIMITS[String(plan ?? "").toLowerCase()] ?? PLAN_JOB_LIMITS.free;
|
|
34
|
+
const reserve = Number.isInteger(ciReserve) && ciReserve >= 0 ? ciReserve : DEFAULT_CI_RESERVE;
|
|
35
|
+
return Math.max(0, limit - reserve);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** `gh api` as an async JSON call: `api(method, path, body?)` → parsed JSON, or null for an empty body. Throws on a non-2xx. */
|
|
39
|
+
export function ghApi({ env = process.env, bin = "gh" } = {}) {
|
|
40
|
+
return (method, path, body = null) => new Promise((resolve, reject) => {
|
|
41
|
+
const args = ["api", "-X", method, path, ...(method === "GET" && /\/comments(\?|$)/.test(path) ? ["--paginate", "--slurp"] : []), ...(body ? ["--input", "-"] : [])];
|
|
42
|
+
const c = spawn(bin, args, { env, stdio: ["pipe", "pipe", "pipe"] });
|
|
43
|
+
let out = "", err = "";
|
|
44
|
+
c.stdout.on("data", (d) => { out += d; });
|
|
45
|
+
c.stderr.on("data", (d) => { err += d; });
|
|
46
|
+
c.on("error", reject);
|
|
47
|
+
c.on("close", (code) => {
|
|
48
|
+
if (code !== 0) return reject(Object.assign(new Error(err.split("\n")[0].slice(0, 300) || `gh api exited ${code}`), { status: /HTTP (\d{3})/.exec(err)?.[1] ? Number(/HTTP (\d{3})/.exec(err)[1]) : undefined }));
|
|
49
|
+
try { resolve(out.trim() ? JSON.parse(out) : null); } catch (e) { reject(e); }
|
|
50
|
+
});
|
|
51
|
+
if (body) c.stdin.end(JSON.stringify(body)); else c.stdin.end();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const flat = (r) => (Array.isArray(r) ? r.flat() : []);
|
|
56
|
+
const issueOf = (id) => /-(\d+)$/.exec(String(id))?.[1] ?? null;
|
|
57
|
+
|
|
58
|
+
/** The Actions transport over an injected `api`. Its launch never carries the spec's env. */
|
|
59
|
+
export function actionsTransport({ repo, settings = {}, api, now = () => Date.now() }) {
|
|
60
|
+
if (typeof api !== "function") throw new Error("actions provider needs an api");
|
|
61
|
+
const runs = async () => ((await api("GET", `repos/${repo}/actions/workflows/${LANE_WORKFLOW}/runs?event=workflow_dispatch&per_page=100`))?.workflow_runs ?? []);
|
|
62
|
+
const runOf = async (id) => (await runs()).find((r) => r.display_title === `forgedock-lane ${id}`) ?? null;
|
|
63
|
+
const launched = new Map(); // lane id -> dispatch time: a run is not listed for a few seconds
|
|
64
|
+
const GRACE_MS = 120000;
|
|
65
|
+
return {
|
|
66
|
+
async launch(spec) {
|
|
67
|
+
if (!/^fdrsbx-[A-Za-z0-9._-]+-\d+$/.test(spec.id)) throw typedError("execution.provider.misconfigured", `actions lane id ${JSON.stringify(spec.id)} is not a lane id`);
|
|
68
|
+
let ref = spec.repo?.ref ?? null;
|
|
69
|
+
if (!ref) { try { ref = (await api("GET", `repos/${repo}`))?.default_branch ?? null; } catch { ref = null; } } // no --lane: the repo's default branch
|
|
70
|
+
if (!ref || !SAFE_REF.test(ref) || ref.includes("..")) throw typedError("execution.provider.misconfigured", `actions lane needs a base lane ref (--lane); got ${JSON.stringify(ref)}`);
|
|
71
|
+
if (settings.dispatcher) {
|
|
72
|
+
let login = null;
|
|
73
|
+
try { login = (await api("GET", "user"))?.login ?? null; } catch { login = null; }
|
|
74
|
+
if (login !== settings.dispatcher) throw typedError("actions.dispatcher_refused", `the dispatcher identity ${JSON.stringify(login)} is not the configured execution.dispatcher ${JSON.stringify(settings.dispatcher)}`);
|
|
75
|
+
}
|
|
76
|
+
const args = (spec.command ?? []).slice(3).filter((a, i, all) => a !== "--result-file" && all[i - 1] !== "--result-file").map(String);
|
|
77
|
+
await api("POST", `repos/${repo}/actions/workflows/${LANE_WORKFLOW}/dispatches`, { ref, inputs: { lane_id: spec.id, issue: String(spec.issue), batch: String(spec.batch ?? ""), ref, args: JSON.stringify(args) } });
|
|
78
|
+
launched.set(spec.id, now());
|
|
79
|
+
},
|
|
80
|
+
async status(id) {
|
|
81
|
+
const r = await runOf(id);
|
|
82
|
+
if (!r) return now() - (launched.get(id) ?? -Infinity) < GRACE_MS ? "running" : "gone";
|
|
83
|
+
return r.status === "completed" ? "exited" : "running";
|
|
84
|
+
},
|
|
85
|
+
async result(id) {
|
|
86
|
+
const issue = issueOf(id);
|
|
87
|
+
if (issue) {
|
|
88
|
+
const marker = LANE_RESULT_MARKER(id);
|
|
89
|
+
const mine = flat(await api("GET", `repos/${repo}/issues/${issue}/comments?per_page=100`)).filter((c) => c?.user?.login === RESULT_BOT && String(c.body ?? "").startsWith(marker));
|
|
90
|
+
const body = String(mine.at(-1)?.body ?? "");
|
|
91
|
+
const m = /```json\s*\n([\s\S]*?)\n```/.exec(body);
|
|
92
|
+
if (m) { try { const o = JSON.parse(m[1]); if (o && typeof o === "object") return o; } catch { /* unreadable: fall through */ } }
|
|
93
|
+
}
|
|
94
|
+
const r = await runOf(id);
|
|
95
|
+
if (r?.conclusion === "timed_out") return { terminalReason: "deferred", code: ACTIONS_TIMEOUT_CODE, retryInSeconds: ACTIONS_TIMEOUT_RETRY_S, detail: `run ${r.id} hit the Actions job time limit before it posted a result; the retry resumes from the lane's pushed checkpoint` };
|
|
96
|
+
return null;
|
|
97
|
+
},
|
|
98
|
+
async usage(id) {
|
|
99
|
+
const r = await runOf(id);
|
|
100
|
+
const a = Date.parse(r?.run_started_at ?? ""), b = Date.parse(r?.updated_at ?? "");
|
|
101
|
+
return Number.isFinite(a) && Number.isFinite(b) && b >= a ? { minutes: Math.round(((b - a) / 60000) * 10) / 10, cost_usd: 0 } : null;
|
|
102
|
+
},
|
|
103
|
+
async destroy(id) {
|
|
104
|
+
launched.delete(id); // a destroyed lane is gone, not "not listed yet"
|
|
105
|
+
const r = await runOf(id);
|
|
106
|
+
if (r && r.status !== "completed") { try { await api("POST", `repos/${repo}/actions/runs/${r.id}/cancel`); } catch (e) { if (e?.status !== 409) return false; } }
|
|
107
|
+
return true;
|
|
108
|
+
},
|
|
109
|
+
async capacity() {
|
|
110
|
+
const cap = laneCap({ jobLimit: settings.jobLimit ?? null, plan: settings.plan ?? null, ciReserve: settings.ciReserve });
|
|
111
|
+
const busy = (await runs()).filter((r) => r.status !== "completed" && String(r.display_title ?? "").startsWith("forgedock-lane ")).length;
|
|
112
|
+
return { free: Math.max(0, cap - busy), online: null };
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The `actions` sandbox provider: the remote provider over `actionsTransport`; the lane log stays on GitHub (public). */
|
|
118
|
+
export function actionsProvider({ batch, repo, settings = {}, api = ghApi(), env = process.env, credentials, now, transport = null, ...rest }) {
|
|
119
|
+
const t = transport ?? actionsTransport({ repo, settings, api, ...(now ? { now } : {}) });
|
|
120
|
+
return remoteProvider({ batch, repo, settings, name: "actions", env, transport: t, ...(credentials ? { credentials } : {}), ...(now ? { now } : {}), ...rest });
|
|
121
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5748: the Actions lane provider over a fake GitHub API.
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
+
import { actionsProvider, laneCap, LANE_RESULT_MARKER, ACTIONS_TIMEOUT_CODE } from "./sandbox-actions.mjs";
|
|
9
|
+
import { openBatch } from "./batch.mjs";
|
|
10
|
+
|
|
11
|
+
/** A fake GitHub: workflow runs by run-name, issue comments, the authenticated login. */
|
|
12
|
+
export function fakeGithub({ login = "forgedock-bot" } = {}) {
|
|
13
|
+
const g = { runs: [], comments: [], dispatches: [], cancelled: [], nextId: 100 };
|
|
14
|
+
g.api = async (method, path, body) => {
|
|
15
|
+
if (method === "POST" && /\/dispatches$/.test(path)) {
|
|
16
|
+
g.dispatches.push({ path, body });
|
|
17
|
+
g.runs.push({ id: g.nextId++, display_title: `forgedock-lane ${body.inputs.lane_id}`, status: "in_progress", conclusion: null, run_started_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:04:30Z" });
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (method === "GET" && /\/runs\?/.test(path)) return { workflow_runs: g.runs };
|
|
21
|
+
if (method === "GET" && /\/comments\?/.test(path)) return [g.comments];
|
|
22
|
+
if (method === "GET" && path === "repos/o/r") return { default_branch: "main" };
|
|
23
|
+
if (method === "GET" && path === "user") return { login };
|
|
24
|
+
if (method === "POST" && /\/cancel$/.test(path)) { const r = g.runs.find((x) => path.includes(`/runs/${x.id}/`)); g.cancelled.push(r.id); r.status = "completed"; return null; }
|
|
25
|
+
throw new Error(`unexpected ${method} ${path}`);
|
|
26
|
+
};
|
|
27
|
+
g.finish = (id, result, { author = "github-actions[bot]", conclusion = "success" } = {}) => {
|
|
28
|
+
const r = g.runs.find((x) => x.display_title === `forgedock-lane ${id}`); r.status = "completed"; r.conclusion = conclusion;
|
|
29
|
+
if (result) g.comments.push({ user: { login: author }, body: `${LANE_RESULT_MARKER(id)}\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\`` });
|
|
30
|
+
};
|
|
31
|
+
return g;
|
|
32
|
+
}
|
|
33
|
+
const make = (g, settings = {}) => { const work = tmpDir("actions-"); const batch = openBatch(join(work, "batches"), "bt"); return { batch, provider: actionsProvider({ batch, repo: "o/r", settings, api: g.api, env: {}, credentials: () => null, gitIdentity: () => ({}) }) }; };
|
|
34
|
+
const START = { issue: 7, args: ["--repo", "o/r", "--lane", "staging"], env: {}, secrets: [] };
|
|
35
|
+
|
|
36
|
+
describe("actions provider (#5748)", () => {
|
|
37
|
+
it("dispatches forgedock-lane.yml with non-secret inputs only, on the base lane ref", async () => {
|
|
38
|
+
const g = fakeGithub(); const { provider } = make(g, { secrets: ["GH_TOKEN"] });
|
|
39
|
+
const h = await provider.start({ ...START, env: { GH_TOKEN: "s3cret-value-123" }, secrets: ["GH_TOKEN"] });
|
|
40
|
+
assert.equal(provider.name, "actions");
|
|
41
|
+
const d = g.dispatches[0];
|
|
42
|
+
assert.match(d.path, /repos\/o\/r\/actions\/workflows\/forgedock-lane\.yml\/dispatches$/);
|
|
43
|
+
assert.equal(d.body.ref, "staging");
|
|
44
|
+
assert.deepEqual(Object.keys(d.body.inputs).sort(), ["args", "batch", "issue", "lane_id", "ref"]);
|
|
45
|
+
assert.equal(JSON.stringify(d).includes("s3cret-value-123"), false);
|
|
46
|
+
assert.deepEqual(JSON.parse(d.body.inputs.args), ["--repo", "o/r", "--lane", "staging"]);
|
|
47
|
+
assert.equal(d.body.inputs.lane_id, h.id);
|
|
48
|
+
assert.equal(await provider.status(h), "running");
|
|
49
|
+
});
|
|
50
|
+
it("polls the run and reads the result from a github-actions[bot] comment only", async () => {
|
|
51
|
+
const g = fakeGithub(); const { provider } = make(g);
|
|
52
|
+
const h = await provider.start(START);
|
|
53
|
+
g.finish(h.id, { terminalReason: "merged", pr: 9 }, { author: "mallory" }); // a spoofed comment on a public repo
|
|
54
|
+
assert.equal(await provider.status(h), "exited");
|
|
55
|
+
assert.equal(await provider.fetchResult(h), null);
|
|
56
|
+
g.comments.push({ user: { login: "github-actions[bot]" }, body: `${LANE_RESULT_MARKER(h.id)}\n\`\`\`json\n{"terminalReason":"merged","pr":9}\n\`\`\`` });
|
|
57
|
+
assert.deepEqual(await provider.fetchResult(h), { terminalReason: "merged", pr: 9 });
|
|
58
|
+
assert.equal(h.minutes, 4.5);
|
|
59
|
+
});
|
|
60
|
+
it("a run that hit the job time limit without a result is a retryable deferral", async () => {
|
|
61
|
+
const g = fakeGithub(); const { provider } = make(g);
|
|
62
|
+
const h = await provider.start(START);
|
|
63
|
+
g.finish(h.id, null, { conclusion: "timed_out" });
|
|
64
|
+
const r = await provider.fetchResult(h);
|
|
65
|
+
assert.equal(r.terminalReason, "deferred"); assert.equal(r.code, ACTIONS_TIMEOUT_CODE); assert.ok(r.retryInSeconds > 0);
|
|
66
|
+
});
|
|
67
|
+
it("a run that is not listed is gone after the dispatch grace; teardown cancels a live run", async () => {
|
|
68
|
+
const g = fakeGithub(); let t = 0; const { batch } = make(g);
|
|
69
|
+
const provider = actionsProvider({ batch, repo: "o/r", settings: {}, api: g.api, env: {}, credentials: () => null, gitIdentity: () => ({}), now: () => t });
|
|
70
|
+
const h = await provider.start(START); g.runs.length = 0;
|
|
71
|
+
assert.equal(await provider.status(h), "running"); t = 130000;
|
|
72
|
+
assert.equal(await provider.status(h), "gone");
|
|
73
|
+
const h2 = await provider.start({ ...START, issue: 8 });
|
|
74
|
+
assert.equal(await provider.teardown(h2), true); assert.equal(g.cancelled.length, 1);
|
|
75
|
+
assert.equal(await provider.teardown(h2), true);
|
|
76
|
+
});
|
|
77
|
+
it("capacity is the plan's job limit minus the CI reserve minus lanes in flight", async () => {
|
|
78
|
+
assert.equal(laneCap({ plan: "free" }), 15); assert.equal(laneCap({ plan: "team", ciReserve: 10 }), 50);
|
|
79
|
+
assert.equal(laneCap({ jobLimit: 8, ciReserve: 20 }), 0); assert.equal(laneCap({}), 15);
|
|
80
|
+
const g = fakeGithub(); const { provider } = make(g, { plan: "free", ciReserve: 5 });
|
|
81
|
+
assert.deepEqual(await provider.capacity(), { free: 15, online: null });
|
|
82
|
+
await provider.start(START); await provider.start({ ...START, issue: 8 });
|
|
83
|
+
assert.equal((await provider.capacity()).free, 13);
|
|
84
|
+
});
|
|
85
|
+
it("refuses a dispatcher that is not the configured app/bot, and an unsafe base ref", async () => {
|
|
86
|
+
const g = fakeGithub({ login: "someone-else" }); const { provider } = make(g, { dispatcher: "forgedock-bot" });
|
|
87
|
+
await assert.rejects(provider.start(START), { code: "actions.dispatcher_refused" });
|
|
88
|
+
assert.equal(g.dispatches.length, 0);
|
|
89
|
+
const ok = make(fakeGithub(), { dispatcher: "forgedock-bot" }).provider;
|
|
90
|
+
await ok.start(START);
|
|
91
|
+
const g2 = fakeGithub(); await make(g2).provider.start({ ...START, args: [] }); assert.equal(g2.dispatches[0].body.ref, "main"); // no --lane: the default branch
|
|
92
|
+
await assert.rejects(make(fakeGithub()).provider.start({ ...START, args: ["--lane", "-x"] }), { code: "execution.provider.misconfigured" });
|
|
93
|
+
});
|
|
94
|
+
});
|
|
@@ -14,6 +14,7 @@ import { makeLedger } from "./ledger.mjs";
|
|
|
14
14
|
import { openBatch } from "./batch.mjs";
|
|
15
15
|
import { orchestrate } from "./orchestrate.mjs";
|
|
16
16
|
import { planGc, applyGc } from "../gc.mjs";
|
|
17
|
+
import { actionsProvider, LANE_RESULT_MARKER } from "./sandbox-actions.mjs";
|
|
17
18
|
|
|
18
19
|
const HOST = "testhost";
|
|
19
20
|
const SECRET = "s3cret-value-123";
|
|
@@ -62,7 +63,26 @@ function remoteFixture(batch, { launchError = null } = {}) {
|
|
|
62
63
|
};
|
|
63
64
|
}
|
|
64
65
|
|
|
65
|
-
|
|
66
|
+
/** #5748: the Actions provider over a fake GitHub (runs by run-name, result comments by the Actions bot). */
|
|
67
|
+
function actionsFixture(batch, { launchError = null } = {}) {
|
|
68
|
+
const runs = new Map(), comments = [];
|
|
69
|
+
const api = async (method, path, body) => {
|
|
70
|
+
if (method === "POST" && /\/dispatches$/.test(path)) { if (launchError) throw launchError; runs.set(`forgedock-lane ${body.inputs.lane_id}`, { id: runs.size + 1, display_title: `forgedock-lane ${body.inputs.lane_id}`, status: "in_progress" }); return null; }
|
|
71
|
+
if (method === "GET" && path === "repos/o/r") return { default_branch: "main" };
|
|
72
|
+
if (method === "GET" && /\/runs\?/.test(path)) return { workflow_runs: [...runs.values()] };
|
|
73
|
+
if (method === "GET" && /\/comments\?/.test(path)) return [comments];
|
|
74
|
+
if (method === "POST" && /\/cancel$/.test(path)) { for (const [k, r] of runs) if (path.includes(`/runs/${r.id}/`)) runs.delete(k); return null; }
|
|
75
|
+
throw new Error(`unexpected ${method} ${path}`);
|
|
76
|
+
};
|
|
77
|
+
const provider = actionsProvider({ batch, repo: "o/r", settings: {}, api, env: {}, credentials: () => null, gitIdentity: () => ({}) });
|
|
78
|
+
return {
|
|
79
|
+
provider,
|
|
80
|
+
finish: (h, result) => { runs.get(`forgedock-lane ${h.id}`).status = "completed"; comments.push({ user: { login: "github-actions[bot]" }, body: `${LANE_RESULT_MARKER(h.id)}\n\`\`\`json\n${JSON.stringify(result)}\n\`\`\`` }); },
|
|
81
|
+
exists: (id) => runs.has(`forgedock-lane ${id}`),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const FIXTURES = { container: containerFixture, remote: remoteFixture, actions: actionsFixture };
|
|
66
86
|
|
|
67
87
|
for (const [name, make] of Object.entries(FIXTURES)) {
|
|
68
88
|
describe(`sandbox provider contract: ${name} (#4254)`, () => {
|
|
@@ -100,6 +120,7 @@ for (const [name, make] of Object.entries(FIXTURES)) {
|
|
|
100
120
|
const started = [];
|
|
101
121
|
const r = await providerLanes({ provider: wrapped, laneArgs: () => ["--repo", "o/r"], ledgerFor, env: { GH_TOKEN: SECRET }, secrets: ["GH_TOKEN"], pollMs: 2 }).runOne(9, "staging", { onStart: (x) => started.push(x) });
|
|
102
122
|
assert.equal(r.terminalReason, "merged");
|
|
123
|
+
await r.postRun?.(); // #5808: teardown runs after the result is handed back
|
|
103
124
|
assert.deepEqual(atStart, [provider.idFor(9)]);
|
|
104
125
|
assert.equal(ledgerFor(9).read(), null);
|
|
105
126
|
const files = [JSON.stringify(started), JSON.stringify(r)];
|
|
@@ -22,6 +22,7 @@ import { dirname, join } from "node:path";
|
|
|
22
22
|
import { mergeRemoteLog } from "../engine/runlog.mjs";
|
|
23
23
|
import { safeSegment } from "./ledger.mjs";
|
|
24
24
|
import { scopedEnv } from "./execution.mjs";
|
|
25
|
+
import { OUTCOME_CODES } from "../engine/outcome-codes.mjs";
|
|
25
26
|
import { laneEnvFor, readEnvSnapshots } from "../env/env.mjs";
|
|
26
27
|
import { resolveCredential } from "./credentials.mjs";
|
|
27
28
|
import { relayCommandNames, runRelayed, servicePending } from "./relay.mjs";
|
|
@@ -94,7 +95,7 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
94
95
|
return s === "running" || s === "pending" || s === "starting" ? "running" : s === "gone" ? "gone" : "exited";
|
|
95
96
|
},
|
|
96
97
|
async logs(id, cursor = 0) { const r = await call("GET", `${p(id)}/logs?cursor=${encodeURIComponent(cursor)}`); return r.ok ? { text: String(r.data?.text ?? ""), cursor: r.data?.cursor ?? cursor } : { text: "", cursor }; },
|
|
97
|
-
async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
|
|
98
|
+
async result(id) { const r = await call("GET", `${p(id)}/result`); if (r.status === 401) throw Object.assign(fail("result", r), { transient: true }); if (r.ok && r.data?.drained === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, retryInSeconds: 60, cost_usd: 0, detail: `sandbox ${id} was drained to free capacity for reserved work (${String(r.data.reason ?? "").slice(0, 120)}); rescheduled` }; /* #5856 */ return r.ok && r.data && typeof r.data === "object" ? r.data : null; },
|
|
98
99
|
async usage(id) { const r = await call("GET", `${p(id)}/usage`); return r.ok && Number.isFinite(Number(r.data?.minutes)) ? { minutes: Number(r.data.minutes), ...(typeof r.data.agent === "string" && r.data.agent ? { agent: r.data.agent } : {}) } : null; }, // agent: #4549, optional
|
|
99
100
|
async stop(id) { const r = await call("POST", `${p(id)}/stop`); if (r.ok) return true; if (r.status === 404 || r.status === 405) return false; throw fail("stop", r); },
|
|
100
101
|
async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
|
|
@@ -228,6 +229,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
228
229
|
const envSnap = settings.forgeYaml ? readEnvSnapshots(settings.forgeYaml) : null; // env.snapshots: off unless enabled
|
|
229
230
|
const spec = {
|
|
230
231
|
id, issue, batch: batch.id, image: settings.image ?? null,
|
|
232
|
+
priority: "borrow", // #5856: lanes run on leftover capacity; a pool with reservations throttles/drains them for reserved work
|
|
231
233
|
repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
|
|
232
234
|
...(settings.laneTools?.length ? { lane_tools: settings.laneTools } : {}), // #5650: per-repo lane image
|
|
233
235
|
...(envSnap?.enabled ? { env_snapshots: { enabled: true, ready: envSnap.ready, keep: envSnap.keep, max_age_days: envSnap.maxAgeDays } } : {}), // the agent builds and stages snapshots outside the lane
|
|
@@ -49,10 +49,22 @@ export function tickText(c) {
|
|
|
49
49
|
return c.status === "stalled" ? `${s} (STALLED)` : s;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* Signal a stalled live daemon: SIGTERM, then SIGKILL after `graceMs` if it is still alive. #5806: a daemon that is down while
|
|
54
|
+
* `unfinished()` names daemon batches still waiting is started again (`start()`), so a dead schedd never leaves a batch parked.
|
|
55
|
+
* @returns the check, plus `killed` (and `started` when it started one)
|
|
56
|
+
*/
|
|
53
57
|
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
54
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m) } = {}) {
|
|
58
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null } = {}) {
|
|
55
59
|
const c = stallCheck({ dir, stallMs, now, alive });
|
|
60
|
+
if (c.status === "down" && start) {
|
|
61
|
+
let ids = [];
|
|
62
|
+
try { ids = unfinished() ?? []; } catch { ids = []; }
|
|
63
|
+
if (!ids.length) return { ...c, killed: null };
|
|
64
|
+
log(`schedd watchdog: FORGE:DECISION daemon down with ${ids.length} unfinished batch(es) (${ids.slice(0, 3).join(" ")}${ids.length > 3 ? " …" : ""}); starting it (it resumes them)`);
|
|
65
|
+
try { await start(); } catch (e) { log(`schedd watchdog: start failed: ${e?.message ?? e}`); return { ...c, killed: null, started: false }; }
|
|
66
|
+
return { ...c, killed: null, started: true };
|
|
67
|
+
}
|
|
56
68
|
if (c.status !== "stalled") return { ...c, killed: null };
|
|
57
69
|
log(`schedd watchdog: pid ${c.pid} silent for ${Math.round(c.ageMs / 1000)} s (limit ${Math.round(stallMs / 1000)} s), sending SIGTERM`);
|
|
58
70
|
try { kill(c.pid, "SIGTERM"); } catch { return { ...c, killed: null }; }
|
|
@@ -44,6 +44,19 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
|
44
44
|
assert.deepEqual(sent, [[42, "SIGTERM"], [42, "SIGKILL"]]);
|
|
45
45
|
});
|
|
46
46
|
|
|
47
|
+
it("#5806: a down daemon with unfinished daemon batches is started once per watchdog run; with none it is left down", async () => {
|
|
48
|
+
const dir = tmpDir("hb-"), lines = [];
|
|
49
|
+
let starts = 0;
|
|
50
|
+
const run = (unfinished, start = async () => { starts++; }) => watchdog({ dir, now: () => 0, alive: () => false, unfinished, start, log: (m) => lines.push(m) });
|
|
51
|
+
assert.equal((await run(() => [])).started, undefined);
|
|
52
|
+
assert.equal(starts, 0);
|
|
53
|
+
const r = await run(() => ["b1", "b2"]);
|
|
54
|
+
assert.deepEqual([r.status, r.started, starts], ["down", true, 1]);
|
|
55
|
+
assert.match(lines.join("\n"), /FORGE:DECISION daemon down with 2 unfinished batch\(es\) \(b1 b2\); starting it/);
|
|
56
|
+
assert.equal((await run(() => ["b1"], async () => { throw new Error("no unit"); })).started, false);
|
|
57
|
+
assert.match(lines.at(-1), /start failed: no unit/);
|
|
58
|
+
});
|
|
59
|
+
|
|
47
60
|
it("bestEffortRenice never throws", () => {
|
|
48
61
|
assert.equal(bestEffortRenice(() => { throw new Error("EACCES"); }), false);
|
|
49
62
|
assert.equal(bestEffortRenice(() => {}), true);
|
package/bin/lean/schedd.mjs
CHANGED
|
@@ -46,10 +46,11 @@ import { createConnection, createServer } from "node:net";
|
|
|
46
46
|
import { execFileSync, spawn } from "node:child_process";
|
|
47
47
|
import { homedir, tmpdir } from "node:os";
|
|
48
48
|
import { createHash } from "node:crypto";
|
|
49
|
-
import { join, resolve } from "node:path";
|
|
49
|
+
import { delimiter, join, resolve } from "node:path";
|
|
50
50
|
import { fileURLToPath } from "node:url";
|
|
51
51
|
import { schedDir, pidAlive } from "./sched.mjs";
|
|
52
|
-
import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, evaluateDispatchStall, firstHourReport, recordStallAlert, writeFirstHour } from "./batch-health.mjs";
|
|
52
|
+
import { DEFAULT_STALL_MIN, FIRST_HOUR_FILE, FIRST_HOUR_MIN, decideStallAction, evaluateDispatchStall, firstHourReport, readHealth, recordStallAlert, recordStallRecovery, writeFirstHour } from "./batch-health.mjs";
|
|
53
|
+
import { probeBatchEnv } from "./lanecheck.mjs";
|
|
53
54
|
import { HEARTBEAT_MS, writeHeartbeat, clearHeartbeat } from "./schedd-health.mjs";
|
|
54
55
|
import { batchRoot, listBatches, openBatch, SECRET_ENV } from "./batch.mjs";
|
|
55
56
|
import { killTrackedChildren } from "./effects.mjs";
|
|
@@ -121,14 +122,17 @@ export function globToRegExp(glob) {
|
|
|
121
122
|
return new RegExp(`^${re}$`);
|
|
122
123
|
}
|
|
123
124
|
|
|
124
|
-
/**
|
|
125
|
-
|
|
125
|
+
/**
|
|
126
|
+
* `path` without non-existent dirs, per-session temp dirs (an `arg0`/`claude*` dir under a temp root) and `exclude` glob matches.
|
|
127
|
+
* #5806: split on the platform's PATH separator (`;` on win32): splitting `C:\a;C:\b` on `:` left one bogus entry pinned.
|
|
128
|
+
*/
|
|
129
|
+
export function sanitizePath(path, { exclude = [], exists = existsSync, tmpRoots = ["/tmp", "/var/tmp", tmpdir(), process.env.TMPDIR], sep = delimiter } = {}) {
|
|
126
130
|
const globs = exclude.map(globToRegExp);
|
|
127
131
|
const roots = tmpRoots.filter(Boolean).map((r) => r.replace(/\/+$/, ""));
|
|
128
132
|
const keep = (d) => d && exists(d) && !globs.some((g) => g.test(d.replace(/\/+$/, "")))
|
|
129
133
|
&& !(roots.some((r) => d === r || d.startsWith(`${r}/`)) && SESSION_DIR.test(d));
|
|
130
134
|
const seen = new Set();
|
|
131
|
-
return String(path).split(
|
|
135
|
+
return String(path).split(sep).filter((d) => keep(d) && !seen.has(d) && seen.add(d)).join(sep);
|
|
132
136
|
}
|
|
133
137
|
|
|
134
138
|
/**
|
|
@@ -191,7 +195,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
191
195
|
root = batchRoot(), log = (m) => console.log(m), pid = process.pid, alive = pidAlive, resumeOnStart = true, stopMs = STOP_MS,
|
|
192
196
|
lockCheckMs = LOCK_CHECK_MS, admitMs = Number(process.env.FORGEDOCK_SCHEDD_ADMIT_MS) || ADMIT_MS, lagMs = LAG_MS, stallCheckMs = Number(process.env.FORGEDOCK_SCHEDD_STALL_CHECK_MS) || 60_000, stallMin = Number(process.env.FORGEDOCK_SCHEDD_STALL_MIN) || DEFAULT_STALL_MIN, due = null, dueMs = Number(process.env.FORGEDOCK_SCHEDD_DUE_MS) || DUE_MS, preflight = null,
|
|
193
197
|
abandonMs = (Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) > 0 ? Number(process.env.FORGEDOCK_SCHEDD_ABANDON_DAYS) * 24 * 3600 * 1000 : ABANDON_AGE_MS), killChildren = killTrackedChildren,
|
|
194
|
-
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined } = {}) {
|
|
198
|
+
hostLoad = liveOverload(), installedVersion = readInstalledVersion, respawn = undefined, probeEnv = (env) => probeBatchEnv(env), restartForStall = undefined } = {}) {
|
|
195
199
|
const p = scheddPaths(dir);
|
|
196
200
|
// #5204: default handover target: a new daemon from the (new) install unless systemd restarts the unit itself
|
|
197
201
|
const respawnFn = respawn !== undefined ? respawn : () => { if (!["active", "activating"].includes(unitState())) defaultSpawn({ dir }); };
|
|
@@ -228,7 +232,7 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
228
232
|
const emit = (m) => { for (const s of ent.subs) s(m); };
|
|
229
233
|
let started = false, endedClean = false;
|
|
230
234
|
const sink = {
|
|
231
|
-
batch: (b) => { ent.id = b.id; ent.dir = b.dir; hosted.set(b.id, ent); started = true; resolve(ent); },
|
|
235
|
+
batch: (b) => { ent.id = b.id; ent.dir = b.dir; ent.since = Date.now(); hosted.set(b.id, ent); started = true; resolve(ent); },
|
|
232
236
|
row: (row) => emit({ type: "row", row }),
|
|
233
237
|
line: (text) => emit({ type: "line", text }),
|
|
234
238
|
};
|
|
@@ -493,6 +497,11 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
493
497
|
// #5314: a batch with ready issues, free lanes and no dispatch for `stallMin` is re-hosted once per ready set, else one needs-you
|
|
494
498
|
// alert is recorded (health.json, status, sched show); every batch also gets its first-hour report once, without operator action.
|
|
495
499
|
const rehostedStall = new Map();
|
|
500
|
+
// #5806: a hosted batch whose runner is alive but makes no progress (a wedged setup read, a hung child) is recovered by the
|
|
501
|
+
// upgrade handover path (#5204): close() aborts every runner and kills the daemon's own children (lanes keep running), then a
|
|
502
|
+
// fresh daemon resumes every batch. Once per batch and ready set (recorded in health.json before the restart).
|
|
503
|
+
const restartStall = restartForStall !== undefined ? (id) => restartForStall(id)
|
|
504
|
+
: (id) => { log(`schedd: restarting to recover stalled batch ${id}`); close().then(() => { try { respawnFn?.(); } catch (e) { log(`schedd: respawn failed: ${e?.message ?? e}`); } }); };
|
|
496
505
|
let watching = false;
|
|
497
506
|
const watchBatches = async () => {
|
|
498
507
|
if (closing || watching) return;
|
|
@@ -511,27 +520,44 @@ export async function startDaemon({ dir = schedDir(), runBatch, idleMs = Number(
|
|
|
511
520
|
const created = Date.parse(plan.created ?? "");
|
|
512
521
|
if (b.isTerminal() && (!Number.isFinite(created) || now - created >= 24 * 3600_000)) continue; // nothing left to report or re-host
|
|
513
522
|
const reported = !!b.readReport(), cancelled = !!b.readCancel(), state = b.store.peek(), isHosted = hosted.has(id) || starting.has(id);
|
|
514
|
-
const
|
|
523
|
+
const stallOpts = { held: b.readHeld(), parallel: b.readParallel(), hosted: isHosted, lastProgressMs: b.lastProgressMs(), now, windowMin: stallMin, cancelled, reported };
|
|
524
|
+
let stall = evaluateDispatchStall(state, stallOpts);
|
|
525
|
+
if (stall && preflight) { // #5745: name the preflight gate holding admission (advisory; dispatch decisions are unchanged)
|
|
526
|
+
let gates = [];
|
|
527
|
+
try { gates = ((await preflight()) ?? []).filter((f) => f && f.ok !== true && f.code).map((f) => ({ code: f.code, detail: f.detail })); } catch { gates = []; }
|
|
528
|
+
if (gates.length) stall = evaluateDispatchStall(state, { ...stallOpts, gates }) ?? stall;
|
|
529
|
+
}
|
|
515
530
|
if (Number.isFinite(created) && (reported || now - created >= FIRST_HOUR_MIN * 60_000) && !existsSync(join(b.dir, FIRST_HOUR_FILE)) && now - created < 24 * 3600_000) {
|
|
516
531
|
if (writeFirstHour(b, firstHourReport(state, { batchId: id, now, held: b.readHeld(), holdInfo: b.readHoldInfo?.() ?? null, stall }))) log(`schedd: first-hour report written for batch ${id}`);
|
|
517
532
|
}
|
|
518
533
|
const sig = stall ? stall.ready.join(",") : "";
|
|
519
534
|
const last = b.lastProgressMs();
|
|
520
|
-
if (!isHosted && !cancelled && !reported && state?.pending?.length && last !== null && now - last > abandonMs && (!stall || rehostedStall.get(id) === sig)) {
|
|
535
|
+
if (!isHosted && !cancelled && !reported && state?.pending?.length && last !== null && now - last > abandonMs && (!stall || rehostedStall.get(id) === sig || readHealth(b.dir)?.stallRecovery?.sig === sig)) {
|
|
521
536
|
b.requestCancel({ reason: "abandoned" }); // #5531: idle past N days and not re-hostable: marked once (the cancel file ends the scan for it)
|
|
522
537
|
lateReport.abandoned.push(id);
|
|
523
538
|
log(`schedd: batch ${id} abandoned (not hosted, ${state.pending.length} pending, no progress for ${Math.round((now - last) / 86400_000)} days)`);
|
|
524
539
|
continue;
|
|
525
540
|
}
|
|
526
541
|
if (!stall) continue;
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
542
|
+
// #5806: the batch env is probed first (a PATH without gh/git/node stalls every resume the same way); the first stall of a
|
|
543
|
+
// ready set is recovered once (health.json stallRecovery survives a daemon restart), a repeat alerts with the probed cause.
|
|
544
|
+
let probe = null;
|
|
545
|
+
try { probe = plan.env ? probeEnv(mergeEnv(process.env, plan.env)) : null; } catch { probe = null; }
|
|
546
|
+
const decision = decideStallAction(stall, { recovery: readHealth(b.dir)?.stallRecovery ?? null, probe, hosted: isHosted });
|
|
547
|
+
if (decision.action === "alert") {
|
|
548
|
+
if (recordStallAlert(b, stall, { cause: decision.cause })) log(`schedd: batch ${id} needs you: ${stall.detail}${decision.cause ? `; probed: ${decision.cause}` : ""}`);
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
// #5806: a runner this daemon (re)started less than a window ago is not restarted yet (its first save may still be due)
|
|
552
|
+
if (decision.action === "restart-daemon" && now - (hosted.get(id)?.since ?? now) < stallMin * 60_000) continue;
|
|
553
|
+
rehostedStall.set(id, sig);
|
|
554
|
+
log(`schedd: ${recordStallRecovery(b, stall, { action: decision.action, sig })}`);
|
|
555
|
+
if (decision.action === "restart-daemon") { restartStall(id); return; }
|
|
556
|
+
log(`schedd: re-hosting batch ${id} (${stall.detail})`);
|
|
557
|
+
if (last !== null && now - last > abandonMs) lateReport.rehosted.push(id); // #5531
|
|
558
|
+
const started = host({ argv: ["--resume", id], cwd: process.cwd(), env: {}, keepBreaker: true });
|
|
559
|
+
starting.set(id, started);
|
|
560
|
+
started.catch((e) => { log(`schedd: re-host ${id} failed: ${e?.message ?? e}`); recordStallAlert(b, stall, { cause: `resume failed: ${String(e?.message ?? e).slice(0, 300)}` }); }).finally(() => starting.delete(id));
|
|
535
561
|
} catch { /* advisory: one unreadable batch never stops the watchdog */ }
|
|
536
562
|
}
|
|
537
563
|
}
|
package/bin/lean/schedd.test.mjs
CHANGED
|
@@ -13,7 +13,8 @@ import { findUnhosted, startDaemon, scheddPaths, connectDaemon, request, unitSta
|
|
|
13
13
|
import { schedDir } from "./sched.mjs";
|
|
14
14
|
import { readHeartbeat } from "./schedd-health.mjs";
|
|
15
15
|
import { formatTable, orchestrate } from "./orchestrate.mjs";
|
|
16
|
-
import { orchestrateFromCli, scheddFromCli } from "../engine-cli.mjs";
|
|
16
|
+
import { orchestrateFromCli, scheddFromCli, runBatch } from "../engine-cli.mjs";
|
|
17
|
+
import { probeBatchEnv } from "./lanecheck.mjs";
|
|
17
18
|
|
|
18
19
|
// #4503: this process, and the env its clients submit for their lanes, never resolve the host's `~/.forge/sched`.
|
|
19
20
|
process.env.FORGEDOCK_SCHED_DIR = tmpDir("schedd-home-");
|
|
@@ -485,6 +486,45 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
|
|
|
485
486
|
} finally { await d.close(); }
|
|
486
487
|
});
|
|
487
488
|
|
|
489
|
+
it("#5806: a hosted runner wedged in setup restarts the daemon once (decision logged); the same stall again alerts and never loops", async () => {
|
|
490
|
+
const dir = tmpDir("schedd-stall-setup-"), root = join(dir, "batches"), id = "b20261121-000000-5806";
|
|
491
|
+
const b = openBatch(root, id);
|
|
492
|
+
b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString() });
|
|
493
|
+
b.store.save({ v: 1, phase: "setup", setup: { read: 0, total: 2 }, order: [1, 2], deps: {}, results: {}, running: {}, pending: [1, 2], parallel: 2 });
|
|
494
|
+
const old = new Date(Date.now() - 10 * 60000);
|
|
495
|
+
utimesSync(join(b.dir, "state.json"), old, old);
|
|
496
|
+
const runBatch = async ({ sink }) => { sink.batch({ id, dir: b.dir }); return await new Promise(() => {}); }; // wedged in setup
|
|
497
|
+
const restarts = [], lines = [];
|
|
498
|
+
const d = await startDaemon({ dir, root, runBatch, log: (m) => lines.push(m), stallCheckMs: 50, stallMin: 0.001, restartForStall: (bid) => restarts.push(bid) });
|
|
499
|
+
try {
|
|
500
|
+
await until(() => restarts.length === 1, 8000);
|
|
501
|
+
assert.deepEqual(restarts, [id]);
|
|
502
|
+
assert.ok(lines.some((l) => /FORGE:DECISION batch .+ stall-recovery: restart the hosting schedd/.test(l)), lines.join("\n"));
|
|
503
|
+
assert.equal(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stallRecovery.action, "restart-daemon");
|
|
504
|
+
utimesSync(join(b.dir, "state.json"), old, old);
|
|
505
|
+
await until(() => readFileSync(join(b.dir, "health.json"), "utf8").includes("stalled again after auto-recovery"), 8000);
|
|
506
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
507
|
+
assert.equal(restarts.length, 1, "recovered once, then alerted");
|
|
508
|
+
assert.match(readFileSync(join(b.dir, "batch.log"), "utf8"), /BATCH UNHEALTHY .*\(stuck in setup, 0\/2 issues read\).*probed: stalled again after auto-recovery/);
|
|
509
|
+
} finally { await d.close(); }
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
it("#5806: an unhosted stalled batch whose pinned PATH lost gh/git/node is not resumed: it alerts with the probed cause", async () => {
|
|
513
|
+
const dir = tmpDir("schedd-stall-env-"), root = join(dir, "batches"), id = "b20261121-000001-5806";
|
|
514
|
+
const b = openBatch(root, id);
|
|
515
|
+
b.writePlan({ daemon: true, repo: "o/r", created: new Date().toISOString(), env: { PATH: join(dir, "bogus") } });
|
|
516
|
+
b.store.save({ v: 1, order: [1], results: {}, running: {}, pending: [1], parallel: 1 });
|
|
517
|
+
const old = new Date(Date.now() - 10 * 60000);
|
|
518
|
+
utimesSync(join(b.dir, "state.json"), old, old);
|
|
519
|
+
const calls = [];
|
|
520
|
+
const d = await startDaemon({ dir, root, runBatch: async ({ argv }) => { calls.push(argv); return await new Promise(() => {}); }, log: () => {}, resumeOnStart: false, stallCheckMs: 50, stallMin: 0.001 });
|
|
521
|
+
try {
|
|
522
|
+
await until(() => existsSync(join(b.dir, "health.json")) && readFileSync(join(b.dir, "health.json"), "utf8").includes("probed: batch env"), 8000);
|
|
523
|
+
assert.deepEqual(calls, [], "a resume would stall the same way");
|
|
524
|
+
assert.match(JSON.parse(readFileSync(join(b.dir, "health.json"), "utf8")).stall.cause, /gh, git, node not resolvable on the batch env PATH/);
|
|
525
|
+
} finally { await d.close(); }
|
|
526
|
+
});
|
|
527
|
+
|
|
488
528
|
it("#4917: a resume that leaves the waiting issue unadmitted (breaker tripped, retry-at passed) is not re-hosted again", async () => {
|
|
489
529
|
const dir = tmpDir("schedd-rehost-loop-"), root = join(dir, "batches"), id = "b20261031-000000-4918";
|
|
490
530
|
const calls = [];
|
|
@@ -788,6 +828,26 @@ await orchestrateFromCli(["1", "2", "--parallel", "2", "--repo", "o/r", "--no-pr
|
|
|
788
828
|
assert.deepEqual(redactEnv({ A: "1", GH_TOKEN: "x" }), { A: "1", GH_TOKEN: "<redacted>" });
|
|
789
829
|
});
|
|
790
830
|
|
|
831
|
+
it("#5806: sanitizePath splits a win32 PATH on `;` (splitting on `:` left one bogus entry pinned)", () => {
|
|
832
|
+
const win = "C:\\Windows\\system32;C:\\Program Files\\GitHub CLI;C:\\gone";
|
|
833
|
+
const exists = (d) => d !== "C:\\gone";
|
|
834
|
+
assert.equal(sanitizePath(win, { sep: ";", exists, tmpRoots: [] }), "C:\\Windows\\system32;C:\\Program Files\\GitHub CLI");
|
|
835
|
+
assert.equal(sanitizePath("/usr/bin:/gone", { sep: ":", exists: (d) => d !== "/gone", tmpRoots: [] }), "/usr/bin");
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
it("#5806: a create or resume whose pinned env PATH cannot resolve gh/git/node fails fast with that reason", async () => {
|
|
839
|
+
const root = tmpDir("schedd-probe-"), bogus = join(root, "bogus");
|
|
840
|
+
const deps = { allowTmpfs: true, batchRoot: root, probeEnv: probeBatchEnv, io: { gh: async () => "o/r\n" } };
|
|
841
|
+
const sink = { batch: () => {}, row: () => {}, line: () => {} };
|
|
842
|
+
await assert.rejects(runBatch({ argv: ["1", "--repo", "o/r"], cwd: root, env: { PATH: bogus }, sink, deps, daemon: true }),
|
|
843
|
+
/batch not started: gh, git, node not resolvable on the batch env PATH \(empty\)/, "the sanitised pin drops the missing dir");
|
|
844
|
+
assert.deepEqual(listBatches(root), [], "no batch dir is left behind");
|
|
845
|
+
const b = openBatch(root, "b-env");
|
|
846
|
+
b.writePlan({ v: 1, id: "b-env", argv: ["1", "--repo", "o/r"], repo: "o/r", cwd: root, created: new Date().toISOString(), daemon: true, env: { PATH: bogus } });
|
|
847
|
+
await assert.rejects(runBatch({ argv: ["--resume", "b-env"], cwd: root, sink, deps, daemon: true }),
|
|
848
|
+
/batch b-env cannot resume: gh, git, node not resolvable on the batch env PATH \(1 entry: .*bogus\); fix its pin with forgedock orchestrate --set-env b-env PATH=/);
|
|
849
|
+
});
|
|
850
|
+
|
|
791
851
|
it("#4691: plan.json holds none of the session token, temp PATH dir or excluded wrapper dir; --show/--set/--unset-env edit it", async () => {
|
|
792
852
|
const h = host();
|
|
793
853
|
const work = tmpDir("schedd-pin-");
|