forgedock 1.71.0 → 1.72.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 +1 -1
- package/bin/engine/outcome-codes.mjs +5 -4
- package/bin/init-detect.mjs +35 -2
- package/bin/lean/admit.mjs +118 -0
- package/bin/lean/admit.test.mjs +78 -0
- package/bin/lean/attempts.mjs +1 -1
- package/bin/lean/batch.mjs +8 -0
- package/bin/lean/batch.test.mjs +17 -0
- package/bin/lean/concurrency.mjs +7 -2
- package/bin/lean/concurrency.test.mjs +16 -3
- package/bin/lean/conformance.mjs +2 -0
- package/bin/lean/conformance.test.mjs +9 -0
- package/bin/lean/effects.mjs +8 -0
- package/bin/lean/failure-census.mjs +1 -1
- package/bin/lean/lean.mjs +93 -4
- package/bin/lean/lean.test.mjs +38 -0
- package/bin/lean/orchestrate-envhold.test.mjs +14 -0
- package/bin/lean/orchestrate-heldroot.test.mjs +32 -0
- package/bin/lean/orchestrate.mjs +33 -11
- package/bin/lean/queuecause.mjs +42 -0
- package/bin/lean/release-cigreen.mjs +18 -4
- package/bin/lean/release-cigreen.test.mjs +23 -0
- package/bin/lean/release-review.mjs +24 -10
- package/bin/lean/release-review.test.mjs +65 -0
- package/bin/lean/release.mjs +1 -1
- package/bin/lean/release.test.mjs +19 -0
- package/bin/lean/schedd.mjs +24 -1
- package/bin/lean/schedd.test.mjs +38 -0
- package/bin/pool/agent.mjs +32 -14
- package/bin/pool/docker-dns.mjs +23 -0
- package/bin/pool/docker.mjs +5 -3
- package/bin/pool/engine-placement.test.mjs +2 -2
- package/bin/pool/image-manifest.test.mjs +13 -0
- package/bin/pool/lane-image.mjs +56 -15
- package/bin/pool/lane-tools.mjs +26 -12
- package/bin/pool/lane-tools.test.mjs +63 -1
- package/bin/pool/project-layer.mjs +2 -2
- package/bin/pool/router.mjs +2 -1
- package/bin/review-staging.mjs +14 -11
- package/bin/review-staging.test.mjs +20 -1
- package/bin/stats/escapes.mjs +124 -0
- package/bin/stats/index.mjs +5 -1
- package/bin/stats/quality-ledger.mjs +49 -0
- package/bin/stats/quality-ledger.test.mjs +84 -0
- package/bin/stats/weekly.mjs +230 -0
- package/docs/OUTCOME-CODES.md +2 -1
- package/package.json +1 -1
- package/pool/README.md +2 -0
- package/pool/image/Dockerfile +4 -1
- package/pool/image/lane-tools-sets.json +6 -0
- package/scripts/lane-variants.mjs +51 -0
package/bin/lean/lean.mjs
CHANGED
|
@@ -31,6 +31,7 @@ import { namedPaths, isTrustedIssueComment, prodFailureSignal } from "./prefilte
|
|
|
31
31
|
import { writeStatus, postUpsert, postKeyed, isKeyedPost, isStatusPost, isUpsertPost, hasSection, clearPipelineLabels, IN_PLACE_MARKERS, commentId, contractKey } from "./statuscomment.mjs";
|
|
32
32
|
import { decidePost } from "./commentstate.mjs"; // #5979
|
|
33
33
|
import { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs"; // #5979
|
|
34
|
+
import { baseHealth, fetchBaseChecks, baseRedComment, hasAdmitComment, classifyDryRun, renderStamp, stampable, inputOf, fingerprintStop, stopReason, admitEvent } from "./admit.mjs"; // #6206
|
|
34
35
|
import { checksAt, mergeCheckEntries, CHECKS_FILE } from "./postdeploy-check.mjs";
|
|
35
36
|
import { matchBaselines, baselineFailures, foldRegression } from "./baselines.mjs";
|
|
36
37
|
import { readRollouts, detectNewOffKeys, rolloutModes, liveDeferralBlocks } from "./activation.mjs";
|
|
@@ -58,7 +59,7 @@ import { computeTrigger, riskPathHits, TRIGGER_MODES, pathDomains, parseEnforceD
|
|
|
58
59
|
import { hostCapabilityBlock, contractHostNeeds } from "./execution.mjs";
|
|
59
60
|
import { baseMergeOnlyBlock, envGapBlockCode, toolGapFailures, packageDirsMissingDeps, failureOutsideDiff } from "./envgap.mjs"; // #6106
|
|
60
61
|
|
|
61
|
-
const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or directory.*\b(?:docker|promtool)\b|\b(?:docker|promtool)\b[^\n]{0,80}(?:not (?:installed|found|available)|no such file|cannot connect|daemon)|cannot connect to the docker daemon|no docker daemon|no module named|ModuleNotFoundError|\bENOENT\b[^\n]{0,60}spawn/i;
|
|
62
|
+
const MISSING_TOOL_RE = /command not found|not found in PATH|no such file or directory.*\b(?:docker|promtool)\b|\b(?:docker|promtool)\b[^\n]{0,80}(?:not (?:installed|found|available)|no such file|cannot connect|daemon)|cannot connect to the docker daemon|no docker daemon|image[^\n]{0,30}present locally|unable to find image|valid docker environment|no module named|ModuleNotFoundError|\bENOENT\b[^\n]{0,60}spawn/i;
|
|
62
63
|
/** #4685: true when a builder's block summary names a missing tool or module (environment), not a credential. */
|
|
63
64
|
/** #5623: a contract problem the builder can fix in its own session (shape, typed fields, test-plan rules, check ids), as
|
|
64
65
|
* opposed to one that needs the issue changed (quote not verbatim) or a person. */
|
|
@@ -85,6 +86,7 @@ import { parseCoupled, coupledFailures } from "./coupled.mjs";
|
|
|
85
86
|
import { analyzeRelaxations, relaxationFailures } from "./relaxation.mjs";
|
|
86
87
|
import { startSpeculative } from "./overlap.mjs";
|
|
87
88
|
import { loadGuards, selectGuards, runGuards, supersededIds, supersessionComment, weakGuardNotes } from "./guardgate.mjs";
|
|
89
|
+
import { buildMergeLedger } from "../stats/quality-ledger.mjs";
|
|
88
90
|
import { freshFix, issueSummary, firstPassOf, sessionCostDelta, mergeNarrowTasks } from "./fixround.mjs";
|
|
89
91
|
import { floorRoute, parseBuilderRouting, provisionalRoute, routeBuilder, shouldEscalate } from "./routing.mjs";
|
|
90
92
|
import { makeTurnBudget, TURN_BUDGET_DEFAULTS, scaledExtra, laneSize, recoverySize, wrapupGrant, budgetDigest } from "./budget.mjs";
|
|
@@ -150,6 +152,7 @@ export const RECOVER_HOW = Object.freeze({
|
|
|
150
152
|
[OUTCOME_CODES.ENV_TOOL_MISSING]: "a validate command could not run because the host lacks the tool or module named in the earlier run's detail; the change may already be correct. Do not edit the deliverables for it and never install anything globally: run the same check through the repo's own toolchain (its virtualenv, lockfile-pinned runner or package scripts), record that exit under the same validate id and name the command you used in your summary",
|
|
151
153
|
[ENV_VALIDATE_PLACEMENT]: "an earlier run in a remote sandbox saw a frozen validate command fail; this host is a different environment (Docker, browsers, network, repo-local services). Rerun the frozen command unchanged here and record its real exit under the same validate id; change the deliverables only if it fails here too, and never substitute or narrow it for an environment gap",
|
|
152
154
|
[ENV_VALIDATE_TIMEOUT]: "a validate command timed out (exit 124) on the engine's rerun, even after one longer retry: host load, not a failed check; the change may already be correct. Do not edit the deliverables for it: run the same command narrowed to the changed files (or through the repo's own cached toolchain) with a longer timeout, record that exit under the same validate id and name the command in your summary",
|
|
155
|
+
[OUTCOME_CODES.ENV_CAPABILITY_DOCKER]: "the earlier run's validate command needed a Docker daemon or image the sandbox lacked; this placement has Docker (or the validate is deferred to CI by a FORGE:DECISION). Re-run the checks here and fix only real failures; never stub out the container the test needs",
|
|
153
156
|
[OUTCOME_CODES.ENV_CAPABILITY_REMOTE]: "the earlier run ran in a remote sandbox that lacks a host-only capability (SOPS/age key, ops credentials, read-only prod monitor SSH); this host has it. Do the work that needed it now, with the host's own tools and credentials, and never print or commit a secret in the clear",
|
|
154
157
|
[OUTCOME_CODES.CONFORMANCE_UNIMPLEMENTED]: "an earlier run's conformance check found a requirement or validate command not done after one builder resume; the branch holds its work. For each named gap deliver the requirement against the frozen contract, adding any file it needs as an `add-deliverable` amendment, and re-run the validate commands",
|
|
155
158
|
[OUTCOME_CODES.CONFORMANCE_OMISSION]: "an earlier run's review found a requirement the change left out or narrowed after one builder resume; the branch holds its work. For each named gap either deliver the requirement (adding any needed file as an `add-deliverable` amendment) or, when the clause is optional, unquantified or outside the issue's acceptance criteria, record an `add-requirement` / `defer` amendment with a why so the engine files a tracked follow-up instead of stopping",
|
|
@@ -409,7 +412,8 @@ export async function runCore(o) {
|
|
|
409
412
|
const sessionCosts = new Map(); // #4407: session id -> last reported cumulative cost
|
|
410
413
|
let sessionId = null;
|
|
411
414
|
|
|
412
|
-
|
|
415
|
+
let ciVerifies = 0, ciMergeFixRounds = 0; // #6203: counted off the run-log events for the MERGE_LEDGER record
|
|
416
|
+
const ev = (e) => { if (e?.event === "CI_VERIFY") ciVerifies++; else if (e?.event === "CI_FIX_ROUND") { if (e.trigger === "merge") ciMergeFixRounds++; } return appendEvent(dir, issue, e, { repo }); }; // #4432: the run log is keyed by repo + issue
|
|
413
417
|
/** #5435: time one sandbox_start step (SANDBOX_STEP event + ledger sub-timing); the result and errors pass through. */
|
|
414
418
|
const step = async (name, fn) => {
|
|
415
419
|
const s0 = now();
|
|
@@ -788,6 +792,12 @@ export async function runCore(o) {
|
|
|
788
792
|
const phases = phaseLedger.snapshot(); // #4908: run log gets the nested ledger, FORGE:TELEMETRY the flattened scalars
|
|
789
793
|
ev({ ...term, phases });
|
|
790
794
|
await emit({ ...term, ...flattenPhases(phases) });
|
|
795
|
+
if (reason === "merged") { // #6203: one MERGE_LEDGER record per merge (first_pass, human touches, test delta, CI attempts, deduped cost, wall per phase)
|
|
796
|
+
try {
|
|
797
|
+
await emit(buildMergeLedger({ firstPass: firstPassOf(builderTriggers), recovered: Boolean(recover), attempt: recover?.attempt ?? o.attempt ?? 1, ciVerifies: ciVerifies + ciMergeFixRounds, ciFixRounds: builderTriggers.filter((x) => x.trigger === "ci_red" || x.trigger === "merge_ci").length,
|
|
798
|
+
files: String(await git(["diff", "--name-only", `${base}...HEAD`]).catch(() => "")).split("\n"), comments: allComments(), sinceMs: Date.now() - (now() - t0), costUsd: usage.cost_usd, phases, wallMs: now() - t0, engineVersion: ENGINE_VERSION, tier: route?.tier, model: route?.model, pr: extra.pr }));
|
|
799
|
+
} catch { /* the ledger is best effort */ }
|
|
800
|
+
}
|
|
791
801
|
// #4297: only a final failure the runner never requeues puts needs-human back (needsHuman() relabels on its own path). invalid,
|
|
792
802
|
// decomposed and dependency-* are legitimate non-failure endings; deferred/engine-error may be requeued, so the batch runner
|
|
793
803
|
// (orchestrate settle, relabelNeedsHuman) relabels those once they are final. #4302: a non-final attempt never relabels; the runner
|
|
@@ -864,6 +874,15 @@ export async function runCore(o) {
|
|
|
864
874
|
const error = String(e?.message ?? e).slice(0, 200);
|
|
865
875
|
T.anomalies.push(`needs-human ${step} failed: ${error}`); ev({ event: "NEEDS_HUMAN_LABEL_FAILED", step, error });
|
|
866
876
|
};
|
|
877
|
+
/** #6206: ` base=<12> in=<16> code=<code>` appended to a park's sig line: the fingerprint stop admits again only when the base head or the input changed. Never throws. */
|
|
878
|
+
async function admitStamp(code) {
|
|
879
|
+
if (!stampable(code)) return "";
|
|
880
|
+
try {
|
|
881
|
+
const sha = String(await git(["rev-parse", base])).trim();
|
|
882
|
+
const s = renderStamp({ base: sha, input: inputOf({ iss, comments: allComments(), trusted: (c) => c?.__mine === true || isTrustedIssueComment(c), engineVersion: ENGINE_VERSION }), code });
|
|
883
|
+
return s ? ` ${s}` : "";
|
|
884
|
+
} catch { return ""; }
|
|
885
|
+
}
|
|
867
886
|
async function needsHuman(why, code = OUTCOME_CODES.ENGINE_ERROR, { ask: askText, note: askNote = "", ...extra } = {}) {
|
|
868
887
|
// #4725: a recorded premise (`Premise: <kind>:<arg>`) that already holds is no blocker: no label, the lane runs again.
|
|
869
888
|
const predicate = parsePredicate(why);
|
|
@@ -883,13 +902,13 @@ export async function runCore(o) {
|
|
|
883
902
|
const stoppable = code !== OUTCOME_CODES.BUILDER_BLOCKED && code !== OUTCOME_CODES.FAILURE_REPEATED && !ENV_ENGINE_OWNED_CODES.includes(code);
|
|
884
903
|
const identical = stoppable ? countIdentical(allComments(), sig, (c) => c?.__mine === true || isTrustedIssueComment(c)) + 1 : 1;
|
|
885
904
|
if (shouldPark(identical)) {
|
|
886
|
-
try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig })); } catch (e) { labelFailed("comment", e); }
|
|
905
|
+
try { await post("FORGE:PARKED", summaryComment({ attempts: identical, code, detail: why, sig: `${sig}${await admitStamp(code)}` })); } catch (e) { labelFailed("comment", e); }
|
|
887
906
|
try { await ghc(["issue", "edit", String(issue), "-R", repo, "--add-label", "needs-human", "--add-label", parkedLabel(OUTCOME_CODES.FAILURE_REPEATED)]); } catch (e) { labelFailed("label", e); }
|
|
888
907
|
T.decisions.push(`Identical failure ${code} (${sig}) seen ${identical}x: parked as ${OUTCOME_CODES.FAILURE_REPEATED}, not relaunched`);
|
|
889
908
|
return finish("needs-human", why, { code: OUTCOME_CODES.FAILURE_REPEATED, ...extra, ...(recover ? { recovery: true } : {}) }, OUTCOME_CODES.FAILURE_REPEATED);
|
|
890
909
|
}
|
|
891
910
|
const notes = [premiseAnnotation(predicate), closedEdgeNote(closedDeps), link, askNote].filter(Boolean).join("\n");
|
|
892
|
-
try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\nsig=${sig}\n\n_${usageLine()}_`); }
|
|
911
|
+
try { await post("FORGE:NEEDS_HUMAN", `## Needs human\n${why}${notes ? `\n\n${notes}` : ""}${recoverUnlabelled ? `\n\n${laneRecoveryEvidence("needs-human", code, "")}` : ""}\n\nsig=${sig}${await admitStamp(code)}\n\n_${usageLine()}_`); } // #6206: the stamp (base head, input hash, code) lets the next admit see that nothing changed
|
|
893
912
|
catch (e) { labelFailed("comment", e); }
|
|
894
913
|
// #5423/#5755: an environment gap is the engine's to recover or hold on an env issue, so a first lane leaves the issue visible; a final recovery lane (no seam) still labels
|
|
895
914
|
if (!(!recover && ENV_ENGINE_OWNED_CODES.includes(code))) {
|
|
@@ -2320,6 +2339,67 @@ export async function runCore(o) {
|
|
|
2320
2339
|
return found;
|
|
2321
2340
|
}
|
|
2322
2341
|
|
|
2342
|
+
/**
|
|
2343
|
+
* #6206: cheap deterministic checks before the first builder/plan session. Returns a finished lane result when the lane is doomed (the issue, the
|
|
2344
|
+
* base or the environment cannot succeed as things stand), else null. Every outcome is one ADMIT_PROBE telemetry event with builder_spend_usd 0.
|
|
2345
|
+
* `o.admitProbe: false` turns it off. Seams that are absent (no required-check read, no login probe, no run seam) skip their step.
|
|
2346
|
+
*/
|
|
2347
|
+
async function admitProbe(frozenNow) {
|
|
2348
|
+
if (o.admitProbe === false) return null;
|
|
2349
|
+
const t0a = now(), trustedC = (c) => c?.__mine === true || isTrustedIssueComment(c);
|
|
2350
|
+
const rec = async (r) => { const e = admitEvent({ ...r, ms: now() - t0a }); ev(e); try { await emit(e); } catch { /* telemetry is best effort */ } };
|
|
2351
|
+
let head = ""; try { head = String(await git(["rev-parse", base])).trim(); } catch { /* unreadable base: the base steps fail open */ }
|
|
2352
|
+
if (!recover) { // 4. failure fingerprint: parked before on this base head and this input
|
|
2353
|
+
const input = inputOf({ iss, comments: allComments(), trusted: trustedC, engineVersion: ENGINE_VERSION });
|
|
2354
|
+
const hit = fingerprintStop({ comments: allComments(), base: head, input, trusted: trustedC });
|
|
2355
|
+
if (hit) {
|
|
2356
|
+
await rec({ outcome: "fingerprint_stop", code: OUTCOME_CODES.FAILURE_REPEATED, detail: `${hit.code} ${hit.sig}` });
|
|
2357
|
+
T.decisions.push(`Admit probe: ${stopReason(hit)}`);
|
|
2358
|
+
return await needsHuman(`Admit probe (#6206): ${stopReason(hit)}.`, OUTCOME_CODES.FAILURE_REPEATED);
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
if (head && lane && base === `origin/${lane}` && repo && io.baseRequiredChecks) { // 1. base health
|
|
2362
|
+
let required = [], rows = null;
|
|
2363
|
+
try { required = (await io.baseRequiredChecks(lane)) ?? []; } catch { /* unreadable: no evidence */ }
|
|
2364
|
+
if (required.length) { try { rows = await fetchBaseChecks({ gh: ghc, repo, sha: head }); } catch { rows = null; } }
|
|
2365
|
+
if (rows) {
|
|
2366
|
+
const h = baseHealth({ checks: rows, required, issueText: `${iss?.title ?? ""}\n${iss?.body ?? ""}` });
|
|
2367
|
+
if (h.red) {
|
|
2368
|
+
const key = `base.red ${base}@${head.slice(0, 12)}`;
|
|
2369
|
+
if (!hasAdmitComment(allComments(), key)) { try { await post("FORGE:ADMIT_PROBE", baseRedComment({ base, sha: head, failing: h.failing })); } catch (e) { T.anomalies.push(`Admit probe comment not posted: ${String(e?.message ?? e).slice(0, 160)}`); } }
|
|
2370
|
+
const detail = `base ${base} is red on required check(s) ${h.failing.map((f) => `${f.name}${f.url ? ` (${f.url})` : ""}`).join(", ")}, which this issue does not touch; deferred before any builder session`;
|
|
2371
|
+
await rec({ outcome: "base_red", code: OUTCOME_CODES.BASE_RED, detail, checks: h.failing.map((f) => ({ name: f.name, url: f.url })) });
|
|
2372
|
+
T.decisions.push(`Admit probe: ${detail}`);
|
|
2373
|
+
return await finish("deferred", detail, { code: OUTCOME_CODES.BASE_RED, retryInSeconds: 900 }, OUTCOME_CODES.BASE_RED);
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
if (io.claudeAuthProbe && !smartRotator && !sandboxCred) { // 2. environment: the claude login answers (`claude auth status`, no model call)
|
|
2378
|
+
let a = null; try { a = await io.claudeAuthProbe({}); } catch { /* no verdict */ }
|
|
2379
|
+
if (a && a.ok === false) {
|
|
2380
|
+
const detail = "claude CLI login does not answer (expired or invalid); deferred before any builder session until the login is fixed";
|
|
2381
|
+
await rec({ outcome: "env_auth", code: OUTCOME_CODES.BACKEND_AUTH, detail });
|
|
2382
|
+
return await finish("deferred", detail, { code: OUTCOME_CODES.BACKEND_AUTH, retryInSeconds: AUTH_RETRY_SECONDS }, OUTCOME_CODES.BACKEND_AUTH);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
if (frozenNow && o.placement?.where !== "remote" && (io.probeCommand || io.preflightRun)) { // 3. contract dry-run of the reused frozen contract (a fresh lane has none yet; a remote one runs its own preflight below)
|
|
2386
|
+
const w = Math.max(0, Number(contextWaitSeconds) || 0) * 1000;
|
|
2387
|
+
let misses = await preflightValidates(frozenNow).catch(() => []);
|
|
2388
|
+
if (misses.length && !depsDone) { await within(depsP, w); misses = await preflightValidates(frozenNow).catch(() => []); } // dependencies may provide the tool
|
|
2389
|
+
const dep = await depOwnerOf(), dr = classifyDryRun({ misses, owned: (t) => t === "forgedock" || dep.owner(t) !== null || hasRecipe(t) });
|
|
2390
|
+
if (dr.docker.length) {
|
|
2391
|
+
T.decisions.push(`FORGE:DECISION: validate ${dr.docker.join(", ")} needs Docker, which this placement lacks; it is deferred to CI instead of parking the lane later (admit probe)`);
|
|
2392
|
+
await rec({ outcome: "contract_docker_deferred", code: OUTCOME_CODES.ENV_CAPABILITY_DOCKER, detail: `validate ${dr.docker.join(", ")} deferred to CI`, checks: dr.docker.map((id) => ({ name: id })) });
|
|
2393
|
+
}
|
|
2394
|
+
if (dr.tools.length) {
|
|
2395
|
+
const detail = `the frozen contract's validate ${dr.ids.join(", ")} needs ${dr.tools.join(", ")}, which this placement lacks (probed on the base tree); the lane ends before any builder session and is re-placed or recovered`;
|
|
2396
|
+
await rec({ outcome: "contract_tool_missing", code: OUTCOME_CODES.ENV_TOOL_MISSING, detail, checks: dr.tools.map((t) => ({ name: t })) });
|
|
2397
|
+
return await needsHuman(`Admit probe (#6206): ${detail}.`, OUTCOME_CODES.ENV_TOOL_MISSING);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
await rec({ outcome: "admitted" });
|
|
2401
|
+
return null;
|
|
2402
|
+
}
|
|
2323
2403
|
const isSplit = (iss.labels ?? []).some((l) => (l?.name ?? l) === SPLIT_LABEL);
|
|
2324
2404
|
/**
|
|
2325
2405
|
* #4211: the refactor:split step. One tool-less grouping call over the symbol index (none for a chained plan), the
|
|
@@ -2527,6 +2607,10 @@ export async function runCore(o) {
|
|
|
2527
2607
|
ev(rec); await emit(rec);
|
|
2528
2608
|
T.decisions.push(`Pre-contract sessions provisionally routed to the ${preRoute.tier} tier (${preRoute.class}: ${preRoute.reason})`);
|
|
2529
2609
|
}
|
|
2610
|
+
{ // #6206: the admit probe: base health, login, contract dry-run and the failure fingerprint, before any builder or plan session (zero builder spend, no LLM)
|
|
2611
|
+
const stop = await admitProbe(frozen);
|
|
2612
|
+
if (stop) return stop;
|
|
2613
|
+
}
|
|
2530
2614
|
if (!planOnly) await label("building"); // #5831
|
|
2531
2615
|
// #4450: the light lane (lean.light mode on, eligible, fresh lane): one builder session, derived contract, or an upgrade
|
|
2532
2616
|
const waitMs = Math.max(0, Number(contextWaitSeconds) || 0) * 1000, tHot = now();
|
|
@@ -3934,6 +4018,11 @@ export async function runCore(o) {
|
|
|
3934
4018
|
T.anomalies.push("Contract defect: a frozen validate command is a runner CLI usage error");
|
|
3935
4019
|
return await needsHuman(`Contract defect (not a conformance failure): a frozen validate command is rejected by its runner's CLI, so no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRecovery re-plans the command (vitest: --reporter=dot, not -q).`, OUTCOME_CODES.CONTRACT_INVALID_COMMAND);
|
|
3936
4020
|
}
|
|
4021
|
+
if (failures.every((f) => /^docker(?: daemon)?$/i.test(f.tool ?? ""))) { // #6196: no Docker daemon/image where the validate ran; re-placed on the host, else deferred to CI
|
|
4022
|
+
T.anomalies.push("Environment error: a validate command needs Docker (no daemon or image in this sandbox)");
|
|
4023
|
+
T.decisions.push("FORGE:DECISION: the Docker-dependent validate is an environment gap of this sandbox; it is re-placed on the host, else deferred to CI");
|
|
4024
|
+
return await needsHuman(`Environment error (not a conformance failure): a validate command needs a Docker daemon or image this sandbox lacks, so it could not run; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nRecovery re-places the lane on a host with Docker; where that is off, the validate is deferred to CI (FORGE:DECISION).`, OUTCOME_CODES.ENV_CAPABILITY_DOCKER);
|
|
4025
|
+
}
|
|
3937
4026
|
const tools = [...new Set(failures.filter((f) => f.tool).map((f) => f.tool))].join(", ");
|
|
3938
4027
|
T.anomalies.push(`Environment error: validate command(s) could not run, the host is missing ${tools}`);
|
|
3939
4028
|
return await needsHuman(`Environment error (not a conformance failure): the host is missing ${tools}, so validate command(s) could not run; no builder resume was spent and nothing merged:\n${failures.map((f) => `- ${f.code}: ${f.detail}`).join("\n")}\n\nInstall it on the host or run the check through the repo's own toolchain, then rerun.`, OUTCOME_CODES.ENV_TOOL_MISSING);
|
package/bin/lean/lean.test.mjs
CHANGED
|
@@ -575,6 +575,44 @@ describe("core work-on", () => {
|
|
|
575
575
|
assert.equal((await run(before)).code, "failure.repeated", "a decision older than the park does not clear it");
|
|
576
576
|
});
|
|
577
577
|
|
|
578
|
+
it("#6206 a park carries a base/input/code stamp; the same base head and input is not re-admitted (no builder session), a moved base is", async () => {
|
|
579
|
+
const bot = (body) => ({ author: { login: "rapiercraft-forgedock" }, body });
|
|
580
|
+
const first = world({ changed: [], result: { status: "fixed", summary: "x", evidence: [], tests: [] } });
|
|
581
|
+
await run(first);
|
|
582
|
+
const nh = first.comments.find((c) => c.includes("<!-- FORGE:NEEDS_HUMAN -->"));
|
|
583
|
+
assert.ok(nh && /sig=[0-9a-f]{12} base=\S{1,12} in=[0-9a-f]{16} code=\S+/.test(nh), nh);
|
|
584
|
+
const prior = first.comments.map(bot), same = world({ changed: [], viewComments: prior });
|
|
585
|
+
const r = await run(same);
|
|
586
|
+
assert.equal(r.code, "failure.repeated");
|
|
587
|
+
assert.equal(same.calls.filter((c) => c[0] === "runner").length, 0, "no builder session on an unchanged base and input");
|
|
588
|
+
assert.ok(same.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "fingerprint_stop" && e.builder_spend_usd === 0), JSON.stringify(same.telemetry));
|
|
589
|
+
const moved = world({ changed: [], baseHeads: ["ffffffffffff1111"], viewComments: prior });
|
|
590
|
+
await run(moved);
|
|
591
|
+
assert.ok(!moved.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "fingerprint_stop"), "a moved base head admits again");
|
|
592
|
+
const off = world({ changed: [], viewComments: prior });
|
|
593
|
+
await run(off, { admitProbe: false });
|
|
594
|
+
assert.ok(!off.telemetry.some((e) => e.event === "ADMIT_PROBE"));
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
it("#6206 a base red on a required check the issue does not touch defers base.red with the check links before any builder session; a red the issue names admits", async () => {
|
|
598
|
+
const red = (name) => JSON.stringify({ name, conclusion: "failure", url: `https://github.com/o/r/runs/${name}`, completed_at: "2026-11-28T10:00:00Z", summary: "" });
|
|
599
|
+
const mk = (title) => {
|
|
600
|
+
const w = world({ title });
|
|
601
|
+
const gh = w.io.gh;
|
|
602
|
+
w.io.baseRequiredChecks = async () => ["e2e"];
|
|
603
|
+
w.io.gh = async (a, opts) => (a[0] === "api" && a.some((x) => /\/check-runs$/.test(x)) ? `${red("e2e")}\n` : gh(a, opts));
|
|
604
|
+
return w;
|
|
605
|
+
};
|
|
606
|
+
const w = mk("foo breaks");
|
|
607
|
+
const r = await run(w);
|
|
608
|
+
assert.equal(r.code, "base.red");
|
|
609
|
+
assert.equal(w.calls.filter((c) => c[0] === "runner").length, 0);
|
|
610
|
+
assert.ok(w.comments.some((c) => c.includes("Admit probe: base is red") && /(^|[\s(<])https:\/\/github\.com\/o\/r\/runs\/e2e([\s)>]|$)/m.test(c)));
|
|
611
|
+
assert.ok(w.telemetry.some((e) => e.event === "ADMIT_PROBE" && e.outcome === "base_red" && e.builder_spend_usd === 0));
|
|
612
|
+
const named = mk("fix the red e2e check");
|
|
613
|
+
assert.notEqual((await run(named)).code, "base.red");
|
|
614
|
+
});
|
|
615
|
+
|
|
578
616
|
it("#6076 an unhappy terminal posts one FORGE:LANE_AUDIT; a failing audit post leaves the terminal reason unchanged", async () => {
|
|
579
617
|
const block = { status: "blocked", summary: "need creds", block: { kind: "human", why: "credentials" } };
|
|
580
618
|
const w = world({ changed: [], result: block });
|
|
@@ -383,3 +383,17 @@ describe("#5988: breaker scoped by signature and agent", () => {
|
|
|
383
383
|
assert.ok(r.updates.some((u) => u.outcome === "breaker"), "bounded: the batch breaker trips");
|
|
384
384
|
});
|
|
385
385
|
});
|
|
386
|
+
|
|
387
|
+
describe("#6196 env.capability_docker", () => {
|
|
388
|
+
const dock = (more = {}) => ({ terminalReason: "needs-human", code: "env.capability_docker", detail: "Environment error: a validate command needs a Docker daemon or image this sandbox lacks", placement: { where: "remote" }, ...more });
|
|
389
|
+
const rem = (hostFallback) => ({ max: 2, isRemote: () => true, place: () => ({ where: "remote", reason: "test" }), admit: () => ({ ok: true }), onBudget: "stop", costPerMinute: 0, ...(hostFallback === undefined ? {} : { hostFallback }) });
|
|
390
|
+
it("is recovered on the host when host fallback is on", async () => {
|
|
391
|
+
const r = await harness({ script: { 3: [dock(), MERGED] }, extra: { remote: rem() }, envHold: null });
|
|
392
|
+
assert.deepEqual(r.calls.map((c) => c.n), [3, 3]);
|
|
393
|
+
assert.equal(r.byIssue[3].outcome, "merged");
|
|
394
|
+
});
|
|
395
|
+
it("records the CI-defer decision and does not re-place on the host when host fallback is off", async () => {
|
|
396
|
+
const r = await harness({ script: { 3: [dock()] }, extra: { remote: rem(false) }, envHold: null });
|
|
397
|
+
assert.ok(r.decisions.some((d) => d.issue === 3 && /no host re-placement for env\.capability_docker.*deferred to CI/.test(d.what)));
|
|
398
|
+
});
|
|
399
|
+
});
|
|
@@ -70,3 +70,35 @@ describe("#5893 held needs-human root readmit", () => {
|
|
|
70
70
|
assert.ok(!again.updates.some((u) => u.outcome === "readmitted"));
|
|
71
71
|
});
|
|
72
72
|
});
|
|
73
|
+
|
|
74
|
+
// #6197: an --add reaches a batch whose every pending issue is operator-held within one poll.
|
|
75
|
+
describe("#6197 add to an all-held batch", () => {
|
|
76
|
+
for (const [name, hold] of [["hold expiry", { 1: { expiresAt: new Date(Date.now() + 3600_000).toISOString() } }], ["no expiry (finalise path)", {}]]) {
|
|
77
|
+
it(`held pending with ${name}: an add dispatches within one pollMs`, async () => {
|
|
78
|
+
const ran = [], naps = [];
|
|
79
|
+
let added = [], napped = 0, stop = false;
|
|
80
|
+
const p = orchestrate({ issues: [1], parallel: 1, pollMs: 50, store: memStore(), getHeld: () => [1], getHoldInfo: () => hold, expireHolds: () => [], getCancelled: () => (stop ? { at: new Date().toISOString(), reason: "test" } : null),
|
|
81
|
+
getAdded: () => { const a = added; return a; },
|
|
82
|
+
sleep: async (ms) => { naps.push(ms); if (++napped === 1) added = [7]; await sleep(1); },
|
|
83
|
+
runOne: async (n) => { ran.push(n); stop = true; return MERGED; } });
|
|
84
|
+
if (name.startsWith("no")) added = [7];
|
|
85
|
+
await Promise.race([p, sleep(1500)]);
|
|
86
|
+
stop = true; await Promise.race([p, sleep(500)]);
|
|
87
|
+
assert.deepEqual(ran, [7]);
|
|
88
|
+
assert.ok(naps.every((ms) => ms <= 50), `every nap is poll-capped: ${naps}`);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
it("an add is read within one pollMs while the only pending issue waits on a long notBefore timer", async () => {
|
|
92
|
+
const ran = [], naps = [];
|
|
93
|
+
let added = [], napped = 0, stop = false;
|
|
94
|
+
const store = memStore();
|
|
95
|
+
store.save({ v: 1, order: [2], results: {}, running: {}, pending: [2], notBefore: { 2: Date.now() + 3600_000 } });
|
|
96
|
+
const p = orchestrate({ issues: [2], parallel: 1, pollMs: 50, store, getAdded: () => added,
|
|
97
|
+
sleep: async (ms) => { if (stop) throw new Error("test over"); naps.push(ms); if (++napped === 1) added = [7]; await sleep(1); },
|
|
98
|
+
runOne: async (n) => { ran.push(n); stop = true; return MERGED; } });
|
|
99
|
+
await Promise.race([p.catch(() => {}), sleep(1500)]);
|
|
100
|
+
stop = true; await Promise.race([p.catch(() => {}), sleep(500)]);
|
|
101
|
+
assert.deepEqual(ran, [7]);
|
|
102
|
+
assert.ok(naps.every((ms) => ms <= 50), `every nap is poll-capped: ${naps}`);
|
|
103
|
+
});
|
|
104
|
+
});
|
package/bin/lean/orchestrate.mjs
CHANGED
|
@@ -125,6 +125,7 @@
|
|
|
125
125
|
* the queue order except that decomposed sub-issues go first. A settled row carries `est_minutes` (estimated vs. actual).
|
|
126
126
|
*/
|
|
127
127
|
import { decideClear, decideAutoReset } from "./clear-breaker.mjs";
|
|
128
|
+
import { createQueueClock } from "./queuecause.mjs";
|
|
128
129
|
import { RECONCILE_MS, BREAKER_COOLDOWN_MS, diffSelection, readmitDue, needsDecisionDigest, environmentalDetail, closesManually } from "./reconcile.mjs";
|
|
129
130
|
import { parseDependsOn } from "../engine/phases.mjs";
|
|
130
131
|
import { classifyNeedsHuman, recoveryCodeOf, recoveryClassOf, OUTCOME_CODES, ENV_VALIDATE_PLACEMENT, ENV_VALIDATE_TIMEOUT, MECHANICAL_CODES } from "../engine/outcome-codes.mjs";
|
|
@@ -376,6 +377,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
376
377
|
const deferrals = toMap(saved?.deferrals);
|
|
377
378
|
const capReasons = toMap(saved?.capReasons); // #5938: issue -> the pool's last `sandbox.capacity` / host-disk reason (read by the batch health stall verdict)
|
|
378
379
|
const capDefers = toMap(saved?.capDeferrals); // #5112: issue -> `sandbox.capacity` deferrals (uncapped, so not in `deferrals`)
|
|
380
|
+
const capQuiet = new Set(); // #6204: issues whose current capacity wait was already logged once
|
|
379
381
|
const capFellBack = new Set(); // #5112: issues already reported as a capacity fallback (one decision each)
|
|
380
382
|
const engineErrors = toMap(saved?.engineErrors);
|
|
381
383
|
const transients = toMap(saved?.transientRetries); // #5161: issue -> transient engine-error retries taken
|
|
@@ -404,6 +406,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
404
406
|
const missingTools = async (tools) => { if (typeof envHold?.missingTools !== "function") return null; try { const m = await envHold.missingTools(tools); return Array.isArray(m) ? m : null; } catch { return null; } };
|
|
405
407
|
const checked = toMap(saved?.prefilter); // issue -> pre-filter result
|
|
406
408
|
const estimates = toMap(saved?.estimates); // #4409: issue -> estimated lane minutes; only with `estimate`
|
|
409
|
+
const queueClock = createQueueClock(saved?.queueClock); // #6203: queue_wait by cause, from first ready; a requeue does not reset it
|
|
407
410
|
const enqueued = toMap(saved?.enqueued); // #4409: issue -> when it last entered the queue (starvation guard)
|
|
408
411
|
const heads = new Set(saved?.heads ?? []); // #4409: decomposed sub-issues not started yet: the head of their priority band
|
|
409
412
|
let errorTimes = [...(saved?.errorTimes ?? [])];
|
|
@@ -472,7 +475,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
472
475
|
// #5652: with host fallback off (execution.host_fallback / host.role: orchestrator) the host is orchestrator-only: no re-placement here
|
|
473
476
|
// #5931: a credentials block pinned the issue to the host (ledger hostPin): applied on readmit whatever host fallback says
|
|
474
477
|
if (ledgers.get(n)?.hostPin) return { where: "local", reason: "host pin: ops_credentials block" };
|
|
475
|
-
if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_ENGINE_SKEW].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
|
|
478
|
+
if (hostFallbackOn() && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_ENGINE_SKEW].includes(recovering.get(n)?.code)) return { where: "local", reason: `host capability: recovering ${recovering.get(n).code}` };
|
|
476
479
|
// #5371: a mechanical recovery never repeats the placement of the run that failed (a remote sandbox env defect recurs there), and a remote validate failure is rerun on the host
|
|
477
480
|
if (recovering.get(n)?.code === ENV_VALIDATE_PLACEMENT || (MECHANICAL_CODES.includes(recovering.get(n)?.code) && recovering.get(n)?.where === "remote")) {
|
|
478
481
|
if (hostFallbackOn()) return { where: "local", reason: `different placement: recovering ${rec.code} off the remote run` };
|
|
@@ -507,7 +510,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
507
510
|
const recoveryMax = Number.isInteger(recovery?.maxAttempts) && recovery.maxAttempts > 0 ? recovery.maxAttempts : 0;
|
|
508
511
|
// #4725: mechanical/env codes recover on their own budget (>= the conformance one); 0 maxAttempts still turns recovery off.
|
|
509
512
|
const mechMax = recoveryMax && Number.isInteger(recovery?.mechanicalMaxAttempts) && recovery.mechanicalMaxAttempts > 0 ? Math.max(recovery.mechanicalMaxAttempts, recoveryMax) : recoveryMax;
|
|
510
|
-
const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING]; // #5232: deterministic for a frozen command (a timeout is load, not listed)
|
|
513
|
+
const REPEAT_ENV_CODES = [OUTCOME_CODES.ENV_REPRO_UNRUNNABLE, OUTCOME_CODES.ENV_TOOL_MISSING, OUTCOME_CODES.ENV_CAPABILITY_DOCKER]; // #6196: a docker-less host repeats identically // #5232: deterministic for a frozen command (a timeout is load, not listed)
|
|
511
514
|
const sigOf = (d) => String(d ?? "").replace(/\s+/g, " ").trim();
|
|
512
515
|
// #5592: env.tool_missing repeats are the same defect when the same tools are missing, whatever else the detail says (probe lines, ids, paths vary per run)
|
|
513
516
|
const toolsOf = (d) => { const m = /(?:host|sandbox) is missing ([^\n]+?), so validate command/i.exec(String(d ?? "")); return m ? m[1].split(/\s*,\s*/).sort().join(",") : null; };
|
|
@@ -555,7 +558,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
555
558
|
...(stackedTried.size ? { stacked: toObj(stackedOf), stackedTried: [...stackedTried] } : {}),
|
|
556
559
|
...(requeueApplied.size ? { requeueApplied: [...requeueApplied], requeued: toObj(requeuedInfo) } : {}),
|
|
557
560
|
...(relabelled.size ? { relabelled: [...relabelled] } : {}), ...(cancelled ? { cancelled } : {}), ...(train ? { train: train.snapshot() } : {}),
|
|
558
|
-
...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), ...(heads.size ? { heads: [...heads] } : {}),
|
|
561
|
+
...(estimate ? { estimates: toObj(estimates), enqueued: toObj(enqueued) } : {}), queueClock: queueClock.toJSON(), ...(heads.size ? { heads: [...heads] } : {}),
|
|
559
562
|
...(engineSigs.size ? { engineSigs: toObj(engineSigs) } : {}), ...(heldSigs.size ? { heldSigs: toObj(heldSigs) } : {}), ...(deterministic.size ? { deterministicSigs: [...deterministic] } : {}), ...(toolReadmits.size ? { toolReadmits: [...toolReadmits] } : {}), ...(select ? { select } : {}), ...(readmit.size ? { readmit: toObj(readmit) } : {}), ...(envSigs.size ? { envSigs: toObj(envSigs) } : {}), ...(ledgers.size ? { attempts: toObj(ledgers) } : {}), ...(selMatched.size ? { selMatched: [...selMatched] } : {}) });
|
|
560
563
|
};
|
|
561
564
|
const update = (row) => { store?.log?.(row); onUpdate(row); };
|
|
@@ -1167,7 +1170,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1167
1170
|
update({ ...row, detail: `stopped by cancel: ${r?.code ?? row.outcome}${r?.detail ? ` ${r.detail}` : ""}` });
|
|
1168
1171
|
return;
|
|
1169
1172
|
}
|
|
1170
|
-
if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) capDefers.delete(n); // #5746: a lane the pool accepted resets the capacity count
|
|
1173
|
+
if (!(row.outcome === "deferred" && r?.code === "sandbox.capacity")) { capDefers.delete(n); capQuiet.delete(n); } // #5746: a lane the pool accepted resets the capacity count
|
|
1171
1174
|
if (row.outcome === "deferred" && (r?.code === "stack.replan" || r?.code === "stack.restart") && !cancelled) {
|
|
1172
1175
|
// #5833: the stacked dependent's PR and branch were dropped. replan: it builds as a normal lane on the lane base (today's held/skipped
|
|
1173
1176
|
// rules decide while its dependency is unsatisfied); restart: it may stack again on the dependency's new head, from the frozen contract.
|
|
@@ -1241,6 +1244,12 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1241
1244
|
return;
|
|
1242
1245
|
}
|
|
1243
1246
|
requeue(n, capGated ? 0 : delayMs); done(); save();
|
|
1247
|
+
// #6204: admit-or-don't-start: a pool refusal the capacity sample gates is a wait, not a deferral row: the issue stays pending and
|
|
1248
|
+
// the sample (polled every pollMs) wakes it. The first refusal of a wait is one batch event; queue_wait is attributed to `capacity` by the clock.
|
|
1249
|
+
if (capGated && r?.code === "sandbox.capacity") {
|
|
1250
|
+
if (!capQuiet.has(n)) { capQuiet.add(n); try { store?.log?.({ event: "capacity.wait", issue: n, batch: batchId ?? null, reason: r.reason ?? null }); } catch { /* best effort */ } }
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1244
1253
|
update({ ...row, detail: `requeued in ${Math.round(pol.delayMs / 1000)}s: ${r?.code ?? "deferred"}${r?.detail ? ` ${r.detail}` : ""}` });
|
|
1245
1254
|
return;
|
|
1246
1255
|
}
|
|
@@ -1273,7 +1282,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1273
1282
|
lostSeen.set(la, [...win, lostNow]);
|
|
1274
1283
|
}
|
|
1275
1284
|
if (row.outcome === "engine-error") {
|
|
1276
|
-
const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) : null;
|
|
1285
|
+
const ag = r?.agent ?? r?.sandbox?.agent ?? null, hs = ag && breaker ? hostSignature(r, row.detail) ?? (isTransientEngineError(row.detail) ? "transport" : null) : null; // #6204: a host's link failures pause that host, not the batch
|
|
1277
1286
|
const sc = hs ? await scopedEngineError(ag, hs) : null;
|
|
1278
1287
|
const qn = sc?.quarantined ? (quarantineRequeues.get(n) ?? 0) + 1 : 0; // a lane waits out the quarantine a bounded number of times, then counts as an ordinary engine-error (batch breaker included)
|
|
1279
1288
|
if (sc?.quarantined && qn <= QUARANTINE_REQUEUES) { quarantineRequeues.set(n, qn); // #5988: an agent in quarantine: its lane waits and is requeued without a relaunch or breaker count; unaffected agents keep admitting
|
|
@@ -1368,7 +1377,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1368
1377
|
const sameHostReplay = !repeatEnv && !prior && row.code === OUTCOME_CODES.ENV_TOOL_MISSING && row.placement?.where !== "remote" && toolsOf(row.detail) !== null;
|
|
1369
1378
|
// #5805: an env defect the host still has is held until the engine, the batch env or the host changes, not ended or re-run.
|
|
1370
1379
|
// A tool-missing recovery that would run on the host (not the #5423 remote retry) is not launched while the probe still misses the tool.
|
|
1371
|
-
const envNoHost = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
|
|
1380
|
+
const envNoHost = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
|
|
1372
1381
|
const lacking = row.code === OUTCOME_CODES.ENV_TOOL_MISSING ? toolsOf(row.detail) : null;
|
|
1373
1382
|
if (ehOn && !envNoHost && !row.securityEscalated) {
|
|
1374
1383
|
let stillLacks = false;
|
|
@@ -1390,8 +1399,8 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1390
1399
|
decided({ issue: n, what: `no further recovery for ${row.code}: the same failure repeated`, why: firstLine(row.detail), alternative: "requeue another recovery lane that rebuilds against the same frozen command" });
|
|
1391
1400
|
}
|
|
1392
1401
|
// #5652: a remote lane's tool/capability end is not recovered on the host when host fallback is off; the lane message names the fix
|
|
1393
|
-
const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
|
|
1394
|
-
if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)`, why: firstLine(row.detail), alternative: "re-place the lane on the host" });
|
|
1402
|
+
const noHostRecovery = !hostFallbackOn() && row.placement?.where === "remote" && [OUTCOME_CODES.ENV_CAPABILITY_REMOTE, OUTCOME_CODES.ENV_CAPABILITY_DOCKER, OUTCOME_CODES.ENV_TOOL_MISSING].includes(row.code);
|
|
1403
|
+
if (noHostRecovery) decided({ issue: n, what: `no host re-placement for ${row.code}: host fallback is off (execution.host_fallback / host.role: orchestrator)${row.code === OUTCOME_CODES.ENV_CAPABILITY_DOCKER ? "; the Docker-dependent validate is deferred to CI" : ""}`, why: firstLine(row.detail), alternative: "re-place the lane on the host" }); // #6196
|
|
1395
1404
|
// #5749: an env.validate_timeout is host load, so its recovery lane is not started while the host is overloaded (it would time out again)
|
|
1396
1405
|
if (overload && row.code === ENV_VALIDATE_TIMEOUT && classifyNeedsHuman(facts) === "recoverable" && used < max) {
|
|
1397
1406
|
const isOver = () => { try { return overload()?.overloaded === true; } catch { return false; } };
|
|
@@ -1482,10 +1491,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
1482
1491
|
const pl = placed.get(n) ?? (remote ? (remoteRun.has(n) ? { where: "remote", reason: "mode remote" } : (placeOf(n) ?? undefined)) : undefined);
|
|
1483
1492
|
placed.delete(n);
|
|
1484
1493
|
const queueMs = Number.isFinite(enqueued.get(n)) ? Math.max(0, now() - enqueued.get(n)) : null; // #4908: queue_wait in the phase ledger
|
|
1494
|
+
const qc = queueClock.take(n, now()); // #6203
|
|
1485
1495
|
heads.delete(n); enqueued.delete(n); busyNoted.delete(n);
|
|
1486
|
-
const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
|
|
1496
|
+
const rec = { startedAt: now(), ...(plan ? { plan: true } : {}), ...(stackedOn ? { stackedOn } : {}), ...(queueMs != null ? { queueMs } : {}), ...(qc ? { queueCauses: qc.causes, queueTotalMs: qc.total_ms } : {}), ...(lane ? { lane } : {}), ...(remoteRun.has(n) ? { remote: true } : {}), ...(pl ? { placement: pl } : {}) };
|
|
1487
1497
|
if (!firstAdmit.has(n)) firstAdmit.set(n, rec.startedAt); // #5834: chain wall time starts at the first admission, plan lane included
|
|
1488
|
-
runRecs.set(n, rec); keptBoxes.delete(n); notBefore.delete(n); capReasons.delete(n); save();
|
|
1498
|
+
runRecs.set(n, rec); keptBoxes.delete(n); notBefore.delete(n); capReasons.delete(n); capQuiet.delete(n); save();
|
|
1489
1499
|
track(n, (async () => {
|
|
1490
1500
|
// Pre-filter once per issue (a requeued issue is not re-checked); fail-open: an error means a normal lane.
|
|
1491
1501
|
if (prefilter && !checked.has(n)) { let pf = null; try { pf = await prefilter(n, lane); } catch { pf = null; } checked.set(n, pf); save(); }
|
|
@@ -2175,6 +2185,15 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
2175
2185
|
await refreshBlocked();
|
|
2176
2186
|
await refreshBaseWaits();
|
|
2177
2187
|
checkGates();
|
|
2188
|
+
queueClock.tick(pending, (n) => { // #6203: why each pending issue waits right now (the order is the precedence)
|
|
2189
|
+
if (opPause) return "pause";
|
|
2190
|
+
if (tripped) return "breaker";
|
|
2191
|
+
if (opHeld.has(n)) return "hold";
|
|
2192
|
+
if (blocked.has(n) || edges(n).some((d) => !(results.has(d) && SATISFIED.has(results.get(d).outcome)))) return "dependency";
|
|
2193
|
+
if (poolDown && isRemote(n)) return "host_offline";
|
|
2194
|
+
if (running.size >= K() || (notBefore.get(n) ?? 0) > t || capReasons.has(n) || baseHeld.has(n) || pfAll) return "capacity";
|
|
2195
|
+
return "other";
|
|
2196
|
+
}, t);
|
|
2178
2197
|
// #4866: lane preflight. A failing check holds admission (all lanes, or only remote ones by its scope), says why once per batch,
|
|
2179
2198
|
// and is re-checked every pass so the batch resumes on its own; it is not an engine-error, so the breaker never sees it.
|
|
2180
2199
|
pfAll = false; pfRemote = false;
|
|
@@ -2361,9 +2380,11 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
2361
2380
|
let wake = waits.length ? Math.max(0, Math.min(...waits) - t) : null;
|
|
2362
2381
|
if (holdUntil && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4446: a cleared hold (forgedock limits clear) admits on the next poll
|
|
2363
2382
|
if (getPause && pending.length && (opPause || running.size)) wake = Math.min(wake ?? pollMs, pollMs); // #5975: an --unpause or expiry
|
|
2383
|
+
if (pending.some((n) => capQuiet.has(n) && !(notBefore.get(n) > t))) wake = Math.min(wake ?? pollMs, pollMs); // #6204: a capacity-gated issue is woken by the next pool sample, not a per-issue timer
|
|
2364
2384
|
if ((getParallel || getHeld) && pending.length) wake = Math.min(wake ?? pollMs, pollMs);
|
|
2365
2385
|
if (offered.size && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // a slot another batch frees
|
|
2366
2386
|
if (pending.some((n) => remoteCapped.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5138: a live --set-max-remote raise
|
|
2387
|
+
if ((getAdded || getRequeued) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #6197: an --add/--requeue is read within one poll even when every pending issue is held or waits on a long timer
|
|
2367
2388
|
if ((getAdded || getRequeued || (getChildren && addsEpicChildren(autoChildren?.mode))) && running.size) wake = Math.min(wake ?? pollMs, pollMs); // #4408/#4550: an add or requeue while only lanes run
|
|
2368
2389
|
if (getRequeued && pending.some((n) => quota.has(n) || notBefore.has(n))) wake = Math.min(wake ?? pollMs, pollMs); // #5203: a --requeue releasing a quota pause
|
|
2369
2390
|
if ((pfAll || pfRemote || baseRedHold) && pending.length) wake = Math.min(wake ?? pollMs, pollMs); // #4866
|
|
@@ -2393,6 +2414,7 @@ export async function orchestrate({ issues, parallel = 3, runOne, readBody, pref
|
|
|
2393
2414
|
else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n)) && holdExpiring([...opHeldHit]) && !cancelled) await nap(wake ?? pollMs); // #5469: a hold with an expiry keeps the batch open until it expires (re-admit or alert), not finalised silently
|
|
2394
2415
|
else if (pending.length && opHeldHit.size && !pending.some((n) => !opHeldHit.has(n) && isReady(n))) { if (await drainAdds()) continue; break; } // #4592: held by the operator: pending for a --resume
|
|
2395
2416
|
else if (pending.length && (driftHeld.size || integHeld.size)) { if (await drainAdds()) continue; break; } // held by a drift flag (block_dispatch) or a red integration streak (#4667): pending for a later batch
|
|
2417
|
+
else if (pending.some((n) => capQuiet.has(n))) await nap(Math.min(wake ?? pollMs, pollMs)); // #6204: waiting for a pool slot with nothing running: the next capacity sample wakes it
|
|
2396
2418
|
else if (pending.some((n) => remoteCapped.has(n))) await nap(wake ?? pollMs); // #5138: live max_remote 0: wait for a raise or another placement
|
|
2397
2419
|
else if (pending.length) { // nothing runnable, nothing running, nothing waiting on time: a dependency cycle
|
|
2398
2420
|
// #5162: only real cycles are labelled so; the rest name the cycle member (or failed root) that blocks them
|
|
@@ -2525,7 +2547,7 @@ export function formatTable(rows) {
|
|
|
2525
2547
|
*/
|
|
2526
2548
|
export function phasesOf(r, rec) {
|
|
2527
2549
|
if (!r?.phases || typeof r.phases !== "object" || !Object.keys(r.phases).length) return null;
|
|
2528
|
-
return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(rec.queueMs), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
|
|
2550
|
+
return { ...(Number.isFinite(rec?.queueMs) && rec.queueMs > 0 ? { queue_wait: { ms: Math.round(Math.max(rec.queueMs, rec.queueTotalMs ?? 0)), ...(rec.queueCauses ? { causes: rec.queueCauses } : {}), ...((r.sandbox?.agent ?? r.agent) ? { worker: r.sandbox?.agent ?? r.agent } : {}) } } : {}), ...r.phases };
|
|
2529
2551
|
}
|
|
2530
2552
|
|
|
2531
2553
|
export function formatWaitSummary(rows, heavyStats = null) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* queue_wait by cause (#6203). One clock per batch: an issue's wait starts when it is first seen pending ("ready") and
|
|
5
|
+
* accrues per cause while it is pending; it does NOT reset on a requeue (the old `enqueued` stamp did), and it stops while the
|
|
6
|
+
* issue runs. The runner calls `tick` once per scheduling pass with a pure `causeOf(issue)`; `take` closes the issue's
|
|
7
|
+
* accrual when its lane starts and returns the totals so far. State is plain JSON so a resumed batch keeps it.
|
|
8
|
+
*/
|
|
9
|
+
export const QUEUE_CAUSES = Object.freeze(["hold", "pause", "capacity", "breaker", "dependency", "host_offline", "other"]);
|
|
10
|
+
const isNum = (x) => typeof x === "number" && Number.isFinite(x);
|
|
11
|
+
|
|
12
|
+
export function createQueueClock(saved = null) {
|
|
13
|
+
const acc = new Map(Object.entries(saved?.acc ?? {}).map(([n, c]) => [n, { ...c }]));
|
|
14
|
+
const readyAt = new Map(Object.entries(saved?.readyAt ?? {}));
|
|
15
|
+
const last = new Map(); // issue -> {at, cause}; not persisted: a restart opens a fresh segment
|
|
16
|
+
const add = (n, cause, ms) => { if (ms > 0) { const a = acc.get(n) ?? {}; a[cause] = (a[cause] ?? 0) + ms; acc.set(n, a); } };
|
|
17
|
+
const close = (n, t) => { const l = last.get(n); if (l) add(String(n), l.cause, Math.max(0, t - l.at)); last.delete(n); };
|
|
18
|
+
return {
|
|
19
|
+
/** Attribute the time since the previous tick to the issue's previous cause, then open a segment with its current cause. */
|
|
20
|
+
tick(pending, causeOf, t) {
|
|
21
|
+
const keep = new Set();
|
|
22
|
+
for (const n of pending) {
|
|
23
|
+
const k = String(n); keep.add(k);
|
|
24
|
+
if (!readyAt.has(k)) readyAt.set(k, t);
|
|
25
|
+
close(k, t);
|
|
26
|
+
let c = "other"; try { c = causeOf(n); } catch { /* fail-open */ }
|
|
27
|
+
last.set(k, { at: t, cause: QUEUE_CAUSES.includes(c) ? c : "other" });
|
|
28
|
+
}
|
|
29
|
+
for (const k of [...last.keys()]) if (!keep.has(k)) close(k, t); // left the queue without take(): stop accruing
|
|
30
|
+
},
|
|
31
|
+
/** The issue starts: close its segment and return {total_ms, causes, ready_at}; null when it was never queued. */
|
|
32
|
+
take(n, t) {
|
|
33
|
+
const k = String(n); close(k, t);
|
|
34
|
+
const causes = acc.get(k);
|
|
35
|
+
if (!causes) return null;
|
|
36
|
+
return { total_ms: Math.round(Object.values(causes).reduce((a, b) => a + b, 0)), causes: Object.fromEntries(Object.entries(causes).map(([c, v]) => [c, Math.round(v)])), ready_at: isNum(Number(readyAt.get(k))) ? Number(readyAt.get(k)) : null };
|
|
37
|
+
},
|
|
38
|
+
/** The issue ended for good: forget it. */
|
|
39
|
+
drop(n) { const k = String(n); acc.delete(k); readyAt.delete(k); last.delete(k); },
|
|
40
|
+
toJSON: () => ({ acc: Object.fromEntries(acc), readyAt: Object.fromEntries(readyAt) }),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
@@ -20,6 +20,10 @@ export const CI_GREEN_POLL_MS = 30_000;
|
|
|
20
20
|
export const CI_GREEN_MAX_WAIT_MIN = 40;
|
|
21
21
|
const SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
|
|
22
22
|
const json = (s) => JSON.parse(String(s || "null"));
|
|
23
|
+
/** `gh api --paginate --jq '.x[] | {..}'` prints one JSON object per line, across all pages. */
|
|
24
|
+
const ndjson = (s) => String(s || "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
|
|
25
|
+
/** Polls (CI_GREEN_POLL_MS apart) to wait for a rerun's attempt number to advance before the checks are read again. */
|
|
26
|
+
const RERUN_SETTLE_POLLS = 10;
|
|
23
27
|
|
|
24
28
|
/** forge.yaml `release.ci_green.max_wait_min` and `release.block_severity` (lowest blocking severity; default high) -> `{ciGreen, blockSeverity}`; only set keys are returned. */
|
|
25
29
|
export function ciGreenKeys(r) {
|
|
@@ -76,9 +80,9 @@ export function realCiSeam(ctx) {
|
|
|
76
80
|
isDraft: async (pr) => Boolean(json(await gh(["pr", "view", String(pr), "--repo", repo, "--json", "isDraft"]))?.isDraft),
|
|
77
81
|
headOf: async (pr) => String(await gh(["pr", "view", String(pr), "--repo", repo, "--json", "headRefOid", "--jq", ".headRefOid"])).trim(),
|
|
78
82
|
checks: async ({ head }) => {
|
|
79
|
-
const runs =
|
|
83
|
+
const runs = ndjson(await gh(["api", "--paginate", `repos/${repo}/commits/${head}/check-runs?per_page=100`, "--jq", ".check_runs[] | {name, status, conclusion, link: .details_url}"]));
|
|
80
84
|
let statuses = [];
|
|
81
|
-
try { statuses =
|
|
85
|
+
try { statuses = ndjson(await gh(["api", "--paginate", `repos/${repo}/commits/${head}/status?per_page=100`, "--jq", ".statuses[] | {name: .context, state, link: .target_url}"])); } catch { /* check runs alone */ }
|
|
82
86
|
return [
|
|
83
87
|
...runs.map((k) => ({ name: k.name, bucket: bucketOf(k.status, k.conclusion), link: k.link })),
|
|
84
88
|
...statuses.map((k) => ({ name: k.name, bucket: k.state === "success" ? "pass" : k.state === "pending" ? "pending" : "fail", link: k.link })),
|
|
@@ -158,14 +162,24 @@ async function waitGreen(ctx, pr, seam) {
|
|
|
158
162
|
}
|
|
159
163
|
ctx.save?.();
|
|
160
164
|
let reran = 0;
|
|
165
|
+
const before = new Map();
|
|
161
166
|
for (const id of ids.keys()) {
|
|
162
|
-
|
|
167
|
+
const attempt = await seam.runAttempt(id);
|
|
168
|
+
if (!attemptGuard({ attempt }).allow) continue;
|
|
163
169
|
await seam.rerunFailed(id);
|
|
170
|
+
before.set(id, attempt);
|
|
164
171
|
reran++;
|
|
165
172
|
}
|
|
166
173
|
if (!reran) return { red: true, head, failing: st.failing };
|
|
167
174
|
ctx.io.print?.(`release: ci-green: rerunning ${[...ids.values()].join(", ")} once`);
|
|
168
|
-
|
|
175
|
+
// The old failure stays visible until GitHub registers the new attempt: wait for the attempt number to advance (bounded), not a fixed sleep.
|
|
176
|
+
for (let n = 0; n < RERUN_SETTLE_POLLS; n++) {
|
|
177
|
+
await seam.sleep(CI_GREEN_POLL_MS);
|
|
178
|
+
if (seam.now() >= deadline) break;
|
|
179
|
+
let settled = true;
|
|
180
|
+
for (const [id, was] of before) { const now = await seam.runAttempt(id); if (was == null || now == null || now <= was) settled = false; }
|
|
181
|
+
if (settled) break;
|
|
182
|
+
}
|
|
169
183
|
}
|
|
170
184
|
}
|
|
171
185
|
|
|
@@ -27,6 +27,29 @@ function seam(snaps, o = {}) {
|
|
|
27
27
|
const ctx = (s, extra = {}) => ({ io: { ciGreen: s, print() {} }, repo: "o/r", def: "main", config: {}, state: { steps: { "release-pr": { done: true, result: { pr: 7 } } } }, save() {}, ...extra });
|
|
28
28
|
const row = (bucket, id = 1) => ({ name: "build", bucket, link: link(id) });
|
|
29
29
|
|
|
30
|
+
describe("ci-green rerun lag and pagination (#6177)", () => {
|
|
31
|
+
it("waits for the rerun attempt to register instead of reading the stale failure as red", async () => {
|
|
32
|
+
const s = seam([]); let att = 1, polls = 0;
|
|
33
|
+
s.runAttempt = async () => { if (s.log.includes("rerun:5") && ++polls > 3) att = 2; return att; };
|
|
34
|
+
s.checks = async () => [row(att >= 2 ? "pass" : "fail", 5)];
|
|
35
|
+
const r = await ciGreenStep(ctx(s));
|
|
36
|
+
assert.equal(r.green, true); assert.equal(s.log.filter((x) => x === "rerun:5").length, 1);
|
|
37
|
+
});
|
|
38
|
+
it("stays bounded when the attempt never advances", async () => {
|
|
39
|
+
const s = seam([[row("fail", 5)]]);
|
|
40
|
+
const c = ctx(s, { io: { ciGreen: s, print() {}, review: {} } });
|
|
41
|
+
const r = await ciGreenWait(c, 7, { noFix: true });
|
|
42
|
+
assert.equal(r.red, true); assert.ok(s.log.filter((x) => x === "sleep").length <= 12);
|
|
43
|
+
});
|
|
44
|
+
it("reads every page of check runs", async () => {
|
|
45
|
+
const { realCiSeam } = await import("./release-cigreen.mjs");
|
|
46
|
+
const calls = [];
|
|
47
|
+
const gh = async (a) => { calls.push(a); const all = a.includes("--paginate"); return a.join(" ").includes("/status") ? "" : Array.from({ length: all ? 150 : 100 }, (_, i) => JSON.stringify({ name: `c${i}`, status: "completed", conclusion: "success" })).join("\n"); };
|
|
48
|
+
const out = await realCiSeam({ io: { gh }, repo: "o/r" }).checks({ head: H });
|
|
49
|
+
assert.equal(out.length, 150); assert.ok(calls.every((a) => a[0] !== "api" || a.includes("--paginate")));
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
30
53
|
describe("ci-green step (#6164)", () => {
|
|
31
54
|
it("is a default release step between release-pr and review", () => {
|
|
32
55
|
const i = RELEASE_STEPS.indexOf("ci-green");
|