forgedock 1.65.0 → 1.67.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 +2 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +143 -19
- package/bin/forgedock.mjs +7 -0
- package/bin/help-text.mjs +3 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/advisory.test.mjs +49 -0
- package/bin/lean/amendment-schema.mjs +31 -0
- package/bin/lean/attempts.mjs +159 -0
- package/bin/lean/attempts.test.mjs +127 -0
- package/bin/lean/basered.mjs +55 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +13 -5
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +62 -0
- package/bin/lean/batch.test.mjs +119 -3
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/commentstate.mjs +41 -0
- package/bin/lean/commentstate.test.mjs +32 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +4 -2
- package/bin/lean/conformance.mjs +35 -3
- package/bin/lean/conformance.test.mjs +52 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/execution.mjs +31 -13
- package/bin/lean/execution.test.mjs +46 -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/lean.mjs +130 -30
- package/bin/lean/lean.test.mjs +138 -47
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +74 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +84 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +202 -28
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/prompts.mjs +6 -10
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +38 -2
- package/bin/lean/recurrence.test.mjs +56 -1
- package/bin/lean/sandbox-remote.mjs +33 -2
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +19 -0
- package/bin/lean/schedd.mjs +97 -10
- package/bin/lean/schedd.test.mjs +138 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +37 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/verify.mjs +2 -1
- package/bin/pool/agent.mjs +46 -8
- package/bin/pool/cache-sweep.mjs +41 -4
- package/bin/pool/cli.mjs +28 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/lane-tools.mjs +21 -0
- package/bin/pool/mirror-seed.mjs +21 -2
- package/bin/pool/router.mjs +6 -2
- 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/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +1 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +2 -1
- package/scripts/check-devdocs-freshness.sh +1 -1
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/** #5985: closed-loop lane concurrency. */
|
|
4
|
+
import { describe, it } from "node:test";
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { makeController, classifyRepo, conditionCleared, formatConcurrency, poolReason, REFUSAL_HOLD_MS } from "./concurrency.mjs";
|
|
8
|
+
|
|
9
|
+
const green = { load_per_core: 0.4, mem_available_gb: 12 };
|
|
10
|
+
const mk = (o = {}) => { const c = { t: 1_000_000 }; return { c, ctl: makeController({ ceiling: 8, now: () => c.t, ...o }) }; };
|
|
11
|
+
|
|
12
|
+
describe("controller (#5985)", () => {
|
|
13
|
+
it("halves on pool.host_load, increases +1 under a green pool, never above the ceiling or below 1", () => {
|
|
14
|
+
const { c, ctl } = mk();
|
|
15
|
+
assert.equal(ctl.operating(), 8, "no signal: K is the ceiling");
|
|
16
|
+
const e = ctl.refused({ issue: 1, code: "pool.host_load", live: { load_per_core: 2.2 } });
|
|
17
|
+
assert.equal(e.change, "decrease");
|
|
18
|
+
assert.equal(ctl.operating(), 4);
|
|
19
|
+
assert.equal(ctl.observe(green), null, "refusal in the last N minutes: no increase");
|
|
20
|
+
c.t += REFUSAL_HOLD_MS;
|
|
21
|
+
assert.equal(ctl.observe(green).change, "increase");
|
|
22
|
+
assert.equal(ctl.operating(), 5);
|
|
23
|
+
for (let i = 0; i < 10; i++) ctl.observe(green);
|
|
24
|
+
assert.equal(ctl.operating(), 8);
|
|
25
|
+
assert.equal(ctl.limiting(), "ceiling");
|
|
26
|
+
for (let i = 0; i < 6; i++) { c.t += 2000; ctl.refused({ code: "pool.host_mem" }); }
|
|
27
|
+
assert.equal(ctl.operating(), 1);
|
|
28
|
+
});
|
|
29
|
+
it("a high load alone halves; an unknown pool and a non-pool refusal leave K unchanged", () => {
|
|
30
|
+
const { ctl } = mk();
|
|
31
|
+
assert.equal(ctl.refused({ code: "sandbox.capacity" }), null);
|
|
32
|
+
assert.equal(ctl.observe(null), null);
|
|
33
|
+
assert.equal(ctl.observe({ load_per_core: 0.2 }), null);
|
|
34
|
+
assert.ok(ctl.refused({ live: { load_per_core: 1.8 } }));
|
|
35
|
+
assert.equal(ctl.operating(), 4);
|
|
36
|
+
assert.equal(ctl.limiting(), "host_load");
|
|
37
|
+
});
|
|
38
|
+
it("a red pool (low memory or load >= 1) does not increase", () => {
|
|
39
|
+
const { c, ctl } = mk();
|
|
40
|
+
ctl.refused({ code: "pool.host_load" }); c.t += REFUSAL_HOLD_MS;
|
|
41
|
+
assert.equal(ctl.observe({ load_per_core: 1.2, mem_available_gb: 12 }), null);
|
|
42
|
+
assert.equal(ctl.observe({ load_per_core: 0.3, mem_available_gb: 5 }), null);
|
|
43
|
+
});
|
|
44
|
+
it("classifies heavy repos from usage-history cpu_avg > 1.5 and caps heavy lanes below light", () => {
|
|
45
|
+
const rows = [{ repo: "a/h", cpu_avg: 3 }, { repo: "a/h", cpu_avg: 2 }, { repo: "a/l", cpu_avg: 0.4 }];
|
|
46
|
+
assert.equal(classifyRepo(rows, "a/h"), "heavy");
|
|
47
|
+
assert.equal(classifyRepo(rows, "a/l"), "light");
|
|
48
|
+
assert.equal(classifyRepo(rows, "a/none"), "light", "no history: light");
|
|
49
|
+
const { ctl } = mk({ ceiling: 16 });
|
|
50
|
+
assert.equal(ctl.operating("light"), 16);
|
|
51
|
+
assert.equal(ctl.operating("heavy"), 6);
|
|
52
|
+
assert.equal(ctl.limiting("heavy"), "heavy cap");
|
|
53
|
+
});
|
|
54
|
+
it("names the cleared condition and formats running/K/ceiling (limiting factor)", () => {
|
|
55
|
+
assert.equal(conditionCleared("pool.host_load", { load_per_core: 1.2 }), false);
|
|
56
|
+
assert.equal(conditionCleared("host_load", { load_per_core: 0.9 }), true);
|
|
57
|
+
assert.equal(conditionCleared("pool.host_mem", { mem_available_gb: 9 }), true);
|
|
58
|
+
assert.equal(conditionCleared("pool.host_mem", {}), null);
|
|
59
|
+
assert.equal(conditionCleared("pool.projected_peak", green), null);
|
|
60
|
+
assert.equal(poolReason("pool.disk_cap"), "disk");
|
|
61
|
+
assert.equal(poolReason("sandbox.capacity"), "");
|
|
62
|
+
assert.equal(formatConcurrency({ running: 3, k: 4, ceiling: 8, factor: "host_load" }), "concurrency: 3/4/8 (host_load)");
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe("503-storm replay (#5985)", () => {
|
|
67
|
+
it("at most 1 refusal per lane per 5 min: refused lanes hold until the condition clears", () => {
|
|
68
|
+
const fx = JSON.parse(readFileSync(new URL("./fixtures/capacity-storm.json", import.meta.url), "utf8"));
|
|
69
|
+
const c = { t: 0 };
|
|
70
|
+
const ctl = makeController({ ceiling: fx.lanes, now: () => c.t });
|
|
71
|
+
const byLane = new Map();
|
|
72
|
+
for (const a of fx.attempts) (byLane.get(a.lane) ?? byLane.set(a.lane, []).get(a.lane)).push(a);
|
|
73
|
+
const refusals = new Map();
|
|
74
|
+
for (c.t = 0; c.t <= fx.endMs; c.t += fx.pollMs) {
|
|
75
|
+
const cap = c.t < fx.clearsAtMs ? { load_per_core: 2.1, mem_available_gb: 1.2 } : { load_per_core: 0.6, mem_available_gb: 9 };
|
|
76
|
+
ctl.observe(cap);
|
|
77
|
+
for (const [lane, rows] of byLane) {
|
|
78
|
+
if (ctl.holding(lane, cap)) continue;
|
|
79
|
+
const storm = c.t < fx.clearsAtMs;
|
|
80
|
+
if (!storm) { ctl.release(lane); continue; }
|
|
81
|
+
const rec = rows.reduce((b, r) => (Math.abs(r.at - c.t) < Math.abs(b.at - c.t) ? r : b)); // the recorded refusal code nearest this attempt
|
|
82
|
+
ctl.refused({ issue: lane, code: rec.code, live: cap });
|
|
83
|
+
(refusals.get(lane) ?? refusals.set(lane, []).get(lane)).push(c.t);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
assert.ok(refusals.size === fx.lanes);
|
|
87
|
+
for (const [lane, ts] of refusals) for (let i = 0; i < ts.length; i++) {
|
|
88
|
+
const inWin = ts.filter((x) => x >= ts[i] && x < ts[i] + 300_000).length;
|
|
89
|
+
assert.ok(inWin <= 1, `lane ${lane}: ${inWin} refusals within 5 min`);
|
|
90
|
+
}
|
|
91
|
+
const unreplayed = fx.attempts.length; // the unconstrained timer retry would have refused each lane every minute
|
|
92
|
+
assert.ok([...refusals.values()].flat().length < unreplayed / 3);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe("heavy lanes in orchestrate (#5985)", () => {
|
|
97
|
+
it("a heavy repo's lanes run at most the heavy cap at once while light lanes keep the rest of K", async () => {
|
|
98
|
+
const { orchestrate } = await import("./orchestrate.mjs");
|
|
99
|
+
const usageRows = [{ repo: "o/heavy", cpu_avg: 3 }, { repo: "o/light", cpu_avg: 0.3 }];
|
|
100
|
+
const run = async (repo) => {
|
|
101
|
+
let cur = 0, max = 0;
|
|
102
|
+
const events = [];
|
|
103
|
+
await orchestrate({ issues: [1, 2, 3, 4, 5, 6], parallel: 6, usageRows: () => usageRows, repoSlug: "o/none", repoOf: () => repo, readBody: async () => "", onUpdate: (e) => events.push(e),
|
|
104
|
+
sleep: async () => { await new Promise((r) => setImmediate(r)); },
|
|
105
|
+
runOne: async () => { cur++; max = Math.max(max, cur); await new Promise((r) => setTimeout(r, 20)); cur--; return { terminalReason: "merged", pr: 1 }; } });
|
|
106
|
+
return { max, events };
|
|
107
|
+
};
|
|
108
|
+
const heavy = await run("o/heavy"), light = await run("o/light");
|
|
109
|
+
assert.equal(heavy.max, 2, "ceiling 6, heavy cap ceil(6/3)");
|
|
110
|
+
assert.equal(light.max, 6);
|
|
111
|
+
assert.ok(heavy.events.some((e) => e.event === "concurrency" && e.change === "heavy-cap"));
|
|
112
|
+
});
|
|
113
|
+
});
|
|
@@ -204,10 +204,12 @@ describe("conformance gate end-to-end (real git, disposable repo)", { skip: !HAV
|
|
|
204
204
|
res.amendments = [{ kind: "add-requirement", requirement: req("R3"), why: "the issue's requirement 3 was missing" }, { kind: "add-deliverable", id: "D3", path: "src/routes/export.js", why: "implements R3" }]; } });
|
|
205
205
|
merged(o); assert.ok(o.staging.export); assert.ok(o.markers.includes("FORGE:AMENDMENT"));
|
|
206
206
|
});
|
|
207
|
-
it("3 scope creep: an unauthorized billing change is
|
|
207
|
+
it("3 scope creep: an unauthorized billing change is caught by the review's preserve check and reverted before it can reach staging", async () => {
|
|
208
208
|
const o = await runCase({ contract: FULL, impl: (t) => { fix(t, ["scrape", "search", "export"]); t.write({ "src/billing.js": "export function price(units) { return Math.round(units) * 0.01; }\n" }); },
|
|
209
209
|
resume: (t) => t.restore("src/billing.js") });
|
|
210
|
-
|
|
210
|
+
// unclog: file scope alone is advisory (no precheck stop); the violated preserve row (P1) blocks and the resume reverts it
|
|
211
|
+
merged(o); assert.equal(o.staging.billingChanged, false); assert.deepEqual([o.counts.builder, o.counts.reviewer], [3, 2]);
|
|
212
|
+
assert.ok(o.log.some((e) => e.event === "ADVISORY" && e.rows.includes("scope_creep")), "scope creep is recorded as advisory");
|
|
211
213
|
});
|
|
212
214
|
it("4 a claimed follow-up without a tracking issue blocks merge before any review", async () => {
|
|
213
215
|
const o = await runCase({ contract: FULL, impl: (t) => fix(t, ["scrape", "search"]), claims: (k) => claimAll(k).map((r) => (r.id === "R3" ? { id: "R3", status: "deferred", note: "follow-up" } : r)) });
|
package/bin/lean/conformance.mjs
CHANGED
|
@@ -50,6 +50,7 @@ import { globToRegex } from "../../scripts/ci-local/lib.mjs";
|
|
|
50
50
|
import { contractBriefProblems } from "./pagegate.mjs"; // #5428
|
|
51
51
|
import { counterGrowth } from "./hotarea.mjs"; // #5751
|
|
52
52
|
import { designContractFailures } from "./recurrence.mjs"; // #5751
|
|
53
|
+
import { AMEND_KINDS } from "./amendment-schema.mjs"; // #5979
|
|
53
54
|
const C = OUTCOME_CODES;
|
|
54
55
|
|
|
55
56
|
/** #4789: folds what a builder retyping a quote changes: unicode punctuation, markdown links/markup, escapes, invisible chars. */
|
|
@@ -662,7 +663,6 @@ export function validateContract(c, issueText, { repro = false, pages = null, te
|
|
|
662
663
|
/** forge#4519: a shell pattern as in scripts/hotspots.sh `case` (`*` crosses `/`, `?` one character), anchored. */
|
|
663
664
|
const shellGlobRe = (g) => new RegExp(`^${String(g).replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`);
|
|
664
665
|
|
|
665
|
-
const AMEND_KINDS = ["add-deliverable", "add-requirement", ...TRACKED, "amend-requirement", "supersedes", "decision", "substitute-validate", "out-of-band"];
|
|
666
666
|
const UNRELATED_CI_KIND = "unrelated-ci-failure";
|
|
667
667
|
const GUARD_ID_RE = /^#?\d+$/;
|
|
668
668
|
const AMEND_SLIPS = { "amend-requirement": "defer", limitation: "defer", deferred: "defer", deferral: "defer", "scope-deferral": "defer", "verification-substitution": "substitute-validate", "out-of-band-verification": "out-of-band" };
|
|
@@ -709,15 +709,19 @@ function splitRequirementRefs(ref) {
|
|
|
709
709
|
function amendmentProblem(a, tag) {
|
|
710
710
|
const kind = a?.kind;
|
|
711
711
|
const need = kind === "add-deliverable" ? "needs a path" : kind === "add-requirement" ? "needs requirement {id, quote}"
|
|
712
|
-
: kind === "supersedes" ? "needs guard: \"#N\" (the guarded issue) or mechanism: \"<name>\" (#5752: retires the guards whose tests the lane deletes)" : TRACKED.includes(kind) ? "needs requirement: \"R#\"" : kind === "amend-requirement" ? "needs requirement: \"R#\" and text (the revised wording)"
|
|
712
|
+
: kind === "supersedes" ? "needs guard: \"#N\" (the guarded issue) or mechanism: \"<name>\" (#5752: retires the guards whose tests the lane deletes); a validate row id such as G2 is not a guard: use substitute-validate {validate, command, why}" : TRACKED.includes(kind) ? "needs requirement: \"R#\"" : kind === "amend-requirement" ? "needs requirement: \"R#\" and text (the revised wording)"
|
|
713
713
|
: kind === "substitute-validate" ? "needs validate: \"V#\" and command" : kind === "out-of-band" ? "needs requirement: \"R#\" and evidence (the job or workflow that measures it)"
|
|
714
714
|
: kind === "decision" ? "needs decision {choice, anchors: [paths or globs], symbols?, supersedes?: decision id}" : null;
|
|
715
715
|
const why = need ? `amendment kind '${kind}' ${need}` : `unknown kind '${kind ?? ""}'; valid kinds are ${AMEND_KINDS.join(", ")}`;
|
|
716
716
|
return `unknown or incomplete amendment: ${why}: ${tag}`;
|
|
717
717
|
}
|
|
718
718
|
|
|
719
|
+
/** #5979: a supersedes whose guard is a frozen validate-row id (G2, V1), not a #N guard issue. */
|
|
720
|
+
const isValidateRowGuard = (a, ids) => !blank(a.guard) && !GUARD_ID_RE.test(String(a.guard).trim()) && (ids ?? []).includes(String(a.guard).trim());
|
|
721
|
+
const validateRowProblem = (id, tag) => `supersedes guard '${String(id).trim()}' is a validate row of the contract, not a guard issue; use {"kind":"substitute-validate","validate":"${String(id).trim()}","command":"<runnable equivalent>","why":"..."}: ${tag}`;
|
|
722
|
+
|
|
719
723
|
/** #5089: shape-only check of the builder's amendments (unknown kind, missing path or requirement), run before the gate so one in-lane correction can fix them. Returns the rejection strings; [] when valid. */
|
|
720
|
-
export function amendmentKindProblems(amendments) {
|
|
724
|
+
export function amendmentKindProblems(amendments, validateIds = []) {
|
|
721
725
|
const out = [];
|
|
722
726
|
for (const raw of Array.isArray(amendments) ? amendments : []) {
|
|
723
727
|
const a = normalizeAmendment(raw);
|
|
@@ -726,7 +730,9 @@ export function amendmentKindProblems(amendments) {
|
|
|
726
730
|
const known = AMEND_KINDS.includes(a?.kind);
|
|
727
731
|
const missing = a?.kind === "add-deliverable" ? blank(a.path)
|
|
728
732
|
: TRACKED.includes(a?.kind) || a?.kind === "amend-requirement" ? blank(a.requirement) : false;
|
|
733
|
+
const validateRow = known && a.kind === "supersedes" && isValidateRowGuard(a, validateIds);
|
|
729
734
|
if (!known || missing) out.push(amendmentProblem(a, tag));
|
|
735
|
+
else if (validateRow) out.push(validateRowProblem(a.guard, tag));
|
|
730
736
|
}
|
|
731
737
|
return out;
|
|
732
738
|
}
|
|
@@ -822,6 +828,8 @@ export function applyAmendments(frozen, amendments, issueText = null, { generate
|
|
|
822
828
|
c.mechanisms = [...(c.mechanisms ?? []).filter((m) => m.mechanism !== mechanism), { mechanism, why: String(a.why).trim() }];
|
|
823
829
|
applied.push({ kind: a.kind, target: `mechanism ${mechanism}`, why: String(a.why).trim() });
|
|
824
830
|
continue;
|
|
831
|
+
} else if (a.kind === "supersedes" && isValidateRowGuard(a, [...(c.validate ?? []), ...(c.regression ?? [])].map((v) => v?.id))) {
|
|
832
|
+
problems.push(validateRowProblem(a.guard, tag)); continue;
|
|
825
833
|
} else if (a.kind === "supersedes" && GUARD_ID_RE.test(String(a.guard ?? "").trim())) {
|
|
826
834
|
// #4693: retires one guard's guard_broken for this lane; the reviewer judges it, the engine tells the guarded issue after merge
|
|
827
835
|
const guard = `#${String(a.guard).trim().replace(/^#/, "")}`;
|
|
@@ -2027,6 +2035,30 @@ export function normalizeKindModes(raw) {
|
|
|
2027
2035
|
* @param {{code?: string}[]} failures
|
|
2028
2036
|
* @param {{shadow?: boolean, kinds?: Record<string,string>|null, allow?: string[]}} [o]
|
|
2029
2037
|
*/
|
|
2038
|
+
/**
|
|
2039
|
+
* Advisory gates (2026-11-26 unclog): rules about the shape of the work (file scope, registries, docs placement,
|
|
2040
|
+
* recurrence design, amendment syntax, growth counters) are reported, never blocking. Measured on 102 open FD/AlterLab
|
|
2041
|
+
* issues: these rows caused ~30% of needs-human parks, repeated identically across reruns, and forced every lane to edit
|
|
2042
|
+
* the same shared files (45 of 67 conflicted base-syncs). A lane still blocks on what shows the change is wrong: failing
|
|
2043
|
+
* validate/CI/guard/repro runs, regressions and unimplemented requirements.
|
|
2044
|
+
*/
|
|
2045
|
+
export const ADVISORY_CODES = Object.freeze([OUTCOME_CODES.CONFORMANCE_SCOPE_CREEP, OUTCOME_CODES.RECURRENCE_DESIGN_MISSING, OUTCOME_CODES.MAINTENANCE_HOTSPOT_GROWTH, OUTCOME_CODES.MAINTENANCE_COUNTER_GROWTH]);
|
|
2046
|
+
export const ADVISORY_KINDS = Object.freeze([
|
|
2047
|
+
"scope_creep", "check_unknown", "design_missing", "design_missing_repeated", "docs_missing", "docs_link_broken",
|
|
2048
|
+
"ci_budget_unannotated", "hotspot_growth", "counter_growth",
|
|
2049
|
+
"amendment_invalid",
|
|
2050
|
+
"page_metadata_missing", "page_sitemap_missing", "page_canonical_missing", "page_structured_data_missing",
|
|
2051
|
+
]);
|
|
2052
|
+
/**
|
|
2053
|
+
* Split failures into {block, advisory}; advisory rows are reported on the issue and never park a lane. `enforce`: codes
|
|
2054
|
+
* a repo explicitly set to "enforce" (forge.yaml engine.conformance_kinds), which stay blocking.
|
|
2055
|
+
*/
|
|
2056
|
+
export function splitAdvisory(failures, { enforce = [] } = {}) {
|
|
2057
|
+
const block = [], advisory = [];
|
|
2058
|
+
for (const f of failures ?? []) (!enforce.includes(f?.code) && (ADVISORY_KINDS.includes(f?.kind) || ADVISORY_CODES.includes(f?.code)) ? advisory : block).push(f);
|
|
2059
|
+
return { block, advisory };
|
|
2060
|
+
}
|
|
2061
|
+
|
|
2030
2062
|
export function blockingFailures(failures, { shadow = false, kinds = null, allow = [] } = {}) {
|
|
2031
2063
|
const block = [], record = [];
|
|
2032
2064
|
for (const f of failures ?? []) {
|
|
@@ -1719,6 +1719,27 @@ describe("#5087 a plan decision may not weaken an e2e/integration criterion to m
|
|
|
1719
1719
|
});
|
|
1720
1720
|
});
|
|
1721
1721
|
|
|
1722
|
+
describe("supersedes naming a validate row (#5979)", () => {
|
|
1723
|
+
const frozen = { requirements: [], deliverables: [], validate: [{ id: "V1", command: "true" }, { id: "G2", command: "node --test a.test.mjs" }] };
|
|
1724
|
+
it("rejects guard G2 with a substitute-validate hint and records no supersedes", () => {
|
|
1725
|
+
const r = applyAmendments(frozen, [{ kind: "supersedes", guard: "G2", why: "w" }]);
|
|
1726
|
+
assert.equal(r.problems.length, 1);
|
|
1727
|
+
assert.match(r.problems[0], /substitute-validate/);
|
|
1728
|
+
assert.deepEqual(r.contract.supersedes ?? [], []);
|
|
1729
|
+
});
|
|
1730
|
+
it("amendmentKindProblems reports it only when given the validate ids", () => {
|
|
1731
|
+
const a = [{ kind: "supersedes", guard: "G2", why: "w" }];
|
|
1732
|
+
assert.match(amendmentKindProblems(a, ["G2"])[0], /substitute-validate/);
|
|
1733
|
+
assert.deepEqual(amendmentKindProblems(a), []);
|
|
1734
|
+
});
|
|
1735
|
+
it("a #N guard and a mechanism still apply", () => {
|
|
1736
|
+
const r = applyAmendments(frozen, [{ kind: "supersedes", guard: "#123", why: "w" }, { kind: "supersedes", mechanism: "m", why: "w" }]);
|
|
1737
|
+
assert.deepEqual(r.problems, []);
|
|
1738
|
+
assert.equal(r.contract.supersedes[0].guard, "#123");
|
|
1739
|
+
assert.equal(r.contract.mechanisms[0].mechanism, "m");
|
|
1740
|
+
});
|
|
1741
|
+
});
|
|
1742
|
+
|
|
1722
1743
|
describe("amendmentKindProblems (#5089)", () => {
|
|
1723
1744
|
it("flags the invented deliverable_change kind and names the valid kinds", () => {
|
|
1724
1745
|
const p = amendmentKindProblems([{ kind: "deliverable_change", requirement: "R1", why: "no Linux build" }]);
|
|
@@ -2432,3 +2453,34 @@ describe("#5754 precheck fails fast on a deliver row the placement cannot produc
|
|
|
2432
2453
|
assert.equal(run("zero 429 lines against the live stack").failures.some((x) => x.kind === "e2e_placement"), false);
|
|
2433
2454
|
});
|
|
2434
2455
|
});
|
|
2456
|
+
|
|
2457
|
+
import { AMENDMENT_EXAMPLES, AMEND_KINDS as SCHEMA_KINDS } from "./amendment-schema.mjs";
|
|
2458
|
+
import { builderImplementPrompt, amendmentCorrectionPrompt } from "./prompts.mjs";
|
|
2459
|
+
|
|
2460
|
+
describe("builder prompt amendments agree with the validator (#5979)", () => {
|
|
2461
|
+
const frozen = {
|
|
2462
|
+
requirements: [{ id: "R1", quote: "q", disposition: "deliver" }],
|
|
2463
|
+
deliverables: [{ id: "D1", path: "a.mjs", change: "c", requirements: ["R1"] }],
|
|
2464
|
+
validate: [{ id: "V1", command: "true" }, { id: "G2", command: "node --test a.test.mjs" }],
|
|
2465
|
+
};
|
|
2466
|
+
it("every documented example passes the shape check and applies without problems", () => {
|
|
2467
|
+
assert.equal(AMENDMENT_EXAMPLES.length, SCHEMA_KINDS.length);
|
|
2468
|
+
for (const ex of AMENDMENT_EXAMPLES) {
|
|
2469
|
+
assert.deepEqual(amendmentKindProblems([ex], ["V1", "G2"]), [], ex.kind);
|
|
2470
|
+
const r = applyAmendments(frozen, [ex]);
|
|
2471
|
+
assert.deepEqual(r.problems, [], `${ex.kind}: ${r.problems}`);
|
|
2472
|
+
}
|
|
2473
|
+
});
|
|
2474
|
+
it("the builder prompt names every kind and the substitute-validate path", () => {
|
|
2475
|
+
const p = builderImplementPrompt();
|
|
2476
|
+
for (const k of SCHEMA_KINDS) assert.ok(p.includes(`"${k.replace("defer|post-deploy", "defer")}`) || p.includes(k), k);
|
|
2477
|
+
assert.match(p, /"kind":"substitute-validate","validate":"G2"/);
|
|
2478
|
+
assert.match(p, /never a supersedes guard/);
|
|
2479
|
+
assert.match(amendmentCorrectionPrompt(["x"]), /substitute-validate/);
|
|
2480
|
+
});
|
|
2481
|
+
it("substitute-validate for G2 validates; supersedes G2 is still rejected", () => {
|
|
2482
|
+
const ok = applyAmendments(frozen, [{ kind: "substitute-validate", validate: "G2", command: "node --test a.test.mjs", why: "w" }]);
|
|
2483
|
+
assert.deepEqual(ok.problems, []);
|
|
2484
|
+
assert.match(applyAmendments(frozen, [{ kind: "supersedes", guard: "G2", why: "w" }]).problems[0], /substitute-validate/);
|
|
2485
|
+
});
|
|
2486
|
+
});
|
package/bin/lean/depcache.mjs
CHANGED
|
@@ -26,6 +26,15 @@ import { join, dirname, basename, relative, resolve, isAbsolute } from "node:pat
|
|
|
26
26
|
import { safeSegment } from "./ledger.mjs";
|
|
27
27
|
|
|
28
28
|
export const depcacheRoot = (env = process.env) => String(env.FORGE_DEPCACHE_ROOT ?? "").trim() || join(homedir(), ".forge", "depcache");
|
|
29
|
+
/**
|
|
30
|
+
* #5901: the per-repo directory under the cache root. A pool lane's checkout is `/cache/work/<sandbox-id>`, so a key made
|
|
31
|
+
* from the checkout path is new for every lane and every lane installs its own copy. The repo slug (`owner/repo`) is the
|
|
32
|
+
* same for all of them; `fallback` (the path-based key) is used only when no repo is known.
|
|
33
|
+
*/
|
|
34
|
+
export const depcacheNamespace = ({ repo, fallback } = {}) => {
|
|
35
|
+
const slug = String(repo ?? "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "_").replace(/^[._]+|[._]+$/g, "");
|
|
36
|
+
return slug || fallback;
|
|
37
|
+
};
|
|
29
38
|
export const DEPCACHE_INSTALL_TIMEOUT_MS = 15 * 60000;
|
|
30
39
|
export const DEPCACHE_MAX_AGE_MS = 7 * 24 * 3600 * 1000;
|
|
31
40
|
const STORES = "stores";
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
/**
|
|
4
|
+
* Batch efficiency ledger (#5987): a pure fold of a batch's `log.jsonl` rows, its state and the schedd's pool samples into a
|
|
5
|
+
* versioned `efficiency.json` (schema in devdocs/modules/lean.md). The failure/stall gates (batch-health.mjs) say a batch is broken;
|
|
6
|
+
* this says it is slow: achieved vs ceiling concurrency, idle slot-minutes by cause, attempts per merge, engine comments per
|
|
7
|
+
* issue, repeated failure signatures, operator interventions, phase p50/p90 vs a baseline, merged/hour, wasted lane-hours, $ per merge.
|
|
8
|
+
*
|
|
9
|
+
* Row fields read are the ones the orchestrator's `update(row)` writes to log.jsonl (all optional): `at`, `issue`, `outcome` (a terminal
|
|
10
|
+
* lane row; `merged` is a good end; `added`, `breaker`, `deferred` are engine/operator notes), `code`, `detail`, `minutes`, `cost_usd`,
|
|
11
|
+
* `phases:{id:{ms}}`. "Engine comments per issue" = the status updates (rows with a `detail`) the engine emitted for the issue.
|
|
12
|
+
* Operator interventions = `--add` rows, `run.interrupted` rows (schedd restart), FORGE:DECISION text in a `detail`, plus `operator`
|
|
13
|
+
* events the caller reads from the batch files (`requeue`, `hold-info`, `parallel`, see `operatorEvents`). Samples `{t, running, ceiling, ready, cause?}` are pushed by the daemon each pass and persisted in the file.
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { writeAtomic } from "./batch.mjs";
|
|
18
|
+
|
|
19
|
+
export const EFFICIENCY_FILE = "efficiency.json";
|
|
20
|
+
export const EFFICIENCY_VERSION = 1;
|
|
21
|
+
export const IDLE_CAUSES = ["capacity", "lease-held", "base.red", "hold", "breaker", "auth-pause", "no-ready"];
|
|
22
|
+
const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
|
|
23
|
+
/** Rows that are progress notes, not the end of a run; never counted as a failed attempt. */
|
|
24
|
+
const NOTE_OUTCOME = new Set(["recovering", "added", "breaker", "planned", "plan-failed", "pool-offline", "host-overloaded", "sched", "integration", "drift", "budget"]);
|
|
25
|
+
const OPERATOR_ROW = (r) => r.outcome === "added" || r.code === "run.interrupted" || /FORGE:DECISION/.test(String(r.detail ?? ""));
|
|
26
|
+
const num = (v) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : null);
|
|
27
|
+
const round = (v, d = 2) => (v === null || !Number.isFinite(v) ? null : Math.round(v * 10 ** d) / 10 ** d);
|
|
28
|
+
const atMs = (r) => { const t = Date.parse(r?.at ?? ""); return Number.isFinite(t) ? t : null; };
|
|
29
|
+
|
|
30
|
+
export function percentile(sorted, p) {
|
|
31
|
+
if (!sorted.length) return null;
|
|
32
|
+
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Phase durations (ms) by phase id over `rows`. */
|
|
36
|
+
export function phaseSpans(rows) {
|
|
37
|
+
const by = {};
|
|
38
|
+
for (const r of rows) for (const [id, v] of Object.entries(r?.phases ?? {})) { const ms = num(v?.ms); if (ms !== null && ms >= 0) (by[id] ??= []).push(ms); }
|
|
39
|
+
const out = {};
|
|
40
|
+
for (const [id, xs] of Object.entries(by)) { xs.sort((a, b) => a - b); out[id] = { n: xs.length, p50: percentile(xs, 0.5), p90: percentile(xs, 0.9) }; }
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const runMinutes = (r) => num(r.minutes) ?? (Object.entries(r.phases ?? {}).reduce((s, [id, v]) => (id === "queue_wait" ? s : s + (num(v?.ms) ?? 0)), 0) / MIN);
|
|
45
|
+
|
|
46
|
+
/** Time-weighted `{achieved, ceiling, ratio}` over the samples since `since`; each sample holds until the next one (or `now`). */
|
|
47
|
+
export function concurrencyOver(samples, since, now) {
|
|
48
|
+
let dt = 0, run = 0, cap = 0;
|
|
49
|
+
samples.forEach((s, i) => {
|
|
50
|
+
const from = Math.max(s.t, since), to = Math.min(samples[i + 1]?.t ?? now, now);
|
|
51
|
+
if (to <= from) return;
|
|
52
|
+
dt += to - from; run += (num(s.running) ?? 0) * (to - from); cap += (num(s.ceiling) ?? 0) * (to - from);
|
|
53
|
+
});
|
|
54
|
+
return dt ? { achieved: round(run / dt), ceiling: round(cap / dt), ratio: cap ? round(run / cap, 3) : null } : { achieved: null, ceiling: null, ratio: null };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Compute the ledger. `prev`: the prior efficiency.json (carries samples and SLO filing state), `sample`: this pass's pool sample,
|
|
59
|
+
* `baseline`: `{phase: {p90}}` over the previous 14 days (default: this log's rows from the 14 days before the last 24 h), `concurrencyMin`: threshold used
|
|
60
|
+
* for `lowSinceMin`. Pure; never throws on malformed rows.
|
|
61
|
+
*/
|
|
62
|
+
export function computeEfficiency({ rows = [], state = null, prev = null, sample = null, now = Date.now(), batchId = null, repo = null, operator = [], baseline = null, concurrencyMin = 0.6, windowMin = 15 } = {}) {
|
|
63
|
+
const list = (Array.isArray(rows) ? rows : []).filter((r) => r && typeof r === "object");
|
|
64
|
+
const samples = [...(Array.isArray(prev?.samples) ? prev.samples : []), ...(sample ? [{ ...sample, t: sample.t ?? now }] : [])]
|
|
65
|
+
.filter((s) => Number.isFinite(s?.t) && s.t > now - DAY).slice(-1500);
|
|
66
|
+
const day = list.filter((r) => (atMs(r) ?? now) > now - DAY);
|
|
67
|
+
const terminal = day.filter((r) => r.outcome && r.issue != null && !NOTE_OUTCOME.has(r.outcome));
|
|
68
|
+
const merged = new Set(terminal.filter((r) => r.outcome === "merged").map((r) => r.issue));
|
|
69
|
+
for (const [n, v] of Object.entries(state?.results ?? {})) if (v?.outcome === "merged") merged.add(Number(n));
|
|
70
|
+
const mergedNow = new Set([...merged].filter((n) => terminal.some((r) => r.issue === n && r.outcome === "merged")));
|
|
71
|
+
|
|
72
|
+
// concurrency and idle slot-minutes by cause (24 h)
|
|
73
|
+
const conc = concurrencyOver(samples, now - windowMin * MIN, now);
|
|
74
|
+
const ready = num(samples.at(-1)?.ready) ?? (Array.isArray(state?.pending) ? state.pending.length : 0);
|
|
75
|
+
let lowSince = null;
|
|
76
|
+
for (let i = samples.length - 1; i >= 0; i--) { const s = samples[i]; if (!(num(s.ready) > 0) || !(num(s.ceiling) > 0) || num(s.running) / num(s.ceiling) >= concurrencyMin) break; lowSince = s.t; }
|
|
77
|
+
const idle = {}; let slot = 0;
|
|
78
|
+
samples.forEach((s, i) => {
|
|
79
|
+
const to = Math.min(samples[i + 1]?.t ?? now, now), dt = (to - s.t) / MIN;
|
|
80
|
+
if (dt <= 0) return;
|
|
81
|
+
const cap = num(s.ceiling) ?? 0, run = num(s.running) ?? 0;
|
|
82
|
+
slot += cap * dt;
|
|
83
|
+
if (cap > run) { const c = s.cause ?? (num(s.ready) > 0 ? "capacity" : "no-ready"); idle[c] = (idle[c] ?? 0) + (cap - run) * dt; }
|
|
84
|
+
});
|
|
85
|
+
const idleByCause = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, round(m, 1)]));
|
|
86
|
+
const idleShare = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, slot ? round(m / slot, 3) : 0]));
|
|
87
|
+
|
|
88
|
+
// attempts, comments, signatures, interventions
|
|
89
|
+
const attempts = terminal.filter((r) => mergedNow.has(r.issue)).length;
|
|
90
|
+
const comments = {};
|
|
91
|
+
for (const r of day) if (r.issue != null) { if (typeof r.detail === "string" && r.detail) comments[r.issue] = (comments[r.issue] ?? 0) + 1; }
|
|
92
|
+
const sigs = {};
|
|
93
|
+
for (const r of terminal) if (r.outcome !== "merged") { const sig = String(r.signature ?? `${r.outcome}:${r.code ?? r.reason ?? r.error ?? ""}`).slice(0, 160); (sigs[sig] ??= new Set()).add(r.issue); (sigs[sig].n = (sigs[sig].n ?? 0) + 1); }
|
|
94
|
+
const repeats = Object.entries(sigs).map(([signature, s]) => ({ signature, count: s.n, issues: [...s].sort((a, b) => a - b) })).sort((a, b) => b.count - a.count);
|
|
95
|
+
const opAt = (e) => (typeof e?.at === "number" ? e.at : Date.parse(e?.at ?? ""));
|
|
96
|
+
const interventions = day.filter(OPERATOR_ROW).length + (Array.isArray(operator) ? operator : []).filter((e) => opAt(e) > now - DAY && opAt(e) <= now).length;
|
|
97
|
+
const capacityRefusals = list.filter((r) => (atMs(r) ?? 0) > now - HOUR && /capacity/.test(String(r.code ?? ""))).length;
|
|
98
|
+
|
|
99
|
+
// phases vs baseline
|
|
100
|
+
const cur = phaseSpans(day);
|
|
101
|
+
const base = baseline ?? Object.fromEntries(Object.entries(phaseSpans(list.filter((r) => { const t = atMs(r) ?? now; return t <= now - DAY && t > now - 15 * DAY; }))).map(([id, v]) => [id, { p90: v.p90 }]));
|
|
102
|
+
const phases = Object.fromEntries(Object.entries(cur).map(([id, v]) => [id, { ...v, baselineP90: base[id]?.p90 ?? null, ratio: base[id]?.p90 ? round(v.p90 / base[id].p90) : null }]));
|
|
103
|
+
|
|
104
|
+
// merged/hour, wasted lane-hours, $ per merge
|
|
105
|
+
const spanH = Math.max(1, Math.min(24, (now - Math.min(now, ...day.map((r) => atMs(r) ?? now))) / HOUR));
|
|
106
|
+
let wastedLater = 0, wastedNever = 0, usd = 0;
|
|
107
|
+
for (const r of terminal) {
|
|
108
|
+
usd += num(r.cost_usd) ?? 0;
|
|
109
|
+
if (r.outcome === "merged") continue;
|
|
110
|
+
(merged.has(r.issue) ? (wastedLater += runMinutes(r)) : (wastedNever += runMinutes(r)));
|
|
111
|
+
}
|
|
112
|
+
const running = state?.running && typeof state.running === "object" ? Object.keys(state.running).length : null;
|
|
113
|
+
return {
|
|
114
|
+
v: EFFICIENCY_VERSION, at: new Date(now).toISOString(), batch: batchId, repo,
|
|
115
|
+
concurrency: { ...conc, windowMin, running, ready, lowSinceMin: lowSince === null ? 0 : round((now - lowSince) / MIN, 1), min: concurrencyMin },
|
|
116
|
+
idle: { slotMinutes: round(slot, 1), byCause: idleByCause, share: idleShare },
|
|
117
|
+
limiters: Object.entries(idleByCause).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([c]) => c),
|
|
118
|
+
attemptsPerMerged: mergedNow.size ? round(attempts / mergedNow.size) : null, merged: mergedNow.size,
|
|
119
|
+
commentsPerIssue: { max: Math.max(0, ...Object.values(comments)), issues: Object.entries(comments).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([n, c]) => ({ issue: Number(n), comments: c })) },
|
|
120
|
+
repeats: repeats.slice(0, 10), interventionsPerDay: interventions, capacityRefusalsPerHour: capacityRefusals,
|
|
121
|
+
phases, mergedPerHour: round(mergedNow.size / spanH),
|
|
122
|
+
wastedLaneHours: { laterMerged: round(wastedLater / 60), neverMerged: round(wastedNever / 60) },
|
|
123
|
+
usdPerMerge: mergedNow.size ? round(usd / mergedNow.size) : null,
|
|
124
|
+
samples, slo: prev?.slo ?? { sigs: {} }, breaches: prev?.breaches ?? [],
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Idle cause of the pool right now, from the batch's recent log rows (last 10 min); undefined when none applies (capacity/no-ready are inferred from `ready`). */
|
|
129
|
+
export function idleCause(rows, now = Date.now()) {
|
|
130
|
+
const recent = (Array.isArray(rows) ? rows : []).filter((r) => r && (atMs(r) ?? 0) > now - 10 * MIN).reverse();
|
|
131
|
+
const brk = recent.find((r) => r.outcome === "breaker");
|
|
132
|
+
if (brk && !/cleared/.test(String(brk.detail ?? ""))) return "breaker";
|
|
133
|
+
for (const r of recent) {
|
|
134
|
+
const d = String(r.detail ?? "");
|
|
135
|
+
if (/base\.red|base is red/.test(`${r.code ?? ""} ${d}`)) return "base.red";
|
|
136
|
+
if (r.outcome === "deferred" && /live lane in batch/.test(d)) return "lease-held";
|
|
137
|
+
if (/capacity/.test(String(r.code ?? ""))) return "capacity";
|
|
138
|
+
}
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Operator actions recorded in a batch dir's files: `requeue` entries, `hold-info` (non-engine owners), the `parallel` file (`--set-parallel`). `[{at, kind}]`. */
|
|
143
|
+
export function operatorEvents(dir) {
|
|
144
|
+
const out = [], j = (n) => { try { return JSON.parse(readFileSync(join(dir, n), "utf8")); } catch { return null; } };
|
|
145
|
+
for (const e of Array.isArray(j("requeue")) ? j("requeue") : []) if (typeof e?.at === "string") out.push({ at: Date.parse(e.at), kind: "requeue" });
|
|
146
|
+
for (const e of Object.values(j("hold-info") ?? {})) if (e && e.owner !== "engine" && typeof e.since === "string") out.push({ at: Date.parse(e.since), kind: "hold" });
|
|
147
|
+
try { out.push({ at: statSync(join(dir, "parallel")).mtimeMs, kind: "set" }); } catch { /* none */ }
|
|
148
|
+
return out.filter((e) => Number.isFinite(e.at));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const readEfficiency = (dir) => { try { const v = JSON.parse(readFileSync(join(dir, EFFICIENCY_FILE), "utf8")); return v && v.v === EFFICIENCY_VERSION ? v : null; } catch { return null; } };
|
|
152
|
+
export const writeEfficiency = (dir, eff) => writeAtomic(join(dir, EFFICIENCY_FILE), JSON.stringify(eff) + "\n", { private: true });
|
|
153
|
+
export const hasEfficiency = (dir) => existsSync(join(dir, EFFICIENCY_FILE));
|
|
154
|
+
|
|
155
|
+
/** The `forgedock status` line: `efficiency: 3/12 lanes (25%) - limiter a b; 2 SLO breaches -> FD#NNNN`. null with no ledger. */
|
|
156
|
+
export function efficiencyLine(eff) {
|
|
157
|
+
const c = eff?.concurrency;
|
|
158
|
+
if (!c || c.running == null && c.achieved == null) return null;
|
|
159
|
+
const run = c.running ?? Math.round(c.achieved), cap = Math.round(c.ceiling ?? 0), pct = cap ? Math.round((run / cap) * 100) : 0;
|
|
160
|
+
const n = (eff.breaches ?? []).length, issues = [...new Set((eff.breaches ?? []).map((b) => b.issue).filter(Boolean))];
|
|
161
|
+
return `efficiency: ${run}/${cap} lanes (${pct}%)${eff.limiters?.length ? ` - limiter ${eff.limiters.join(" ")}` : ""}${n ? `; ${n} SLO breach${n === 1 ? "" : "es"}${issues.length ? ` -> ${issues.map((i) => `FD#${i}`).join(" ")}` : ""}` : ""}`;
|
|
162
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
import { describe, it } from "node:test";
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { computeEfficiency, efficiencyLine, concurrencyOver, idleCause, operatorEvents } from "./efficiency.mjs";
|
|
6
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
7
|
+
import { evaluateSlo, DEFAULT_SLO } from "./slo.mjs";
|
|
8
|
+
|
|
9
|
+
const NOW = Date.parse("2026-11-24T12:00:00Z"), MIN = 60000;
|
|
10
|
+
const iso = (agoMin) => new Date(NOW - agoMin * MIN).toISOString();
|
|
11
|
+
const row = (agoMin, r) => ({ at: iso(agoMin), ...r });
|
|
12
|
+
const samples = (n, running, ceiling, ready) => Array.from({ length: n }, (_, i) => ({ t: NOW - (n - i) * MIN, running, ceiling, ready }));
|
|
13
|
+
|
|
14
|
+
// 11-20..11-24 batches: 3 of 12 lanes busy, one failure signature retried, retries before the merges, operator churn.
|
|
15
|
+
export const slowRows = () => [
|
|
16
|
+
...[1, 2, 3, 4].map((i) => row(300 - i, { issue: 7, outcome: "engine-error", code: "sandbox.capacity", minutes: 30, phases: { setup: { ms: 600000 } } })),
|
|
17
|
+
row(200, { issue: 7, outcome: "merged", minutes: 20, cost_usd: 4 }),
|
|
18
|
+
row(190, { issue: 8, outcome: "ci-failed", minutes: 10 }), row(180, { issue: 8, outcome: "merged", minutes: 10, cost_usd: 2 }),
|
|
19
|
+
row(110, { issue: null, outcome: "added", detail: "9" }), row(105, { issue: 9, outcome: "deferred", code: "run.interrupted", detail: "interrupted: upgrade; requeued" }),
|
|
20
|
+
...Array.from({ length: 22 }, (_, i) => row(90 - i, { issue: 9, outcome: "recovering", detail: `recovering (ci), attempt ${i}/30` })),
|
|
21
|
+
];
|
|
22
|
+
// operator actions the daemon reads from the batch files (requeue entries, hold-info, parallel file)
|
|
23
|
+
export const slowOperator = () => Array.from({ length: 5 }, (_, i) => ({ at: NOW - (100 - i) * MIN, kind: i % 2 ? "requeue" : "hold" }));
|
|
24
|
+
export const healthyRows = () => [row(60, { issue: 1, outcome: "merged", minutes: 20, cost_usd: 2 }), row(30, { issue: 2, outcome: "merged", minutes: 20, cost_usd: 2 })];
|
|
25
|
+
|
|
26
|
+
describe("#5987 efficiency ledger", () => {
|
|
27
|
+
it("time-weights concurrency over the window", () => {
|
|
28
|
+
const s = [{ t: NOW - 10 * MIN, running: 0, ceiling: 4 }, { t: NOW - 5 * MIN, running: 4, ceiling: 4 }];
|
|
29
|
+
assert.equal(concurrencyOver(s, NOW - 15 * MIN, NOW).ratio, 0.5);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it("slow batch: low concurrency, repeats, attempts, comments and interventions all breach", () => {
|
|
33
|
+
const eff = computeEfficiency({ rows: slowRows(), operator: slowOperator(), prev: { samples: samples(40, 3, 12, 5) }, now: NOW, batchId: "b1", repo: "o/r" });
|
|
34
|
+
assert.equal(eff.v, 1);
|
|
35
|
+
assert.equal(eff.concurrency.ratio, 0.25);
|
|
36
|
+
assert.ok(eff.concurrency.lowSinceMin >= 30);
|
|
37
|
+
assert.equal(eff.attemptsPerMerged, 3.5);
|
|
38
|
+
assert.equal(eff.interventionsPerDay, 7);
|
|
39
|
+
assert.equal(eff.repeats[0].count, 4);
|
|
40
|
+
assert.ok(eff.wastedLaneHours.laterMerged > 2);
|
|
41
|
+
assert.equal(eff.usdPerMerge, 3);
|
|
42
|
+
assert.equal(eff.limiters[0], "capacity");
|
|
43
|
+
const codes = evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }).map((b) => b.code);
|
|
44
|
+
for (const c of ["concurrency", "repeat", "attempts", "interventions", "comments"]) assert.ok(codes.includes(c), `${c} in ${codes}`);
|
|
45
|
+
assert.match(efficiencyLine({ ...eff, concurrency: { ...eff.concurrency, running: 3 }, breaches: [{ issue: 12 }] }), /^efficiency: 3\/12 lanes \(25%\) - limiter capacity.*; 1 SLO breach -> FD#12$/);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("healthy batch: no breaches", () => {
|
|
49
|
+
const eff = computeEfficiency({ rows: healthyRows(), prev: { samples: samples(40, 11, 12, 5) }, now: NOW, batchId: "b2", repo: "o/r" });
|
|
50
|
+
assert.deepEqual(evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }), []);
|
|
51
|
+
assert.equal(eff.attemptsPerMerged, 1);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("malformed rows and no samples never throw", () => {
|
|
55
|
+
const eff = computeEfficiency({ rows: [null, "x", { at: "bad" }, { issue: 1, outcome: "merged", phases: { a: { ms: "q" } } }], now: NOW });
|
|
56
|
+
assert.equal(eff.concurrency.ratio, null);
|
|
57
|
+
assert.equal(efficiencyLine(eff), null);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("idleCause reads breaker, lease-held, capacity and base.red from real rows; cleared breaker and old rows give none", () => {
|
|
61
|
+
const r = (o, a = 1) => [row(a, o)];
|
|
62
|
+
assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "tripped" }), NOW), "breaker");
|
|
63
|
+
assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "circuit breaker cleared" }), NOW), undefined);
|
|
64
|
+
assert.equal(idleCause(r({ issue: 3, outcome: "deferred", detail: "#3 has a live lane in batch b2; retried in 30s" }), NOW), "lease-held");
|
|
65
|
+
assert.equal(idleCause(r({ issue: 3, outcome: "deferred", code: "sandbox.capacity" }), NOW), "capacity");
|
|
66
|
+
assert.equal(idleCause(r({ issue: 3, outcome: "needs-human", code: "base.red" }), NOW), "base.red");
|
|
67
|
+
assert.equal(idleCause(r({ issue: null, outcome: "breaker" }, 60), NOW), undefined);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("operatorEvents reads requeue, hold-info and parallel files", async () => {
|
|
71
|
+
const { writeFileSync } = await import("node:fs"), { join } = await import("node:path");
|
|
72
|
+
const d = tmpDir("opev-");
|
|
73
|
+
writeFileSync(join(d, "requeue"), JSON.stringify([{ issue: 4, at: iso(5) }, { issue: "x" }]));
|
|
74
|
+
writeFileSync(join(d, "hold-info"), JSON.stringify({ 5: { owner: "operator", since: iso(4) }, 6: { owner: "engine", since: iso(3) } }));
|
|
75
|
+
writeFileSync(join(d, "parallel"), "4\n");
|
|
76
|
+
assert.deepEqual(operatorEvents(d).map((e) => e.kind).sort(), ["hold", "requeue", "set"]);
|
|
77
|
+
assert.deepEqual(operatorEvents(join(d, "none")), []);
|
|
78
|
+
});
|
|
79
|
+
});
|