forgedock 1.66.0 → 1.68.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 +3 -0
- package/bin/engine/outcome-codes.mjs +2 -0
- package/bin/engine-cli.mjs +193 -27
- package/bin/engine.mjs +10 -0
- package/bin/forgedock.mjs +24 -1
- package/bin/help-text.mjs +4 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/admission.mjs +21 -0
- package/bin/lean/admission.test.mjs +30 -0
- package/bin/lean/advisory.test.mjs +64 -0
- package/bin/lean/amendment-schema.mjs +30 -0
- package/bin/lean/attempts.mjs +162 -0
- package/bin/lean/attempts.test.mjs +141 -0
- package/bin/lean/basered.mjs +81 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +20 -12
- package/bin/lean/batch-health.test.mjs +55 -11
- package/bin/lean/batch.mjs +45 -0
- package/bin/lean/batch.test.mjs +105 -5
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/ci-gate.mjs +2 -90
- package/bin/lean/ci-gate.test.mjs +1 -127
- package/bin/lean/ci-precheck.mjs +25 -8
- package/bin/lean/ci-precheck.test.mjs +24 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/clear-breaker.test.mjs +4 -3
- package/bin/lean/commentstate.mjs +46 -0
- package/bin/lean/commentstate.test.mjs +43 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +13 -8
- package/bin/lean/conformance.mjs +73 -181
- package/bin/lean/conformance.test.mjs +61 -345
- package/bin/lean/depcache.mjs +100 -10
- package/bin/lean/depcache.test.mjs +105 -0
- package/bin/lean/docsgate.mjs +0 -32
- package/bin/lean/docsgate.test.mjs +2 -23
- package/bin/lean/effects-cap.test.mjs +9 -1
- package/bin/lean/effects-killtree.test.mjs +35 -0
- package/bin/lean/effects.mjs +42 -24
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/engine-readmit.test.mjs +35 -0
- package/bin/lean/envgap.mjs +93 -0
- package/bin/lean/envgap.test.mjs +53 -0
- package/bin/lean/execution.mjs +41 -17
- package/bin/lean/execution.test.mjs +58 -0
- package/bin/lean/failure-census.mjs +170 -0
- package/bin/lean/failure-census.test.mjs +59 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/guardgate.test.mjs +2 -3
- package/bin/lean/heavy.mjs +33 -4
- package/bin/lean/heavy.test.mjs +38 -6
- package/bin/lean/hotarea.mjs +0 -36
- package/bin/lean/hotarea.test.mjs +1 -22
- package/bin/lean/issuewatch-verify.mjs +19 -4
- package/bin/lean/issuewatch.mjs +21 -4
- package/bin/lean/issuewatch.test.mjs +48 -1
- package/bin/lean/lane-audit-gap.mjs +66 -0
- package/bin/lean/lane-audit-gap.test.mjs +59 -0
- package/bin/lean/lane-audit-llm.mjs +5 -0
- package/bin/lean/lane-audit-query.mjs +47 -0
- package/bin/lean/lane-audit-query.test.mjs +44 -0
- package/bin/lean/lane-audit-signatures.mjs +33 -0
- package/bin/lean/lane-audit.mjs +110 -0
- package/bin/lean/lane-audit.test.mjs +97 -0
- package/bin/lean/lane-recovery.test.mjs +33 -0
- package/bin/lean/lanecheck.mjs +5 -3
- package/bin/lean/lanecheck.test.mjs +6 -0
- package/bin/lean/lean.mjs +311 -154
- package/bin/lean/lean.test.mjs +530 -223
- package/bin/lean/limits.mjs +17 -0
- package/bin/lean/limits.test.mjs +15 -1
- package/bin/lean/live-execution.mjs +21 -2
- package/bin/lean/live-execution.test.mjs +39 -0
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +82 -0
- package/bin/lean/orchestrate-envhold.test.mjs +47 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
- package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
- package/bin/lean/orchestrate-pause.test.mjs +76 -1
- package/bin/lean/orchestrate-reconcile.test.mjs +164 -0
- package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
- package/bin/lean/orchestrate-stacking.test.mjs +10 -0
- package/bin/lean/orchestrate.mjs +344 -45
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/postdeploy-check.test.mjs +1 -3
- package/bin/lean/precheck.mjs +20 -0
- package/bin/lean/preflight.mjs +100 -11
- package/bin/lean/preflight.test.mjs +44 -4
- package/bin/lean/prompts.mjs +13 -28
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +6 -112
- package/bin/lean/recurrence.test.mjs +11 -92
- package/bin/lean/release-flakes.mjs +14 -2
- package/bin/lean/release-flakes.test.mjs +17 -1
- package/bin/lean/release-ledger.mjs +19 -1
- package/bin/lean/release-ledger.test.mjs +23 -0
- package/bin/lean/release-preflight.mjs +28 -0
- package/bin/lean/release-preflight.test.mjs +42 -1
- package/bin/lean/release-review.mjs +40 -5
- package/bin/lean/release-review.test.mjs +43 -2
- package/bin/lean/release.mjs +43 -14
- package/bin/lean/release.test.mjs +32 -0
- package/bin/lean/retry.mjs +1 -1
- package/bin/lean/retry.test.mjs +6 -1
- package/bin/lean/rotator.mjs +9 -0
- package/bin/lean/rotator.test.mjs +11 -1
- package/bin/lean/sandbox-remote.mjs +49 -11
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +4 -4
- package/bin/lean/schedd-health.test.mjs +8 -4
- package/bin/lean/schedd.mjs +45 -8
- package/bin/lean/schedd.test.mjs +120 -7
- package/bin/lean/selfreview.mjs +1 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +40 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/validate-catalog.mjs +108 -0
- package/bin/lean/validate-catalog.test.mjs +46 -1
- package/bin/lean/verify.mjs +3 -2
- package/bin/pool/affinity.test.mjs +91 -0
- package/bin/pool/agent.mjs +144 -10
- package/bin/pool/cache-sweep.mjs +31 -10
- package/bin/pool/ci-autoscale.mjs +160 -0
- package/bin/pool/cli.mjs +53 -9
- package/bin/pool/docker.mjs +3 -0
- package/bin/pool/engine-placement.test.mjs +94 -0
- package/bin/pool/lane-target.mjs +41 -0
- package/bin/pool/lane-tools.mjs +26 -0
- package/bin/pool/lane-tools.test.mjs +9 -0
- package/bin/pool/mirror-seed.mjs +15 -11
- package/bin/pool/router.mjs +88 -32
- package/bin/pool/version.mjs +29 -2
- package/bin/review-staging.mjs +11 -3
- package/bin/runner.mjs +59 -11
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/bin/stats/release.mjs +7 -0
- package/bin/stats/release.test.mjs +20 -0
- package/bin/stats/scorecard.mjs +187 -0
- package/bin/stats/scorecard.test.mjs +89 -0
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +41 -0
- package/docs/OUTCOME-CODES.md +2 -0
- package/docs/STATS.md +17 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +14 -2
- package/pool/image/manifest.json +25 -0
- package/pool/image/mirror.sh +11 -2
- package/pool/install/install-agent.ps1 +11 -4
- package/scripts/check-devdocs-freshness.sh +1 -1
- package/scripts/ci-local/adapters/github-actions.mjs +8 -0
- package/scripts/ci-local/cli.mjs +1 -1
- package/scripts/ci-local/plan.mjs +3 -2
- package/scripts/ci-local.test.sh +11 -0
- package/scripts/failure-census.mjs +67 -0
- package/scripts/review-finalize.sh +5 -5
- package/scripts/review-finalize.test.sh +8 -1
- package/scripts/verify-phase-trail.sh +11 -0
- package/scripts/verify-phase-trail.test.sh +9 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
3
|
import { describe, it } from "node:test";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
|
-
import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, realSeam, withIntegrityMarker, TEST_GATE_SKIP_NO_TESTS, testGatePrompt, integrationTestCount, resolveSkillName } from "./release-review.mjs";
|
|
5
|
+
import { reviewStep, fixStep, missingReviewers, SPEC_PANEL, MAX_DELTA_PASSES, realSeam, withIntegrityMarker, TEST_GATE_SKIP_NO_TESTS, testGatePrompt, integrationTestCount, resolveSkillName, mapLimit, reviewMaxParallel, defaultReviewParallel, REVIEW_NICE } from "./release-review.mjs";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { EventEmitter } from "node:events";
|
|
8
8
|
import { reviewStagingJson, classifyChecks, cancelOnlyChecks } from "../review-staging.mjs";
|
|
@@ -12,7 +12,7 @@ const manifest = (head, delta = null) => ({ pr: 7, headSha: head, bundle: [1, 2]
|
|
|
12
12
|
const fin = (extra = {}) => ({ code: 0, data: { head: H1, toFile: [], notes: [], ...extra }, lines: [] });
|
|
13
13
|
|
|
14
14
|
/** Seam fake: `heads` is what headOf answers in turn; `fins` what finalize answers in turn. */
|
|
15
|
-
function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [], jobs = [], gatePlan = { clusters: 1, skill: "forgedock:test-gate" } } = {}) {
|
|
15
|
+
function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [], jobs = [], gatePlan = { clusters: 1, skill: "forgedock:test-gate" }, maxParallel = 2 } = {}) {
|
|
16
16
|
const log = [], agents = [], gateSaved = [], agentCalls = [];
|
|
17
17
|
let h = 0, f = 0, l = 0, n = 100;
|
|
18
18
|
return {
|
|
@@ -25,6 +25,7 @@ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [], jobs = []
|
|
|
25
25
|
markLaunched: (file, domains) => log.push(["launched", domains]),
|
|
26
26
|
saveTestGate: (pr, text) => { gateSaved.push(text); return "/sd/7_test_gate_output.txt"; },
|
|
27
27
|
testGatePlan: async () => gatePlan,
|
|
28
|
+
maxParallel: () => maxParallel,
|
|
28
29
|
runAgent: async (a) => { agentCalls.push(a); agents.push(a.role + (a.prompt.includes("findings block required") ? ":reask" : "")); return { text: "ok" }; },
|
|
29
30
|
fileIssue: async ({ item }) => { log.push(["file", item.title]); return n++; },
|
|
30
31
|
failedJobs: async () => jobs,
|
|
@@ -37,6 +38,35 @@ function fakeSeam({ heads = [H1], fins = [fin()], summary, lanes = [], jobs = []
|
|
|
37
38
|
}
|
|
38
39
|
const ctx = (seam, steps = {}) => ({ io: { review: seam }, repo: "o/r", def: "main", staging: "staging", state: { steps: { "release-pr": { result: { pr: 7 } }, ...steps } }, save() {} });
|
|
39
40
|
|
|
41
|
+
describe("#6098 reviewer fan-out is capped and niced", () => {
|
|
42
|
+
it("mapLimit never has more than the cap in flight and keeps order", async () => {
|
|
43
|
+
let live = 0, peak = 0;
|
|
44
|
+
const out = await mapLimit([1, 2, 3, 4, 5, 6, 7, 8], 3, async (x) => { live++; peak = Math.max(peak, live); await new Promise((r) => setTimeout(r, 5)); live--; return x * 2; });
|
|
45
|
+
assert.equal(peak, 3); assert.deepEqual(out, [2, 4, 6, 8, 10, 12, 14, 16]);
|
|
46
|
+
});
|
|
47
|
+
it("review.max_parallel is read from forge.yaml; the default is max(2, cores/2)", () => {
|
|
48
|
+
assert.equal(reviewMaxParallel("a: 1\nreview:\n depth:\n x: 1\n max_parallel: 3 # cap\nother:\n max_parallel: 9\n"), 3);
|
|
49
|
+
assert.equal(reviewMaxParallel("other:\n max_parallel: 9\n"), null);
|
|
50
|
+
assert.equal(reviewMaxParallel("review:\n max_parallel: 0\n"), null);
|
|
51
|
+
assert.equal(defaultReviewParallel(4), 2); assert.equal(defaultReviewParallel(2), 2); assert.equal(defaultReviewParallel(16), 8);
|
|
52
|
+
});
|
|
53
|
+
it("the panel never runs more reviewers at once than the cap", async () => {
|
|
54
|
+
const s = fakeSeam({ maxParallel: 2 });
|
|
55
|
+
let live = 0, peak = 0;
|
|
56
|
+
s.runAgent = async (a) => { live++; peak = Math.max(peak, live); await new Promise((r) => setTimeout(r, 5)); live--; return { text: "ok" }; };
|
|
57
|
+
await reviewStep(ctx(s));
|
|
58
|
+
assert.ok(SPEC_PANEL.length + 1 > 2, "the panel is larger than the cap");
|
|
59
|
+
assert.equal(peak, 2);
|
|
60
|
+
});
|
|
61
|
+
it("reviewer processes are lowered to nice 19 / ionice idle on spawn", async () => {
|
|
62
|
+
let spec = null;
|
|
63
|
+
const real = realSeam({ repo: "o/r", def: "main", env: {}, cwd: "/tmp", makeRunner: () => async (a) => { spec = a; return { text: "" }; } });
|
|
64
|
+
await real.runAgent({ role: "release-review-security", issue: 7, prompt: "p" });
|
|
65
|
+
assert.equal(typeof spec.onSpawn, "function"); assert.equal(REVIEW_NICE, 19);
|
|
66
|
+
assert.equal(spec.onSpawn({ pid: -1 }), false); // an invalid pid is a no-op, never a throw
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
40
70
|
describe("reviewStep", () => {
|
|
41
71
|
it("reviewer sessions run the release job's own forgedock build", async () => {
|
|
42
72
|
let seen = null;
|
|
@@ -166,6 +196,17 @@ describe("fixStep", () => {
|
|
|
166
196
|
assert.equal(c.state.fixloop.heads[H2].rounds, 1, "the round is counted per head sha");
|
|
167
197
|
});
|
|
168
198
|
|
|
199
|
+
it("#6013: failures the staging-health gate named ride in the one fix brief with the release-PR round's failures", async () => {
|
|
200
|
+
const s = fakeSeam({ heads: [H2], jobs: [{ name: "lint", conclusion: "failure", log: "bad" }] });
|
|
201
|
+
let brief = "";
|
|
202
|
+
s.fileFixIssue = async (a) => { brief = a.brief; return 100; };
|
|
203
|
+
const c = ctx(s, { review: { result: { ...failed, ciFailing: 1 } } });
|
|
204
|
+
c.state.knownFailures = [{ name: "black", cause: "regression" }, { name: "lint", cause: "regression" }];
|
|
205
|
+
await fixStep(c);
|
|
206
|
+
assert.match(brief, /ci:black/);
|
|
207
|
+
assert.equal((brief.match(/ci:lint/g) ?? []).length, 1);
|
|
208
|
+
});
|
|
209
|
+
|
|
169
210
|
it("is bounded: one round (ci.fix.max_rounds default 1), then HELD with an owner ask for a non-flake, non-regression failure", async () => {
|
|
170
211
|
const bad = { code: 0, data: { verdict: "BLOCK DEPLOY", marker: "FORGE:GATE_FAILURE", ciFailing: 0 }, lines: [] };
|
|
171
212
|
const s = fakeSeam({ heads: [H2], summary: bad, fins: [fin({ toFile: [{ title: "x", severity: "CRITICAL" }] })] });
|
package/bin/lean/release.mjs
CHANGED
|
@@ -26,14 +26,14 @@ import { budgetReportLine, releaseRuns, detectBudget, readCiPolicy } from "./ci-
|
|
|
26
26
|
import { parseNightlyConfig, readNightly, blocksRelease, fileNightlyRed } from "./release-nightly.mjs";
|
|
27
27
|
import { parseBudgetConfig, applyOnExceed, waveReport, trailingMedian, historyFromRoot, gateHistoryFromRoot, releaseMinutes } from "./release-minutes.mjs";
|
|
28
28
|
import { cutSnapshot, writeRecord, checkChain, verifyRelease, defaultBehind, DEFAULT_PATTERN } from "./release-snapshot.mjs";
|
|
29
|
-
import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat } from "./release-ledger.mjs";
|
|
29
|
+
import { createReleaseLedger, writeRelease, readLedger, acquireLease, heartbeat, recordReleaseRound } from "./release-ledger.mjs";
|
|
30
30
|
import { fenced, epochTrailer } from "./release-fence.mjs";
|
|
31
31
|
import { holdCheck, exemptionsSection, runControl, VERBS as CONTROL_VERBS } from "./release-control.mjs";
|
|
32
32
|
import { parseFlakeConfig, classifyFailure, planRerun, flakeEntry, recordFlakes, readFlakes } from "./release-flakes.mjs";
|
|
33
33
|
import { readActive } from "./release-ledger.mjs";
|
|
34
34
|
import { statusFromCli, policyFromYaml } from "./release-status.mjs";
|
|
35
35
|
import { parseFixConfig } from "./release-fixloop.mjs";
|
|
36
|
-
import { hostPreflightStep, markReadyStep, parsePreflightConfig } from "./release-preflight.mjs";
|
|
36
|
+
import { hostPreflightStep, markReadyStep, stagingHealthStep, parsePreflightConfig } from "./release-preflight.mjs";
|
|
37
37
|
import { roleRefusal } from "./release-credentials.mjs";
|
|
38
38
|
import { mergeGuard } from "./release-gate.mjs";
|
|
39
39
|
|
|
@@ -130,7 +130,7 @@ const snapshotKeys = (r) => {
|
|
|
130
130
|
export const isSnapshot = (config) => config?.mode === "snapshot";
|
|
131
131
|
|
|
132
132
|
/** `{rehearsal}` / `{preflight}` only when configured, so the config of a repo without them keeps its shape. */
|
|
133
|
-
const optKeys = (r) => { const rehearsal = parseRehearsalConfig(r), preflight = parsePreflightConfig(r); return { ...(rehearsal ? { rehearsal } : {}), ...(preflight ? { preflight } : {}) }; };
|
|
133
|
+
const optKeys = (r) => { const rehearsal = parseRehearsalConfig(r), preflight = parsePreflightConfig(r); return { ...(r?.allow_red_staging === true || String(r?.allow_red_staging).toLowerCase() === "true" ? { allowRedStaging: true } : {}), ...(rehearsal ? { rehearsal } : {}), ...(preflight ? { preflight } : {}) }; };
|
|
134
134
|
|
|
135
135
|
const json = (s) => JSON.parse(String(s || "null"));
|
|
136
136
|
|
|
@@ -143,10 +143,26 @@ export async function bundleList({ io, repo, head, base }) {
|
|
|
143
143
|
|
|
144
144
|
const bundleBody = (list) => `## Release bundle\n\n${list.length ? list.map((p) => `- #${p.number} ${p.title}`).join("\n") : "_No merged PRs found since the last release._"}\n`;
|
|
145
145
|
|
|
146
|
+
/** #6013: one `state.rounds` entry per distinct head and outcome (a resume does not double-count). */
|
|
147
|
+
function noteRound(ctx, r) {
|
|
148
|
+
const { state, io } = ctx;
|
|
149
|
+
if ((state.rounds ?? []).some((x) => x.head === r.head && x.outcome === r.outcome)) return;
|
|
150
|
+
const at = new Date(io.now?.() ?? Date.now()).toISOString();
|
|
151
|
+
recordReleaseRound(state, { ...r, startedAt: at, endedAt: at });
|
|
152
|
+
ctx.save();
|
|
153
|
+
}
|
|
154
|
+
|
|
146
155
|
async function preflightStep(ctx) {
|
|
147
156
|
const { io, repo, state, staging } = ctx;
|
|
148
157
|
// Snapshot mode: lanes keep merging to staging; the release is cut from a fixed SHA, so nothing is refused or held (#5276).
|
|
149
|
-
|
|
158
|
+
const health = await stagingHealthStep(ctx);
|
|
159
|
+
if (health.refused) {
|
|
160
|
+
state.knownFailures = health.failed;
|
|
161
|
+
noteRound(ctx, { head: health.head, outcome: "red-staging", cause: health.failed.some((f) => f.cause === "regression") || !health.failed.length ? "regression" : "runner" });
|
|
162
|
+
ctx.save(); return { refused: health.refused, failed: health.failed }; }
|
|
163
|
+
state.knownFailures = health.failed ?? [];
|
|
164
|
+
const warn = health.warning ? { warning: health.warning } : {};
|
|
165
|
+
if (isSnapshot(ctx.config)) return { snapshot: true, held: 0, ...warn };
|
|
150
166
|
const lanes = await io.runningLanes(repo);
|
|
151
167
|
if (lanes.length) return { refused: `lanes of ${repo} are running (${lanes.map((l) => `${l.batch}#${l.issue}`).join(", ")}); wait or cancel them` };
|
|
152
168
|
const open = json(await io.gh(["pr", "list", "--repo", repo, "--base", staging, "--state", "open", "--json", "number"])) ?? [];
|
|
@@ -159,7 +175,7 @@ async function preflightStep(ctx) {
|
|
|
159
175
|
ctx.save();
|
|
160
176
|
await io.setParallel(b.id, 1);
|
|
161
177
|
}
|
|
162
|
-
return { held: state.held.length };
|
|
178
|
+
return { held: state.held.length, ...warn };
|
|
163
179
|
}
|
|
164
180
|
|
|
165
181
|
/** Restore every held batch to its recorded K; best effort, recorded as it goes. */
|
|
@@ -185,14 +201,15 @@ async function snapshotPrStep(ctx) {
|
|
|
185
201
|
}
|
|
186
202
|
const { branch } = state.release;
|
|
187
203
|
const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", branch, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
|
|
188
|
-
if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true, branch };
|
|
204
|
+
if (found) { noteRound(ctx, { pr: found.number, head: found.headRefOid, outcome: "cut" }); return { pr: found.number, head: found.headRefOid, url: found.url, reused: true, branch }; }
|
|
189
205
|
const list = state.releaseBundle ?? [];
|
|
190
|
-
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx)])).trim();
|
|
206
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", branch, "--title", `Release: ${branch} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx) + await scorecardBody(ctx)])).trim();
|
|
191
207
|
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
192
208
|
if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
|
|
193
209
|
state.steps["release-pr"] = { done: false, result: { pr: n } }; // writeRecord reads the PR number from here
|
|
194
210
|
await writeRecord(ctx);
|
|
195
211
|
const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
|
|
212
|
+
noteRound(ctx, { pr: n, head: v?.headRefOid, outcome: "cut" });
|
|
196
213
|
return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length, branch };
|
|
197
214
|
}
|
|
198
215
|
|
|
@@ -202,13 +219,23 @@ async function releasePrStep(ctx) {
|
|
|
202
219
|
const found = json(await io.gh(["pr", "list", "--repo", repo, "--base", def, "--head", staging, "--state", "open", "--json", "number,headRefOid,url"]))?.[0];
|
|
203
220
|
if (found) return { pr: found.number, head: found.headRefOid, url: found.url, reused: true };
|
|
204
221
|
const list = await bundleList({ io, repo, head: staging, base: def });
|
|
205
|
-
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
|
|
222
|
+
const url = String(await io.gh(["pr", "create", "--repo", repo, "--base", def, "--head", staging, "--title", `Release: ${staging} -> ${def}`, "--body", bundleBody(list) + await exemptionBody(ctx) + await scorecardBody(ctx), ...(ctx.config.preflight ? ["--draft"] : [])])).trim();
|
|
206
223
|
const n = Number(/\/pull\/(\d+)/.exec(url)?.[1]);
|
|
207
224
|
if (!Number.isSafeInteger(n)) throw new Error(`gh pr create returned no PR url: ${url}`);
|
|
208
225
|
const v = json(await io.gh(["pr", "view", String(n), "--repo", repo, "--json", "headRefOid"]));
|
|
209
226
|
return { pr: n, head: v?.headRefOid, url, reused: false, bundle: list.length };
|
|
210
227
|
}
|
|
211
228
|
|
|
229
|
+
/** The per-release scorecard (#6084) as a PR-body section with its regressions line; "" on any error (never blocks the PR). */
|
|
230
|
+
async function scorecardBody({ io, repo, state }) {
|
|
231
|
+
try {
|
|
232
|
+
const sc = io.scorecard ? await io.scorecard({ repo, release: state.release?.version ?? state.id }) : await (await import("../stats/scorecard.mjs")).gatherScorecard({ repo, release: state.release?.version ?? state.id }, { gh: io.gh, useCache: false });
|
|
233
|
+
if (!sc) return "";
|
|
234
|
+
const { renderScorecard } = await import("../stats/scorecard.mjs");
|
|
235
|
+
return `\n\n${renderScorecard(sc)}\n`;
|
|
236
|
+
} catch { return ""; }
|
|
237
|
+
}
|
|
238
|
+
|
|
212
239
|
/** The live operator exemptions as a PR-body section (#5568, I20); "" when unmanaged, none, or `_active` is unreadable. */
|
|
213
240
|
async function exemptionBody({ io, repo, config }) {
|
|
214
241
|
if (!config.managed || !io.api) return "";
|
|
@@ -255,21 +282,22 @@ export async function rerunInfraFlakes({ io, repo, head, fence, policy }) {
|
|
|
255
282
|
const cfg = parseFlakeConfig(policy);
|
|
256
283
|
if (!fence?.lctx || !(cfg.rerunBudgetMin > 0)) return out;
|
|
257
284
|
const prior = await readFlakes(fence.lctx), done = prior.filter((f) => f.rerun).map((f) => `${f.sha}:${f.check}`);
|
|
258
|
-
const runs = json(await io.gh(["run", "list", "--repo", repo, "--commit", head, "--status", "failure", "--json", "databaseId,name", "--limit", "20"])) ?? [];
|
|
285
|
+
const runs = json(await io.gh(["run", "list", "--repo", repo, "--commit", head, "--status", "failure", "--json", "databaseId,name,attempt", "--limit", "20"])) ?? [];
|
|
259
286
|
const at = new Date(io.now?.() ?? Date.now()).toISOString(), entries = [];
|
|
260
287
|
let spentMin = 0;
|
|
261
288
|
for (const r of runs) {
|
|
262
289
|
const log = String(await io.gh(["run", "view", String(r.databaseId), "--repo", repo, "--log-failed"]).catch(() => "")).slice(-20_000);
|
|
263
290
|
const c = classifyFailure(log);
|
|
264
|
-
const [d] = planRerun({ jobs: [{ key: `${head}:${r.name}`, name: r.name, class: c.class }], done, spentMin, budgetMin: cfg.rerunBudgetMin });
|
|
291
|
+
const [d] = planRerun({ jobs: [{ key: `${head}:${r.name}`, name: r.name, class: c.class, attempt: r.attempt }], done, spentMin, budgetMin: cfg.rerunBudgetMin });
|
|
265
292
|
if (d.rerun) {
|
|
266
293
|
const f = await fenced(fence, { action: "rerun", key: `rerun-failed:${r.databaseId}` }, () => io.gh(["run", "rerun", String(r.databaseId), "--repo", repo, "--failed"]));
|
|
267
294
|
if (f.refused) { out.skipped.push({ name: r.name, why: f.refused }); continue; }
|
|
268
295
|
out.reran.push(r.name);
|
|
269
|
-
} else out.skipped.push({ name: r.name, why: d.why });
|
|
270
|
-
entries.push(flakeEntry({ check: r.name, signature: c.signature, kind: c.class === "infra" ? "infra" : "decision", sha: head, runIds: [r.databaseId], at, rerun: d.rerun }));
|
|
296
|
+
} else out.skipped.push({ name: r.name, why: d.why, ...(d.capped ? { capped: true } : {}) });
|
|
297
|
+
entries.push(flakeEntry({ check: r.name, signature: c.signature, kind: c.class === "infra" ? "infra" : "decision", sha: head, runIds: [r.databaseId], at, rerun: d.rerun, attempt: r.attempt, reuseForfeited: d.rerun }));
|
|
271
298
|
}
|
|
272
|
-
|
|
299
|
+
// #6014: a rerun entry carries the attempt count and the forfeited reuse; a cap refusal is a visible decision entry, never an infra one
|
|
300
|
+
await recordFlakes(fence.lctx, entries.filter((e) => e.kind === "infra" || e.attempt != null && !e.rerun && out.skipped.some((s) => s.capped && s.name === e.check)));
|
|
273
301
|
} catch { /* best effort */ }
|
|
274
302
|
return out;
|
|
275
303
|
}
|
|
@@ -309,7 +337,8 @@ async function promotionStep(ctx) {
|
|
|
309
337
|
if (gate.deployGate === "failure" && ctx.config.managed && io.git) { // #5568: policy loaded lazily (release-config imports this module)
|
|
310
338
|
const { readPolicy } = await import("./release-config.mjs");
|
|
311
339
|
const policy = readPolicy({ io, defaultBranch: ctx.def }).policy;
|
|
312
|
-
await rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy });
|
|
340
|
+
const rr = await rerunInfraFlakes({ io, repo, head, fence: ctx.fence, policy });
|
|
341
|
+
if (rr.reran.length) noteRound(ctx, { pr, head, outcome: "rerun-flake", cause: "flake" }); // #6013: a rerun that clears an infra failure is a flake round
|
|
313
342
|
}
|
|
314
343
|
const cmd = `gh pr merge ${pr} --repo ${repo} --merge --match-head-commit ${head}`;
|
|
315
344
|
if (!opts.merge && !ctx.config.autoMerge) { io.print(`GATE_PASS on #${pr}. Merge when ready:\n ${cmd}`); return { stopped: true, why: "GATE_PASS; promotion is opt-in (--merge or release.auto_merge)", cmd, head, gate }; }
|
|
@@ -42,6 +42,7 @@ function fakeIo(world = {}) {
|
|
|
42
42
|
throw new Error(`unexpected gh ${j}`);
|
|
43
43
|
},
|
|
44
44
|
};
|
|
45
|
+
if (w.scorecard) io.scorecard = w.scorecard;
|
|
45
46
|
return io;
|
|
46
47
|
}
|
|
47
48
|
const ok = async () => ({ ok: true });
|
|
@@ -191,6 +192,19 @@ describe("release job (#5211)", () => {
|
|
|
191
192
|
assert.ok(create && create.includes("--head") && create.includes("staging") && create.includes("main"));
|
|
192
193
|
});
|
|
193
194
|
|
|
195
|
+
it("#6084: the release PR body carries the scorecard with regressions; a scorecard failure still creates the PR", async () => {
|
|
196
|
+
const body = (c) => c[c.indexOf("--body") + 1];
|
|
197
|
+
const sc = { release: "v2", against: "v1", minN: 10, values: { first_pass_rate: 0.5 }, previous: { first_pass_rate: 0.9 }, verdicts: { first_pass_rate: "regressed" }, regressions: ["first_pass_rate"] };
|
|
198
|
+
const a = await promote({ releasePr: [], scorecard: async () => sc });
|
|
199
|
+
const withCard = body(a.io.calls.find((c) => c[1] === "create"));
|
|
200
|
+
assert.match(withCard, /Release scorecard v2/);
|
|
201
|
+
assert.match(withCard, /Regressions vs v1: first-pass merge rate/);
|
|
202
|
+
const b = await promote({ releasePr: [], scorecard: async () => { throw new Error("boom"); } });
|
|
203
|
+
const create = b.io.calls.find((c) => c[1] === "create");
|
|
204
|
+
assert.ok(create);
|
|
205
|
+
assert.doesNotMatch(body(create), /scorecard/i);
|
|
206
|
+
});
|
|
207
|
+
|
|
194
208
|
it("R5: a killed job resumes from the last completed step", async () => {
|
|
195
209
|
const io = fakeIo(), root = tmp(), id = newReleaseId();
|
|
196
210
|
const mod = await import("./release.mjs");
|
|
@@ -594,3 +608,21 @@ describe("release start|go routing (#5571)", () => {
|
|
|
594
608
|
await assert.rejects(releaseFromCli(["start", "--wave", "x"], opts([], [])), /--wave/);
|
|
595
609
|
});
|
|
596
610
|
});
|
|
611
|
+
|
|
612
|
+
describe("preflight staging-health gate (#6013)", () => {
|
|
613
|
+
const snap = { mode: "snapshot" };
|
|
614
|
+
const world = (runs) => ({ pm: (a) => (a[0] === "api" && /check-runs/.test(a[1]) ? JSON.stringify(runs) : undefined) });
|
|
615
|
+
it("refuses a snapshot cut on a red staging head and proceeds when green", async () => {
|
|
616
|
+
const mod = await import("./release.mjs");
|
|
617
|
+
const root = tmp(), id = newReleaseId();
|
|
618
|
+
const base = (io) => ({ io, repo: REPO, root, mounts: DISK, id, opts: {}, config: snap, branches: { staging: "staging", default: "main" }, steps: mod.withStubs({ "release-pr": ok, review: ok, fixes: ok, promotion: ok, "post-merge": ok }) });
|
|
619
|
+
const reds = await mod.runRelease(base(fakeIo(world([{ name: "black", status: "completed", conclusion: "failure", text: "" }]))));
|
|
620
|
+
assert.equal(reds.status, "refused");
|
|
621
|
+
assert.match(JSON.stringify(reds), /black/);
|
|
622
|
+
const saved = JSON.parse(readFileSync(join(root, id, "state.json"), "utf8").toString());
|
|
623
|
+
assert.equal(saved.rounds[0].outcome, "red-staging");
|
|
624
|
+
assert.equal(saved.rounds[0].cause, "regression");
|
|
625
|
+
const green = await mod.runRelease({ ...base(fakeIo(world([{ name: "black", status: "completed", conclusion: "success", text: "" }]))), id: newReleaseId() });
|
|
626
|
+
assert.notEqual(green.status, "refused");
|
|
627
|
+
});
|
|
628
|
+
});
|
package/bin/lean/retry.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
export const PUSH_TRANSIENT_RE = /remote unpack failed|index-pack failed|RPC failed|unexpected disconnect|early EOF|the remote end hung up|HTTP\/?\s?5\d\d|returned error: 5\d\d|\b50[0234]\b|internal server error|bad gateway|service unavailable|gateway time-?out|connection (?:reset|timed out|refused)|timed out|could not resolve host|broken pipe|ETIMEDOUT|ECONNRESET|temporarily unavailable|\[remote rejected\][^\n]*\(failed\)|unable to write file|unable to create temporary object|unpacker error|failed to write object/i;
|
|
6
6
|
export const PUSH_PERMANENT_RE = /protected branch|GH006|GH013|repository rule violations|permission (?:denied|to .* denied)|denied to|\b403\b|authentication failed|not allowed|hook declined|pre-receive hook declined|\[rejected\]|non-fast-forward|fetch first/i;
|
|
7
|
-
export const GH_TRANSIENT_RE = /HTTP 5\d\d|\b50[0234]\b|secondary rate limit|rate limit exceeded|abuse detection|something went wrong|internal server error|bad gateway|service unavailable|ETIMEDOUT|ECONNRESET|connection reset|timed out|\bEOF\b|temporarily unavailable/i;
|
|
7
|
+
export const GH_TRANSIENT_RE = /HTTP 5\d\d|\b50[0234]\b|secondary rate limit|rate limit exceeded|abuse detection|something went wrong|internal server error|bad gateway|service unavailable|ETIMEDOUT|ECONNRESET|connection reset|timed out|\bEOF\b|temporarily unavailable|stream error|received from peer|error connecting to|check your internet connection|no such host|TLS handshake timeout|i\/o timeout|network is unreachable|connection refused|EAI_AGAIN|ENETUNREACH|ECONNREFUSED/i; // 2026-11-26: gh's network-failure texts (a lossy link dropped a merge into engine-error)
|
|
8
8
|
/** #4507: gh failing to parse its own input: a torn HTTP cache entry (JSON) or a half-written config (YAML). */
|
|
9
9
|
export const GH_PARSE_RE = /invalid character .{0,40}looking for|unexpected end of JSON input|cannot unmarshal|yaml: line \d+|yaml: unmarshal/i;
|
|
10
10
|
export const MERGE_TRANSIENT_RE = new RegExp(`${GH_TRANSIENT_RE.source}|${GH_PARSE_RE.source}|base branch was modified|head branch was modified|mergeability.*unknown|try again`, "i");
|
package/bin/lean/retry.test.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { pollUntil } from "./retry.mjs";
|
|
3
|
+
import { pollUntil, GH_TRANSIENT_RE as NET_RE } from "./retry.mjs";
|
|
4
4
|
|
|
5
5
|
test("pollUntil returns the first truthy probe value, sleeping between tries", async () => {
|
|
6
6
|
let n = 0, t = 0; const sleeps = [];
|
|
@@ -14,3 +14,8 @@ test("pollUntil returns null once the timeout passes, probing at least once", as
|
|
|
14
14
|
assert.equal(v, null); assert.ok(n >= 3);
|
|
15
15
|
assert.equal(await pollUntil(() => null, { timeoutMs: -1, pollMs: 1, sleep: async () => {}, now: () => 0 }), null);
|
|
16
16
|
});
|
|
17
|
+
|
|
18
|
+
test("gh network failures are transient, validation errors are not (2026-11-26: a dropped connection during gh pr merge became an engine-error)", () => {
|
|
19
|
+
for (const t of ["error connecting to api.github.com", "check your internet connection", "dial tcp: lookup api.github.com: no such host", "net/http: TLS handshake timeout", "read tcp: i/o timeout", "connect: connection refused"]) assert.ok(NET_RE.test(t), t);
|
|
20
|
+
for (const t of ["HTTP 422: Validation Failed", "GraphQL: Could not resolve to a PullRequest", "HTTP 404: Not Found"]) assert.ok(!NET_RE.test(t), t);
|
|
21
|
+
});
|
package/bin/lean/rotator.mjs
CHANGED
|
@@ -213,3 +213,12 @@ export function quotaRequeue({ rotator, r, prior = null, delayMs, exclude = null
|
|
|
213
213
|
return { delayMs, rotated: false };
|
|
214
214
|
} catch { return null; }
|
|
215
215
|
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* #5988: the account to try after `failed` (account numbers: the ones whose login just failed) hit a `backend.auth` failure,
|
|
219
|
+
* tried first on resume. Never `failed` itself; null when no rotator or no other account is usable.
|
|
220
|
+
*/
|
|
221
|
+
export function nextAccountAfterAuthFailure(rotator, failed = []) {
|
|
222
|
+
if (!rotator || typeof rotator.pick !== "function") return null;
|
|
223
|
+
try { const p = rotator.pick({ exclude: new Set([...failed].map(Number).filter((n) => Number.isInteger(n) && n > 0)) }); return Number.isInteger(p?.account) ? p.account : null; } catch { return null; }
|
|
224
|
+
}
|
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
|
|
8
|
+
import { parseLive, openRotator, rotatorRetry, quotaRequeue, rotatorKind, nextAccountAfterAuthFailure, realClaude, accountOfPid, ROTATOR_KINDS, HEADROOM_PCT } from "./rotator.mjs";
|
|
9
9
|
import { laneBackendId, openLimits } from "./limits.mjs";
|
|
10
10
|
import { orchestrate, formatTable } from "./orchestrate.mjs";
|
|
11
11
|
import { parseExecution } from "./execution.mjs";
|
|
@@ -244,3 +244,13 @@ describe("account rotator: detection, staleness, exclusion, pick (#5205)", () =>
|
|
|
244
244
|
assert.equal(accountOfPid(undefined, { procRoot: proc }), null);
|
|
245
245
|
});
|
|
246
246
|
});
|
|
247
|
+
|
|
248
|
+
describe("#5988: next account after an auth failure", () => {
|
|
249
|
+
const fake = (accounts) => ({ pick: ({ exclude }) => { const a = accounts.find((n) => !exclude.has(n)); return a ? { account: a } : { account: null }; } });
|
|
250
|
+
it("picks an account other than the failed one; null when none is left or there is no rotator", () => {
|
|
251
|
+
assert.equal(nextAccountAfterAuthFailure(fake([1, 2, 3]), [1]), 2);
|
|
252
|
+
assert.equal(nextAccountAfterAuthFailure(fake([1, 2]), [1, 2]), null);
|
|
253
|
+
assert.equal(nextAccountAfterAuthFailure(null, [1]), null);
|
|
254
|
+
assert.equal(nextAccountAfterAuthFailure({ pick: () => { throw new Error("x"); } }, [1]), null);
|
|
255
|
+
});
|
|
256
|
+
});
|
|
@@ -57,7 +57,7 @@ export function isActionsEndpoint(endpoint) {
|
|
|
57
57
|
* `GET /agents -> {sandboxes}` is the router's live sandbox list (#5422, `inventory()`; malformed or any error throws).
|
|
58
58
|
* Optional relay (#4778): `GET /sandboxes/:id/relay -> {requests: [{rid, argv}]}` lists a sandbox's pending read-only capability
|
|
59
59
|
* requests (404/405 or malformed = none, an older router) and `POST /sandboxes/:id/relay/:rid` `{rc, stdout, stderr}` answers one.
|
|
60
|
-
* Optional `GET /status -> {free: N, online?, total?}` is the pool's free slots (#4540); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
|
|
60
|
+
* Optional `GET /status[?repo=<slug>] -> {free: N, online?, total?}` is the pool's free slots (#4540); `?repo=` (#6041) limits `/status` and `/agents` to the agents the repo may use (router.json `repos.<slug>.agents` / `exclude_agents`); without `online` the agents of `GET /agents` give it (#4788). Anything else (404, error, malformed) is unknown (null).
|
|
61
61
|
*/
|
|
62
62
|
export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fetch }) {
|
|
63
63
|
const root = String(endpoint ?? "").replace(/\/+$/, "");
|
|
@@ -75,9 +75,14 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
75
75
|
const hop = r.status === 401 && ["router", "agent"].includes(r.data?.hop) ? r.data.hop : null;
|
|
76
76
|
const who = hop === "agent" && typeof r.data?.agent === "string" ? `agent ${r.data.agent.slice(0, 64)}` : hop;
|
|
77
77
|
const reason = hop && typeof r.data?.reason === "string" ? r.data.reason.replace(/^(router|agent) auth: /, "").replace(/[^\x20-\x7e]/g, "").slice(0, 80) : "";
|
|
78
|
-
|
|
78
|
+
// 2026-11-26: non-auth failures keep the pool's error text (printable, ≤160 chars, never a token), so a seed 409/422 says why
|
|
79
|
+
const live = typeof token === "function" ? (() => { try { return token(); } catch { return null; } })() : token;
|
|
80
|
+
const err = !hop && typeof r.data?.error === "string" ? redact(r.data.error, [live]).replace(/[^\x20-\x7e]/g, "").slice(0, 160) : "";
|
|
81
|
+
const e = new Error(`sandbox ${what}: HTTP ${r.status}${who ? ` (${who} auth${reason ? `: ${reason}` : ""})` : ""}${err ? `: ${err}` : ""}`);
|
|
79
82
|
e.status = r.status;
|
|
80
83
|
if (hop) e.hop = hop;
|
|
84
|
+
if (typeof r.data?.code === "string" && r.data.code.startsWith("pool.")) e.poolCode = r.data.code; // #5985: the pool's refusal code reaches the deferral row
|
|
85
|
+
if (r.data?.live && typeof r.data.live === "object") e.live = { load_per_core: r.data.live.load_per_core, mem_available_gb: r.data.live.mem_available_gb };
|
|
81
86
|
if (reason) e.reason = reason;
|
|
82
87
|
if ([500, 502, 503, 504].includes(r.status)) e.transient = true; // #4672: a router restart or gateway blip, retried by the lane poll; #5095: 500 too
|
|
83
88
|
if (r.status === 429 || r.status === 503) e.retryable = true;
|
|
@@ -86,8 +91,9 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
86
91
|
return e;
|
|
87
92
|
};
|
|
88
93
|
const p = (id) => `/sandboxes/${encodeURIComponent(id)}`;
|
|
94
|
+
const placedEngine = new Map(); // sandbox id -> lane-engine version of the agent the router placed it on (R3: the ran version is recorded even when the lane reports none)
|
|
89
95
|
return {
|
|
90
|
-
async launch(spec) { const r = await call("POST", "/sandboxes", spec); if (!r.ok) throw fail("launch", r); return r.data ?? {}; },
|
|
96
|
+
async launch(spec) { const r = await call("POST", "/sandboxes", spec); if (!r.ok) throw fail("launch", r); if (typeof r.data?.engine_version === "string" && typeof spec?.id === "string") placedEngine.set(spec.id, r.data.engine_version); return r.data ?? {}; },
|
|
91
97
|
/** #4912: hand the lane to a ready warm sandbox. 200/201 = claimed; 204/404/405 (none ready, or a pool without warm sandboxes) = null. */
|
|
92
98
|
async claim(spec) { const r = await call("POST", "/sandboxes/claim", spec); if (r.status === 200 || r.status === 201) return r.data ?? {}; if (r.status === 204 || r.status === 404 || r.status === 405) return null; throw fail("claim", r); },
|
|
93
99
|
async status(id) {
|
|
@@ -98,7 +104,7 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
98
104
|
return s === "running" || s === "pending" || s === "starting" || s === "paused" ? "running" : s === "gone" ? "gone" : "exited";
|
|
99
105
|
},
|
|
100
106
|
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 }; },
|
|
101
|
-
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?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ 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 */
|
|
107
|
+
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?.disk_pressure === true) return { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_DISK_PRESSURE, retryInSeconds: 120, cost_usd: 0, detail: `sandbox ${id} was stopped to save the host drive (disk pressure); worktree and volume kept, requeued to resume` }; /* #5891 */ 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 */ if (r.ok && r.data && typeof r.data === "object") { const v = r.data.engineVersion ?? r.data.engine_version ?? r.data.forge_version ?? /ForgeDock\s*[·-]\s*v?(\d+\.\d+(?:\.\d+)?)/.exec(String(r.data.banner ?? r.data.log ?? ""))?.[1]; const pv = v ?? placedEngine.get(id); return pv && !r.data.engineVersion ? { ...r.data, engineVersion: String(pv) } : r.data; } return null; }, /* #5931 */
|
|
102
108
|
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
|
|
103
109
|
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); },
|
|
104
110
|
async destroy(id) { const r = await call("DELETE", p(id)); if (r.ok || r.status === 404) return true; throw fail("destroy", r); },
|
|
@@ -141,24 +147,48 @@ export function httpTransport({ endpoint, token = null, fetchFn = globalThis.fet
|
|
|
141
147
|
const sb = r.data.sandboxes && typeof r.data.sandboxes === "object" ? Object.keys(r.data.sandboxes) : [];
|
|
142
148
|
return { agents, total: int(r.data.remote_lanes) ?? sb.filter((id) => id.startsWith("fdrsbx-")).length };
|
|
143
149
|
},
|
|
150
|
+
/** #5985: finished-lane usage rows (`{repo, cpu_avg, ...}`) of every pool agent (`GET /agents/:name/usage`), for the light/heavy lane class. A bad answer throws. */
|
|
151
|
+
async usageHistory() {
|
|
152
|
+
const r = await call("GET", "/agents");
|
|
153
|
+
if (!r.ok) throw fail("usage history", r);
|
|
154
|
+
const names = (Array.isArray(r.data?.agents) ? r.data.agents : []).map((a) => a?.name).filter((n) => typeof n === "string");
|
|
155
|
+
const rows = [];
|
|
156
|
+
for (const n of names) { try { const u = await call("GET", `/agents/${encodeURIComponent(n)}/usage`); if (u.ok && Array.isArray(u.data?.rows)) rows.push(...u.data.rows); } catch { /* one agent down: its rows are unknown */ } }
|
|
157
|
+
return rows;
|
|
158
|
+
},
|
|
144
159
|
async relayPending(id) { const r = await call("GET", `${p(id)}/relay`); return r.ok && Array.isArray(r.data?.requests) ? r.data.requests : []; },
|
|
145
160
|
async relayAnswer(id, rid, out) { const r = await call("POST", `${p(id)}/relay/${encodeURIComponent(rid)}`, out); if (!r.ok) throw fail("relay answer", r); return true; },
|
|
146
|
-
|
|
161
|
+
/** #5991: the pool agent that runs `agent` (any agent when unnamed) answers `GET /agents` and is not paused; errors propagate. */
|
|
162
|
+
async agentOnline(agent = null) {
|
|
163
|
+
const r = await call("GET", "/agents");
|
|
164
|
+
const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
|
|
165
|
+
if (!list) throw fail("agents", r);
|
|
166
|
+
return list.some((a) => a?.ok === true && !a.paused && (!agent || a.name === agent));
|
|
167
|
+
},
|
|
168
|
+
async capacity({ repo } = {}) {
|
|
169
|
+
const q = typeof repo === "string" && repo ? `?repo=${encodeURIComponent(repo)}` : ""; // #6041: only the repo's allowed agents count
|
|
147
170
|
// `free` (#4540) and agent liveness `online`/`total` (#4547) are each optional; none valid is unknown.
|
|
148
171
|
const ok = (v) => Number.isInteger(v) && v >= 0;
|
|
149
172
|
let out = {}, reached = false, lastErr = null;
|
|
150
173
|
try {
|
|
151
|
-
const r = await call("GET",
|
|
174
|
+
const r = await call("GET", `/status${q}`);
|
|
152
175
|
reached = true;
|
|
153
|
-
if (r.ok) { const { free, online, total } = r.data ?? {};
|
|
176
|
+
if (r.ok) { const { free, online, total } = r.data ?? {}; const agents = (Array.isArray(r.data?.agents) ? r.data.agents : []).filter((a) => typeof a?.engine_version === "string").map((a) => ({ name: a.name, ok: a.ok === true, paused: a.paused === true, engine_version: a.engine_version })); // R6: per-agent lane engines
|
|
177
|
+
out = { ...(ok(free) ? { free } : {}), ...(ok(online) ? { online } : {}), ...(ok(total) ? { total } : {}), ...(agents.length ? { agents } : {}) }; }
|
|
154
178
|
} catch (e) { out = {}; lastErr = e; }
|
|
155
|
-
if (out.online === undefined) {
|
|
179
|
+
if (out.online === undefined || out.load_per_core === undefined) {
|
|
156
180
|
// #4788: a router without /status liveness: online = agents answering and not paused, as bin/pool/router.mjs status() does.
|
|
157
181
|
try {
|
|
158
|
-
const r = await call("GET",
|
|
182
|
+
const r = await call("GET", `/agents${q}`);
|
|
159
183
|
reached = true;
|
|
160
184
|
const list = r.ok && Array.isArray(r.data?.agents) ? r.data.agents : null;
|
|
161
|
-
if (list) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
|
|
185
|
+
if (list && out.online === undefined) out = { ...out, online: list.filter((a) => a?.ok === true && !a.paused).length, total: list.length };
|
|
186
|
+
// #5985: live host figures (worst agent); a pool reporting none leaves them unknown
|
|
187
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
188
|
+
const loads = (list ?? []).map((a) => num(a?.load_per_core ?? a?.live?.load_per_core)).filter((v) => v !== null);
|
|
189
|
+
const mems = (list ?? []).map((a) => num(a?.mem_available_gb ?? a?.live?.mem_available_gb)).filter((v) => v !== null);
|
|
190
|
+
if (loads.length) out = { ...out, load_per_core: Math.max(...loads) };
|
|
191
|
+
if (mems.length) out = { ...out, mem_available_gb: Math.min(...mems) };
|
|
162
192
|
} catch (e) { lastErr = e; /* liveness stays unknown */ }
|
|
163
193
|
}
|
|
164
194
|
// #5048 (release review REG-2): a router that answered neither call is unreachable: throw, so the pool is marked down
|
|
@@ -256,6 +286,7 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
256
286
|
const envSnap = settings.forgeYaml ? readEnvSnapshots(settings.forgeYaml) : null; // env.snapshots: off unless enabled
|
|
257
287
|
const spec = {
|
|
258
288
|
id, issue, batch: batch.id, image: settings.image ?? null,
|
|
289
|
+
...(typeof settings.minLaneEngine === "string" && settings.minLaneEngine ? { min_lane_engine: settings.minLaneEngine } : {}), // R2: the router drops lower-engine agents (pool.engine_old deferral)
|
|
259
290
|
priority: "borrow", // #5856: lanes run on leftover capacity; a pool with reservations throttles/drains them for reserved work
|
|
260
291
|
repo: { slug: repo, url: repo ? `https://github.com/${repo}.git` : null, ref: li >= 0 ? args[li + 1] ?? null : null },
|
|
261
292
|
...(settings.laneTools?.length ? { lane_tools: settings.laneTools } : {}), // #5650: per-repo lane image
|
|
@@ -302,11 +333,18 @@ export function remoteProvider({ batch, repo, settings = {}, name = "remote", tr
|
|
|
302
333
|
if (runLog) mergeRemoteLog(env.FORGE_RUNS_DIR || join(homedir(), ".forge", "runs"), h.issue, runLog, { repo });
|
|
303
334
|
return rest;
|
|
304
335
|
},
|
|
336
|
+
/** #5991: is the pool agent of this handle answering? Unknown (null) without transport support; transport errors propagate. */
|
|
337
|
+
async agentOnline(h) {
|
|
338
|
+
if (typeof transport.agentOnline !== "function") return null;
|
|
339
|
+
return transport.agentOnline(typeof h?.agent === "string" && h.agent ? h.agent : null);
|
|
340
|
+
},
|
|
305
341
|
async capacity() {
|
|
306
342
|
// #5048: no capacity() is unknown (null); a transport error propagates, so the caller can report the pool down
|
|
307
343
|
if (typeof transport.capacity !== "function") return null;
|
|
308
|
-
return (await transport.capacity()) ?? null;
|
|
344
|
+
return (await transport.capacity({ repo })) ?? null;
|
|
309
345
|
},
|
|
346
|
+
/** #5985: the pool's usage-history rows; null when the transport has none. */
|
|
347
|
+
async usageHistory() { return typeof transport.usageHistory === "function" ? (await transport.usageHistory()) ?? null : null; },
|
|
310
348
|
/** #4612: a graceful stop at the lane's checkpoint; false when unsupported or failed. Never destroys the sandbox. */
|
|
311
349
|
async stop(h) {
|
|
312
350
|
if (typeof transport.stop !== "function") { stopWhy.set(h.id, "the transport has no stop"); return false; }
|
package/bin/lean/sched.mjs
CHANGED
|
@@ -25,6 +25,7 @@ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statS
|
|
|
25
25
|
import { homedir } from "node:os";
|
|
26
26
|
import { join } from "node:path";
|
|
27
27
|
import { writeAtomic } from "./batch.mjs";
|
|
28
|
+
import { formatConcurrency } from "./concurrency.mjs";
|
|
28
29
|
|
|
29
30
|
export const DEFAULT_PRIORITY = 2;
|
|
30
31
|
export const LOCK_WAIT_MS = 2000;
|
|
@@ -260,6 +261,24 @@ export function remoteLines(st, { agentOf = null } = {}) {
|
|
|
260
261
|
return out;
|
|
261
262
|
}
|
|
262
263
|
|
|
264
|
+
/**
|
|
265
|
+
* #5985: `sched show`/status lines `batch B concurrency: running/K/ceiling (limiting factor)`, from each running batch's last
|
|
266
|
+
* controller event in `log.jsonl` (`eventsOf(batch) -> rows`); `achieved` is running over the configured ceiling. Empty when none logged.
|
|
267
|
+
*/
|
|
268
|
+
export function concurrencyLines(st, { eventsOf = null } = {}) {
|
|
269
|
+
if (typeof eventsOf !== "function") return [];
|
|
270
|
+
const batches = [...new Set([...(st?.slots ?? []), ...(st?.remote ?? [])].map((e) => e.batch).filter(Boolean))];
|
|
271
|
+
const out = [];
|
|
272
|
+
for (const b of batches) {
|
|
273
|
+
let last = null;
|
|
274
|
+
try { for (const r of eventsOf(b) ?? []) if (r?.event === "concurrency") last = r; } catch { last = null; }
|
|
275
|
+
if (!last || !Number.isInteger(last.ceiling)) continue;
|
|
276
|
+
const running = Number.isInteger(last.running) ? last.running : 0;
|
|
277
|
+
out.push(`batch ${b} ${formatConcurrency({ running, k: last.k, ceiling: last.ceiling, factor: last.factor })}; achieved ${running} of ${last.ceiling} configured`);
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
|
|
263
282
|
/** #5847: batch-start report of the effective concurrency K, the host cap and which source set it; pure and read-only. */
|
|
264
283
|
export function describeConcurrency({ parallel, parallelFrom = "default", registryCap = null, globalParallel = null, derivedCap = null, yamlFound = true, cwd = "." } = {}) {
|
|
265
284
|
const pos = (n) => (Number.isInteger(n) && n > 0 ? n : null);
|
package/bin/lean/sched.test.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { writeFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { tmpDir } from "../tests/_tmp.mjs";
|
|
8
|
-
import { describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
8
|
+
import { concurrencyLines, describeConcurrency, grantOrder, openSched, priorityFromLabels, remoteLines } from "./sched.mjs";
|
|
9
9
|
import { orchestrate, estimateLaneMinutes, laneHistory, formatEstimateSummary, EST_DEFAULT_MIN, POST_DEPLOY_EST_MIN } from "./orchestrate.mjs";
|
|
10
10
|
import { schedFromCli } from "../engine-cli.mjs";
|
|
11
11
|
|
|
@@ -601,3 +601,13 @@ describe("describeConcurrency", () => {
|
|
|
601
601
|
assert.deepEqual(describeConcurrency({ parallel: 1 }).warnings, []);
|
|
602
602
|
});
|
|
603
603
|
});
|
|
604
|
+
|
|
605
|
+
describe("concurrencyLines (#5985)", () => {
|
|
606
|
+
it("prints running/K/ceiling (limiting factor) with achieved vs configured from the last controller event", () => {
|
|
607
|
+
const rows = [{ event: "concurrency", k: 8, ceiling: 8, running: 8, factor: "ceiling" }, { issue: 3, outcome: "merged" }, { event: "concurrency", k: 4, ceiling: 8, running: 3, factor: "host_load" }];
|
|
608
|
+
const st = { slots: [{ batch: "b1" }], remote: [{ batch: "b1" }, { batch: "b2" }] };
|
|
609
|
+
const lines = concurrencyLines(st, { eventsOf: (b) => (b === "b1" ? rows : []) });
|
|
610
|
+
assert.deepEqual(lines, ["batch b1 concurrency: 3/4/8 (host_load); achieved 3 of 8 configured"]);
|
|
611
|
+
assert.deepEqual(concurrencyLines(st), []);
|
|
612
|
+
});
|
|
613
|
+
});
|
|
@@ -55,15 +55,15 @@ export function tickText(c) {
|
|
|
55
55
|
* @returns the check, plus `killed` (and `started` when it started one)
|
|
56
56
|
*/
|
|
57
57
|
export async function watchdog({ dir = schedDir(), stallMs = STALL_MS, now = () => Date.now(), alive = pidAlive, kill = (p, s) => process.kill(p, s),
|
|
58
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, batchVerdicts = null, unit = null, emit = null } = {}) {
|
|
58
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)), graceMs = KILL_GRACE_MS, log = (m) => console.log(m), unfinished = () => [], start = null, restart = null, batchVerdicts = null, unit = null, emit = null } = {}) {
|
|
59
59
|
const c = stallCheck({ dir, stallMs, now, alive });
|
|
60
60
|
if (batchVerdicts) { try { for (const l of batchVerdicts() ?? []) log(`schedd watchdog: ${l}`); } catch { /* advisory */ } } // #5938: one verdict line per batch
|
|
61
61
|
// #5966: the unit says active but no daemon answers (no live pid/heartbeat): alert and restart it, whether or not batches are unfinished
|
|
62
|
-
if (c.status === "down" &&
|
|
62
|
+
if (c.status === "down" && restart && unit && ["active", "activating"].includes((() => { try { return unit(); } catch { return null; } })())) {
|
|
63
63
|
log(`schedd watchdog: ALERT unit is active but no daemon answers (schedd status: not running); restarting the unit`);
|
|
64
64
|
try { emit?.({ type: "schedd.unit-no-daemon", at: now() }); } catch { /* advisory */ }
|
|
65
|
-
try { await
|
|
66
|
-
return { ...c, killed: null, alerted: true, started: true };
|
|
65
|
+
try { await restart(); } catch (e) { log(`schedd watchdog: restart failed: ${e?.message ?? e}`); return { ...c, killed: null, alerted: true, started: false, restarted: false }; }
|
|
66
|
+
return { ...c, killed: null, alerted: true, started: true, restarted: true }; // `systemctl start` is a no-op on an active unit, so this must be a restart
|
|
67
67
|
}
|
|
68
68
|
if (c.status === "down" && start) {
|
|
69
69
|
let ids = [];
|
|
@@ -71,16 +71,20 @@ describe("schedd heartbeat and watchdog (#4780)", () => {
|
|
|
71
71
|
|
|
72
72
|
it("#5966: a down daemon while the unit is active alerts, emits an event and restarts the unit, even with no unfinished batches", async () => {
|
|
73
73
|
const dir = tmpDir("schedd-wd-unit-"), lines = [], events = [];
|
|
74
|
-
let starts = 0;
|
|
75
|
-
const run = (unit) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
|
|
74
|
+
let starts = 0, restarts = 0;
|
|
75
|
+
const run = (unit, restart = async () => { restarts++; }) => watchdog({ dir, now: () => 0, alive: () => false, unfinished: () => [], start: async () => { starts++; }, restart, unit, emit: (e) => events.push(e), log: (m) => lines.push(m) });
|
|
76
76
|
const r = await run(() => "active");
|
|
77
77
|
assert.equal(r.started, true);
|
|
78
78
|
assert.equal(r.alerted, true);
|
|
79
|
-
assert.equal(
|
|
79
|
+
assert.equal(r.restarted, true);
|
|
80
|
+
assert.deepEqual([restarts, starts], [1, 0], "an active unit is restarted, never started");
|
|
80
81
|
assert.equal(events[0].type, "schedd.unit-no-daemon");
|
|
81
82
|
assert.ok(lines.some((l) => l.includes("ALERT")));
|
|
82
83
|
await run(() => "inactive");
|
|
83
84
|
await run(() => null);
|
|
84
|
-
assert.equal(
|
|
85
|
+
assert.equal(restarts, 1, "an inactive or absent unit with nothing unfinished is left down");
|
|
86
|
+
const f = await run(() => "active", async () => { throw new Error("denied"); });
|
|
87
|
+
assert.deepEqual([f.started, f.restarted, f.alerted], [false, false, true]);
|
|
88
|
+
assert.match(lines.at(-1), /restart failed: denied/);
|
|
85
89
|
});
|
|
86
90
|
});
|