forgedock 1.60.0 → 1.61.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 +44 -1
- package/bin/engine/runlog.mjs +52 -0
- package/bin/engine-cli.mjs +9 -4
- package/bin/env/bench.mjs +38 -0
- package/bin/env/cli.mjs +134 -0
- package/bin/env/env.mjs +339 -0
- package/bin/forgedock.mjs +32 -3
- package/bin/help-text.mjs +2 -0
- package/bin/lean/ci-budget.mjs +3 -1
- package/bin/lean/ci-classify.mjs +74 -0
- package/bin/lean/ci-classify.test.mjs +147 -0
- package/bin/lean/ci-emit.mjs +175 -0
- package/bin/lean/ci-emit.test.mjs +177 -0
- package/bin/lean/ci-preflight.mjs +183 -0
- package/bin/lean/ci-preflight.test.mjs +122 -0
- package/bin/lean/ci-runner-health.mjs +213 -0
- package/bin/lean/ci-runner-health.test.mjs +113 -0
- package/bin/lean/ci-watch.mjs +79 -0
- package/bin/lean/ci-watch.test.mjs +80 -0
- package/bin/lean/conformance.mjs +7 -1
- package/bin/lean/conformance.test.mjs +7 -1
- package/bin/lean/depcache.mjs +38 -8
- package/bin/lean/deploy-stages.mjs +514 -0
- package/bin/lean/deploy-stages.test.mjs +580 -0
- package/bin/lean/effects.mjs +50 -0
- package/bin/lean/execution.mjs +8 -1
- package/bin/lean/lean.mjs +61 -12
- package/bin/lean/lean.test.mjs +87 -0
- package/bin/lean/preflight.mjs +62 -1
- package/bin/lean/preflight.test.mjs +30 -1
- package/bin/lean/release-deploy.mjs +12 -6
- package/bin/lean/release-flakes.mjs +16 -0
- package/bin/lean/release-flakes.test.mjs +15 -0
- package/bin/lean/release-gates.mjs +24 -1
- package/bin/lean/release-ledger.mjs +21 -0
- package/bin/lean/release-minutes-timing.test.mjs +57 -0
- package/bin/lean/release-minutes.mjs +98 -0
- package/bin/lean/release-promote.mjs +444 -0
- package/bin/lean/release-promote.test.mjs +470 -0
- package/bin/lean/release-rollback.mjs +14 -6
- package/bin/lean/release.mjs +31 -2
- package/bin/lean/sandbox-remote.mjs +11 -3
- package/bin/lean/testengine-recall.mjs +82 -0
- package/bin/lean/testengine-recall.test.mjs +103 -0
- package/bin/lean/testengine-shard.mjs +150 -0
- package/bin/lean/testengine-shard.test.mjs +111 -0
- package/bin/lean/testengine.mjs +486 -0
- package/bin/lean/testengine.test.mjs +303 -0
- package/bin/lean/validate-catalog.mjs +16 -0
- package/bin/lean/validate-catalog.test.mjs +14 -1
- package/bin/lean/verify-settle.test.mjs +156 -0
- package/bin/lean/verify.mjs +98 -3
- package/bin/pool/agent.mjs +65 -6
- package/bin/pool/ci-events.mjs +183 -0
- package/bin/pool/ci-events.test.mjs +143 -0
- package/bin/pool/docker.mjs +7 -0
- package/bin/pool/lane-tools.mjs +32 -0
- package/bin/pool/router.mjs +21 -1
- package/bin/pool/warm.mjs +14 -3
- package/bin/stats/ci-awareness.mjs +66 -0
- package/bin/stats/index.mjs +44 -3
- package/bin/stats/release-ledger.test.mjs +226 -0
- package/bin/stats/release.mjs +365 -1
- package/bin/stats/stats.test.mjs +36 -0
- package/docs/CI.md +31 -0
- package/docs/CONFIG.md +235 -2
- package/docs/ENV-LIBRARY.md +172 -0
- package/docs/STATS.md +43 -0
- package/docs/ci-events.md +88 -0
- package/docs/test-engine.md +98 -0
- package/package.json +1 -1
- package/pool/README.md +1 -0
- package/pool/image/entrypoint.sh +15 -3
- package/pool/services/docker-compose.yml +53 -0
- package/pool/services/git-mirror.sh +22 -0
- package/scripts/acceptance-red-green.sh +5 -2
- package/scripts/acceptance-red-green.test.sh +11 -0
- package/templates/github-actions/forge-env/action.yml +65 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #5718: the release ledger on a recorded-shape fixture (raw REST payloads of a neutral repo, acme/widgets). The fake `gh`
|
|
4
|
+
// serves raw pages and applies the caller's own --jq program with the jq binary, so the projections are exercised too.
|
|
5
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
6
|
+
import { describe, it } from "node:test";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { parseArgs, runStats } from "./index.mjs";
|
|
13
|
+
import { LEDGER_METRICS, baselineOf, compareBaseline, computeReleaseLedger, deployJobOf, gatherReleaseLedger, ledgerSince, ledgerTable, listReleasePrs, parseLedgerConfig, planLedger, renderBaselineCompare, renderReleaseLedger, runReleaseLedger } from "./release.mjs";
|
|
14
|
+
import { listRuns } from "../lean/release-minutes.mjs";
|
|
15
|
+
import { releaseRecords } from "../lean/release-ledger.mjs";
|
|
16
|
+
|
|
17
|
+
const FX = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "fixtures", "release-ledger", "acme-widgets.json"), "utf8"));
|
|
18
|
+
const HAS_JQ = spawnSync("jq", ["--version"]).status === 0;
|
|
19
|
+
const SINCE = Date.parse("2026-03-01T00:00:00Z"), UNTIL = Date.parse("2026-03-03T00:00:00Z"), REPO = "acme/widgets";
|
|
20
|
+
|
|
21
|
+
/** A `gh` that answers the REST paths the ledger reads from the fixture, page by page (`pageSize`), through real jq. */
|
|
22
|
+
function fakeGh(fx = FX, { pageSize = 100 } = {}) {
|
|
23
|
+
const calls = [];
|
|
24
|
+
const gh = async (args) => {
|
|
25
|
+
calls.push(args.join(" "));
|
|
26
|
+
const path = args.find((a) => a.startsWith("repos/")), jq = args[args.indexOf("--jq") + 1];
|
|
27
|
+
const q = new URLSearchParams(path.split("?")[1] ?? "");
|
|
28
|
+
const chunk = (rows) => { const out = []; for (let i = 0; i < Math.max(rows.length, 1); i += pageSize) out.push(rows.slice(i, i + pageSize)); return out; };
|
|
29
|
+
let pages;
|
|
30
|
+
if (/^repos\/[^/]+\/[^/?]+$/.test(path)) pages = [fx.repo];
|
|
31
|
+
else if (/\/pulls\?/.test(path)) { const rows = fx.pulls.filter((p) => p.base.ref === q.get("base")); const n = Number(q.get("per_page")), pg = Number(q.get("page") ?? 1); pages = [rows.slice((pg - 1) * n, pg * n)]; }
|
|
32
|
+
else if (/\/actions\/runs\/(\d+)\/jobs/.test(path)) { const rows = fx.jobs[/runs\/(\d+)\/jobs/.exec(path)[1]] ?? []; pages = chunk(rows).map((jobs) => ({ total_count: rows.length, jobs })); }
|
|
33
|
+
else if (/\/actions\/runs\?/.test(path)) {
|
|
34
|
+
const [a, b] = q.get("created").split("..").map((x) => Date.parse(x));
|
|
35
|
+
const rows = fx.runs.filter((r) => Date.parse(r.created_at) >= a && Date.parse(r.created_at) <= b && (!q.get("branch") || r.head_branch === q.get("branch")) && (!q.get("event") || r.event === q.get("event")))
|
|
36
|
+
.sort((x, y) => Date.parse(y.created_at) - Date.parse(x.created_at)).slice(0, 1000);
|
|
37
|
+
pages = chunk(rows).map((workflow_runs) => ({ total_count: rows.length, workflow_runs }));
|
|
38
|
+
} else throw new Error(`unexpected gh call: ${args.join(" ")}`);
|
|
39
|
+
return pages.map((p) => execFileSync("jq", ["-r", jq], { input: JSON.stringify(p), encoding: "utf8" })).join("");
|
|
40
|
+
};
|
|
41
|
+
return { gh, calls };
|
|
42
|
+
}
|
|
43
|
+
const CFG = { releaseHead: "staging" };
|
|
44
|
+
const gathered = async (cfg = CFG, o = {}) => gatherReleaseLedger({ gh: fakeGh(FX, o).gh, repo: REPO, sinceMs: SINCE, untilMs: UNTIL, cfg, useCache: false });
|
|
45
|
+
|
|
46
|
+
describe("release ledger: config and arguments (#5718)", () => {
|
|
47
|
+
it("parses the forge.yaml stats.ledger_* keys; the release head defaults to branches.staging", () => {
|
|
48
|
+
assert.deepEqual(parseLedgerConfig(null, null), { releaseBase: null, releaseHead: null, ciWorkflows: [], deployWorkflow: null, deployJob: null });
|
|
49
|
+
assert.deepEqual(parseLedgerConfig({ ledger_release_base: "trunk", ledger_ci_workflows: ["CI", "images.yml"], ledger_deploy_workflow: "deploy.yml", ledger_deploy_job: "^rollout" }, { staging: "next" }),
|
|
50
|
+
{ releaseBase: "trunk", releaseHead: "next", ciWorkflows: ["CI", "images.yml"], deployWorkflow: "deploy.yml", deployJob: "^rollout" });
|
|
51
|
+
assert.equal(parseLedgerConfig({ ledger_release_head: "rc" }, { staging: "next" }).releaseHead, "rc");
|
|
52
|
+
});
|
|
53
|
+
it("--release-ledger takes --baseline save|compare; its flags need it", () => {
|
|
54
|
+
const o = parseArgs(["--release-ledger", "--baseline", "save", "--since", "21d", "--deploy-workflow", "deploy.yml", "--json"]);
|
|
55
|
+
assert.equal(o.releaseLedger, true); assert.equal(o.baseline, "save"); assert.equal(o.deployWorkflow, "deploy.yml");
|
|
56
|
+
assert.throws(() => parseArgs(["--release-ledger", "--baseline", "reset"]), /save or compare/);
|
|
57
|
+
assert.throws(() => parseArgs(["--baseline", "save"]), /need --release-ledger/);
|
|
58
|
+
assert.equal(parseArgs([]).releaseLedger, undefined);
|
|
59
|
+
});
|
|
60
|
+
it("--since is a date or a window, default 21 days", () => {
|
|
61
|
+
const now = Date.parse("2026-03-22T00:00:00Z");
|
|
62
|
+
assert.equal(ledgerSince(null, now), Date.parse("2026-03-01T00:00:00Z"));
|
|
63
|
+
assert.equal(ledgerSince("7d", now), now - 7 * 86400000); assert.equal(ledgerSince("36h", now), now - 36 * 3600000);
|
|
64
|
+
assert.equal(ledgerSince("2026-03-10", now), Date.parse("2026-03-10"));
|
|
65
|
+
assert.throws(() => ledgerSince("1.2.0", now), /date .* or a window/);
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe("release ledger: plan (#5718)", () => {
|
|
70
|
+
const runs = FX.runs.map((r) => ({ ...r, prs: r.pull_requests.map((p) => p.number) }));
|
|
71
|
+
const prs = FX.pulls.map((p) => ({ number: p.number, created_at: p.created_at, merged_at: p.merged_at, closed_at: p.closed_at, merge_commit_sha: p.merge_commit_sha, head_ref: p.head.ref, base_ref: p.base.ref }));
|
|
72
|
+
it("picks the release PRs, their CI runs and the deploy workflow with the most runs", () => {
|
|
73
|
+
const p = planLedger({ prs, runs, base: "main", cfg: CFG, untilMs: UNTIL });
|
|
74
|
+
assert.deepEqual(p.releases.map((x) => [x.pr.number, x.ci.map((r) => r.id).sort()]), [[10, [100, 101, 102, 103]], [11, [110]]]);
|
|
75
|
+
assert.equal(p.deployWorkflow, ".github/workflows/deploy.yml");
|
|
76
|
+
assert.deepEqual(p.deploy.map((r) => r.id), [200, 201, 210, 211]);
|
|
77
|
+
assert.ok(!p.need.includes(300), "another deploy-named workflow is not read");
|
|
78
|
+
});
|
|
79
|
+
it("a pinned workflow, a CI workflow filter and any head are honoured", () => {
|
|
80
|
+
assert.deepEqual(planLedger({ prs, runs, base: "main", cfg: { deployWorkflow: "docs.yml" } }).deploy.map((r) => r.id), [300]);
|
|
81
|
+
assert.deepEqual(planLedger({ prs, runs, base: "main", cfg: { ...CFG, ciWorkflows: ["Images"] } }).releases[0].ci.map((r) => r.id), [102]);
|
|
82
|
+
assert.deepEqual(planLedger({ prs, runs, base: "main", cfg: {} }).releases.map((x) => x.pr.number), [10, 11, 12]);
|
|
83
|
+
});
|
|
84
|
+
it("a repo whose CI runs only on push falls back to the head branch's push runs while the PR was open", () => {
|
|
85
|
+
const push = runs.filter((r) => r.event !== "pull_request").concat([{ ...runs[0], id: 130, event: "push", prs: [], created_at: "2026-03-01T10:05:00Z" }]);
|
|
86
|
+
assert.deepEqual(planLedger({ prs, runs: push, base: "main", cfg: CFG, untilMs: UNTIL }).releases.map((x) => x.ci.map((r) => r.id)), [[130], []]);
|
|
87
|
+
});
|
|
88
|
+
it("the deploy job is the configured one, else the longest job whose name says deploy", () => {
|
|
89
|
+
assert.equal(deployJobOf(FX.jobs[201]).name, "deploy");
|
|
90
|
+
assert.equal(deployJobOf(FX.jobs[201], { deployJob: "^pre" }).name, "pre-gate");
|
|
91
|
+
assert.equal(deployJobOf(FX.jobs[211]), null, "a skipped job never deploys");
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe("release ledger: metrics from the Actions API (#5718)", { skip: !HAS_JQ && "jq not installed" }, () => {
|
|
96
|
+
it("computes every target row from runs, jobs and steps", async () => {
|
|
97
|
+
const r = computeReleaseLedger(await gathered(), CFG), m = r.metrics;
|
|
98
|
+
assert.deepEqual(r.n, { rounds: 3, release_prs: 2, release_prs_with_ci: 2, ci_runs: 5, ci_jobs: 7, deploy_attempts: 3, deploy_live: 2, image_build_jobs: 1, failed_runs: 1, mechanical_failures: 1, live_releases: 2, clean_releases: 1 });
|
|
99
|
+
assert.equal(m.ci_round_wall_min_p50, 10); assert.equal(m.ci_round_wall_min_p90, 20); assert.equal(m.ci_round_fail_rate, 0.333);
|
|
100
|
+
assert.equal(m.pushes_per_release_pr_p50, 2); assert.equal(m.pushes_per_release_pr_max, 3);
|
|
101
|
+
// job seconds: failed lint 120, cancelled test 300, of 120+1140+300+115+570+356+580 = 3181
|
|
102
|
+
assert.equal(m.failed_minute_share, 0.038); assert.equal(m.cancelled_minute_share, 0.094);
|
|
103
|
+
assert.equal(m.deploy_live_rate, 0.667); assert.equal(m.deploy_pregate_min_p50, 15); assert.equal(m.deploy_job_min_p50, 22.5); assert.equal(m.deploy_run_min_p50, 37.5);
|
|
104
|
+
assert.equal(m.image_build_min_p50, 4);
|
|
105
|
+
assert.equal(m.mechanical_failure_surfaced_s, 1200); assert.equal(m.first_failed_step_s_p50, 130);
|
|
106
|
+
assert.equal(m.pr_to_live_h_median, 2.38); assert.equal(m.pr_to_live_h_p90, 3.75); assert.equal(m.pr_to_live_clean_h_median, 1);
|
|
107
|
+
assert.equal(m.queue_s_p90, 30); // nearest rank over 13 queue times
|
|
108
|
+
assert.deepEqual(r.setup.self_hosted, { jobs: 4, checkout_s: 100, toolchain_s: 60, deps_s: 200, total_s: 360 });
|
|
109
|
+
assert.deepEqual(r.setup.hosted, { jobs: 3, checkout_s: 5, toolchain_s: 15, deps_s: 30, total_s: 50 });
|
|
110
|
+
assert.deepEqual(r.critical_path.map((c) => [c.job, c.rounds, c.of]), [["test", 3, 3]]);
|
|
111
|
+
assert.deepEqual(r.deploy_steps, [{ step: "Roll out", min_p50: 13, n: 2 }, { step: "Smoke", min_p50: 5, n: 2 }, { step: "Tail services", min_p50: 4.5, n: 2 }]);
|
|
112
|
+
assert.deepEqual(r.releases.map((x) => [x.pr, x.hours, x.pushes, x.deploy_attempts, x.clean]), [[10, 3.75, 3, 2, false], [11, 1, 1, 1, true]]);
|
|
113
|
+
assert.match(r.notes.join("\n"), /deploy workflow detected: \.github\/workflows\/deploy\.yml/);
|
|
114
|
+
});
|
|
115
|
+
it("prints the Targets table with today vs target and a status per row", async () => {
|
|
116
|
+
const r = computeReleaseLedger(await gathered(), CFG), text = renderReleaseLedger(r);
|
|
117
|
+
const row = (k) => r.table.find((x) => x.key === k);
|
|
118
|
+
assert.equal(row("ci_round_wall_min_p50").status, "phase1-met"); assert.equal(row("pushes_per_release_pr_p50").status, "not-met");
|
|
119
|
+
assert.equal(row("pr_to_live_clean_h_median").status, "phase1-met"); assert.equal(row("failed_minute_share").status, "no-target");
|
|
120
|
+
assert.match(text, /\| CI wall time per round \(p50\) \| 10 min \| <= 10 min \| <= 4 min \| phase1-met \|/);
|
|
121
|
+
assert.match(text, /self-hosted: 100 s \+ 60 s \+ 200 s \(total 360 s, 4 job\(s\)\)/);
|
|
122
|
+
assert.match(text, /\| Roll out \| 13 min \|/);
|
|
123
|
+
assert.equal(ledgerTable({}).find((x) => x.key === "queue_s_p90").status, "n/a");
|
|
124
|
+
assert.equal(ledgerTable({ deploy_live_rate: 0.5 }, [{ key: "deploy_live_rate", label: "x", unit: "pct", higherBetter: true, phase1: 0.9, end: 0.99 }])[0].status, "not-met");
|
|
125
|
+
assert.equal(r.table.length, LEDGER_METRICS.length);
|
|
126
|
+
});
|
|
127
|
+
it("release state from the managed ledger raises the attempt count of its release", async () => {
|
|
128
|
+
const data = await gathered();
|
|
129
|
+
const r = computeReleaseLedger({ ...data, ledger: [{ pr: 11, deployAttempts: 3, live: true }] }, CFG);
|
|
130
|
+
assert.deepEqual(r.releases.map((x) => [x.pr, x.deploy_attempts, x.clean]), [[10, 2, false], [11, 3, false]]);
|
|
131
|
+
assert.equal(r.metrics.pr_to_live_clean_h_median, null);
|
|
132
|
+
});
|
|
133
|
+
it("without a deploy workflow, live is the merge time and the report says so", async () => {
|
|
134
|
+
const data = await gathered();
|
|
135
|
+
const r = computeReleaseLedger({ ...data, runs: data.runs.filter((x) => x.event === "pull_request") }, CFG);
|
|
136
|
+
assert.equal(r.deploy_workflow, null); assert.deepEqual(r.releases.map((x) => x.hours), [2, 0.5]);
|
|
137
|
+
assert.match(r.notes.join("\n"), /no deploy workflow found/);
|
|
138
|
+
assert.equal(r.metrics.deploy_live_rate, null);
|
|
139
|
+
});
|
|
140
|
+
it("paginates runs, jobs and PRs: small pages give the same report", async () => {
|
|
141
|
+
const a = computeReleaseLedger(await gathered(), CFG), b = computeReleaseLedger(await gathered(CFG, { pageSize: 2 }), CFG);
|
|
142
|
+
assert.deepEqual(b.metrics, a.metrics);
|
|
143
|
+
const many = { ...FX, pulls: Array.from({ length: 230 }, (_, i) => ({ ...FX.pulls[1], number: 1000 - i, created_at: new Date(UNTIL - i * 600000).toISOString() })) };
|
|
144
|
+
assert.equal((await listReleasePrs({ gh: fakeGh(many).gh, repo: REPO, base: "main", sinceMs: SINCE })).length, 230);
|
|
145
|
+
const f = fakeGh(many);
|
|
146
|
+
assert.equal((await listReleasePrs({ gh: f.gh, repo: REPO, base: "main", sinceMs: UNTIL - 50 * 600000 })).length, 51);
|
|
147
|
+
assert.equal(f.calls.length, 1, "stops at the page that reaches the window start");
|
|
148
|
+
});
|
|
149
|
+
it("a window at the runs API result cap is halved, so no run is dropped", async () => {
|
|
150
|
+
const f = fakeGh();
|
|
151
|
+
const runs = await listRuns({ gh: f.gh, repo: REPO, sinceMs: SINCE, untilMs: UNTIL, cap: 6 });
|
|
152
|
+
assert.equal(new Set(runs.map((r) => r.id)).size, FX.runs.length); assert.equal(runs.length, FX.runs.length);
|
|
153
|
+
assert.ok(f.calls.length > 1);
|
|
154
|
+
});
|
|
155
|
+
it("reads only scoped runs and caches the jobs of completed runs", async () => {
|
|
156
|
+
const env = { FORGE_STATS_CACHE_DIR: tmpDir("ledger-cache-") };
|
|
157
|
+
const f = fakeGh();
|
|
158
|
+
await gatherReleaseLedger({ gh: f.gh, repo: REPO, sinceMs: SINCE, untilMs: UNTIL, cfg: CFG, env });
|
|
159
|
+
assert.ok(f.calls.filter((c) => /actions\/runs\?/.test(c)).every((c) => /branch=(staging|main)&event=/.test(c)), "every runs query names a branch and an event");
|
|
160
|
+
assert.equal(f.calls.filter((c) => /\/jobs\?/.test(c)).length, 9);
|
|
161
|
+
const g = fakeGh();
|
|
162
|
+
const again = await gatherReleaseLedger({ gh: g.gh, repo: REPO, sinceMs: SINCE, untilMs: UNTIL, cfg: CFG, env });
|
|
163
|
+
assert.equal(g.calls.filter((c) => /\/jobs\?/.test(c)).length, 0, "second read: no job call");
|
|
164
|
+
assert.equal(computeReleaseLedger(again, CFG).metrics.ci_round_wall_min_p50, 10);
|
|
165
|
+
});
|
|
166
|
+
it("--baseline save then compare shows before/after per metric, measured the same way", async () => {
|
|
167
|
+
const env = { FORGE_STATS_CACHE_DIR: tmpDir("ledger-base-") }, out = [];
|
|
168
|
+
const deps = { gh: fakeGh().gh, env, now: () => UNTIL, write: (s) => out.push(s), config: CFG };
|
|
169
|
+
assert.equal(await runReleaseLedger({ repo: REPO, since: "2d", baseline: "compare" }, deps), 2, "no baseline yet");
|
|
170
|
+
assert.equal(await runReleaseLedger({ repo: REPO, since: "2d", baseline: "save" }, deps), 0);
|
|
171
|
+
const file = join(env.FORGE_STATS_CACHE_DIR, "acme_widgets", "release-ledger-baseline.json");
|
|
172
|
+
assert.ok(existsSync(file)); assert.equal(JSON.parse(readFileSync(file, "utf8")).metrics.ci_round_wall_min_p50, 10);
|
|
173
|
+
// after: the failed round is gone and the deploy pre-gate job is fast
|
|
174
|
+
const faster = structuredClone(FX);
|
|
175
|
+
faster.runs = faster.runs.filter((r) => r.id !== 100 && r.id !== 103);
|
|
176
|
+
for (const id of [201, 210]) { const [pre, dep] = faster.jobs[id]; const shift = Date.parse(dep.started_at) - Date.parse(pre.started_at) - 60000; pre.completed_at = new Date(Date.parse(pre.started_at) + 55000).toISOString(); for (const x of [dep, ...dep.steps]) for (const k of ["created_at", "started_at", "completed_at"]) if (x[k]) x[k] = new Date(Date.parse(x[k]) - shift).toISOString(); }
|
|
177
|
+
out.length = 0;
|
|
178
|
+
assert.equal(await runReleaseLedger({ repo: REPO, since: "2d", baseline: "compare", json: true, cache: false }, { ...deps, gh: fakeGh(faster).gh }), 0);
|
|
179
|
+
const cmp = Object.fromEntries(JSON.parse(out.join("")).compare.rows.map((x) => [x.key, x]));
|
|
180
|
+
assert.deepEqual([cmp.deploy_pregate_min_p50.before, cmp.deploy_pregate_min_p50.after, cmp.deploy_pregate_min_p50.verdict], [15, 1.1, "improved"]);
|
|
181
|
+
assert.equal(cmp.pushes_per_release_pr_p50.verdict, "improved"); assert.equal(cmp.ci_round_fail_rate.verdict, "improved");
|
|
182
|
+
assert.equal(cmp.deploy_job_min_p50.verdict, "flat"); assert.deepEqual([cmp.setup_hosted_s.before, cmp.setup_hosted_s.after, cmp.setup_hosted_s.verdict], [50, 16, "improved"]);
|
|
183
|
+
});
|
|
184
|
+
it("forgedock stats --release-ledger --json prints the report", async () => {
|
|
185
|
+
const out = [], w = process.stdout.write;
|
|
186
|
+
process.stdout.write = (s) => { out.push(String(s)); return true; };
|
|
187
|
+
let code;
|
|
188
|
+
try { code = await runStats(["--release-ledger", "--repo", REPO, "--since", "2026-03-01", "--no-cache", "--json"], { gh: fakeGh().gh, now: () => UNTIL, ledgerConfig: CFG }); } finally { process.stdout.write = w; }
|
|
189
|
+
assert.equal(code, 0);
|
|
190
|
+
const r = JSON.parse(out.join(""));
|
|
191
|
+
assert.equal(r.repo, REPO); assert.equal(r.base, "main"); assert.equal(r.metrics.deploy_live_rate, 0.667); assert.equal(r.window.days, 2);
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
describe("release ledger: baseline compare (pure, #5718)", () => {
|
|
196
|
+
const rep = (metrics) => ({ repo: REPO, window: { since: "2026-03-01T00:00:00.000Z", until: "2026-03-03T00:00:00.000Z" }, n: {}, metrics });
|
|
197
|
+
it("verdicts: lower is better except the live rate; flat inside 5% (2 points for a share); null when a side is missing", () => {
|
|
198
|
+
const base = baselineOf(rep({ ci_round_wall_min_p50: 28.6, deploy_live_rate: 0.37, failed_minute_share: 0.28, queue_s_p90: 1526, pushes_per_release_pr_p50: 3.5 }), 0);
|
|
199
|
+
const c = compareBaseline(base, rep({ ci_round_wall_min_p50: 9, deploy_live_rate: 0.9, failed_minute_share: 0.29, queue_s_p90: 1600, pushes_per_release_pr_p50: null }));
|
|
200
|
+
const v = Object.fromEntries(c.rows.map((x) => [x.key, x.verdict]));
|
|
201
|
+
assert.equal(v.ci_round_wall_min_p50, "improved"); assert.equal(v.deploy_live_rate, "improved"); assert.equal(v.failed_minute_share, "flat");
|
|
202
|
+
assert.equal(v.queue_s_p90, "flat"); assert.equal(v.pushes_per_release_pr_p50, null); assert.equal(v.image_build_min_p50, null);
|
|
203
|
+
assert.equal(compareBaseline(base, rep({ deploy_live_rate: 0.2, queue_s_p90: 2000 })).rows.filter((x) => x.verdict === "regressed").length, 2);
|
|
204
|
+
assert.match(renderBaselineCompare(c, rep({})), /\| CI wall time per round \(p50\) \| 28\.6 min \| 9 min \| improved \|/);
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
describe("release ledger: managed release state (#5718)", () => {
|
|
209
|
+
it("releaseRecords reads the ledger states of the window and skips unreadable ones", async () => {
|
|
210
|
+
const states = { "r20260301-100000-1": { id: "r20260301-100000-1", status: "done", startedAt: "2026-03-01T10:00:00Z", deploy: { phase: "LIVE_CHECKED", attempts: 2 }, steps: { "release-pr": { result: { pr: 10 } } } },
|
|
211
|
+
"r20260302-090000-1": { id: "r20260302-090000-1", status: "stopped", deploy: { phase: "DEPLOYING", attempts: 1 }, pr: 11 }, "r20260101-000000-1": { status: "done" } };
|
|
212
|
+
const reads = [];
|
|
213
|
+
const api = async (method, path) => {
|
|
214
|
+
reads.push(path);
|
|
215
|
+
if (/matching-refs/.test(path)) return [...Object.keys(states), "r20260302-100000-9", "_active"].map((id) => ({ ref: `refs/heads/forge-ledger/${id}` }));
|
|
216
|
+
const ref = /git\/ref\/heads\/forge-ledger\/(.+)$/.exec(path) ?? /ref=forge-ledger(?:%2F|\/)([^&]+)/.exec(path);
|
|
217
|
+
const id = ref ? decodeURIComponent(ref[1]) : null;
|
|
218
|
+
if (id && !states[id]) { const e = new Error("Not Found"); e.status = 404; throw e; }
|
|
219
|
+
if (/git\/ref\//.test(path)) return { object: { sha: `sha-${id}` } };
|
|
220
|
+
return { content: Buffer.from(JSON.stringify(states[id])).toString("base64"), encoding: "base64" };
|
|
221
|
+
};
|
|
222
|
+
const recs = await releaseRecords({ io: { api }, repo: REPO }, { sinceMs: SINCE });
|
|
223
|
+
assert.deepEqual(recs, [{ id: "r20260301-100000-1", pr: 10, startedAt: "2026-03-01T10:00:00Z", status: "done", live: true, deployAttempts: 2 }, { id: "r20260302-090000-1", pr: 11, startedAt: null, status: "stopped", live: false, deployAttempts: 1 }]);
|
|
224
|
+
assert.ok(!reads.some((p) => p.includes("r20260101")), "a release older than the window costs no read");
|
|
225
|
+
});
|
|
226
|
+
});
|
package/bin/stats/release.mjs
CHANGED
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
* forge#4628: per-release regression rule over the `aggregate()` groups. Each metric is null when its own sample is
|
|
5
5
|
* below minN; a verdict is null when either side is null. There is no "pass" value, only regressed|improved|flat|null.
|
|
6
6
|
*/
|
|
7
|
-
import {
|
|
7
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { DEFAULT_MIN_N, UNKNOWN, compareVersions, percentile } from "./aggregate.mjs";
|
|
10
|
+
import { cacheDir } from "./cache.mjs";
|
|
11
|
+
import * as M from "../lean/release-minutes.mjs";
|
|
8
12
|
|
|
9
13
|
export const METRICS_MARKER = "<!-- FORGE:METRICS v1 -->";
|
|
10
14
|
const isNum = (x) => typeof x === "number" && Number.isFinite(x);
|
|
@@ -73,3 +77,363 @@ export async function postMetrics({ gh, repo, pr, body }) {
|
|
|
73
77
|
else await gh(["api", "-X", "POST", `repos/${repo}/issues/${pr}/comments`, "-f", `body=${body}`]);
|
|
74
78
|
return mine ? "updated" : "created";
|
|
75
79
|
}
|
|
80
|
+
|
|
81
|
+
// ---- Release ledger (#5718, Forge CI W8): the plan's "Today (measured)" numbers from the Actions runs/jobs/steps API plus release state. ----
|
|
82
|
+
|
|
83
|
+
const CI_EVENTS = ["pull_request", "pull_request_target", "merge_group"];
|
|
84
|
+
const DEPLOY_EVENTS = ["push", "workflow_dispatch", "release", "workflow_run"];
|
|
85
|
+
const DEPLOY_NAME_RE = /deploy|rollout|publish|release|ship/i;
|
|
86
|
+
const t = (s) => Date.parse(s);
|
|
87
|
+
const p50 = (v) => percentile(v, 50), p90 = (v) => percentile(v, 90);
|
|
88
|
+
const lcs = (v) => String(v ?? "").toLowerCase();
|
|
89
|
+
const list = (v) => (Array.isArray(v) ? v : String(v ?? "").split(",")).map((x) => String(x).trim()).filter(Boolean);
|
|
90
|
+
const re = (s) => { try { return s ? new RegExp(s, "i") : null; } catch { return null; } };
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The plan's Targets table: today vs phase 1 vs end. `higherBetter` flips the verdict; a metric without targets is
|
|
94
|
+
* reported and compared against a baseline only. Units: s, min, h, n (a count), pct (a 0..1 share).
|
|
95
|
+
*/
|
|
96
|
+
export const LEDGER_METRICS = Object.freeze([
|
|
97
|
+
{ key: "mechanical_failure_surfaced_s", label: "Mechanical failure surfaced (run start -> run end)", unit: "s", phase1: 60, end: 30 },
|
|
98
|
+
{ key: "setup_self_hosted_s", label: "Job setup, self-hosted (checkout + toolchain + dependencies)", unit: "s", phase1: 30, end: 10 },
|
|
99
|
+
{ key: "setup_hosted_s", label: "Job setup, hosted (checkout + toolchain + dependencies)", unit: "s" },
|
|
100
|
+
{ key: "ci_round_wall_min_p50", label: "CI wall time per round (p50)", unit: "min", phase1: 10, end: 4 },
|
|
101
|
+
{ key: "pushes_per_release_pr_p50", label: "Pushes per release PR (p50)", unit: "n", phase1: 1.5, end: 1 },
|
|
102
|
+
{ key: "deploy_pregate_min_p50", label: "Deploy pre-gate (run start -> deploy job start)", unit: "min", phase1: 5, end: 1 },
|
|
103
|
+
{ key: "image_build_min_p50", label: "Image build (p50 per job)", unit: "min", phase1: 4, end: 1.5 },
|
|
104
|
+
{ key: "deploy_job_min_p50", label: "Deploy job (rollout)", unit: "min", phase1: 15, end: 5 },
|
|
105
|
+
{ key: "pr_to_live_clean_h_median", label: "Release PR opened -> live (clean, median)", unit: "h", phase1: 1, end: 0.5 },
|
|
106
|
+
{ key: "pr_to_live_h_median", label: "Release PR opened -> live (all, median)", unit: "h" },
|
|
107
|
+
{ key: "pr_to_live_h_p90", label: "Release PR opened -> live (all, p90)", unit: "h" },
|
|
108
|
+
{ key: "queue_s_p90", label: "Queue time (p90)", unit: "s", phase1: 30, end: 30 },
|
|
109
|
+
{ key: "failed_minute_share", label: "CI minutes in failed jobs", unit: "pct" },
|
|
110
|
+
{ key: "cancelled_minute_share", label: "CI minutes in cancelled jobs", unit: "pct" },
|
|
111
|
+
{ key: "ci_round_fail_rate", label: "CI rounds that fail", unit: "pct" },
|
|
112
|
+
{ key: "deploy_live_rate", label: "Deploy attempts that reached live", unit: "pct", higherBetter: true },
|
|
113
|
+
]);
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* forge.yaml `stats:` keys of the ledger (all optional) -> config. `ledger_release_base` (default: the repo's default
|
|
117
|
+
* branch), `ledger_release_head` (default: `branches.staging` when set, else any head), `ledger_ci_workflows` (names or
|
|
118
|
+
* file names; default every workflow), `ledger_deploy_workflow` (name or file; default: detected), `ledger_deploy_job`
|
|
119
|
+
* (regex on the job name; default: detected).
|
|
120
|
+
*/
|
|
121
|
+
export function parseLedgerConfig(stats, branches) {
|
|
122
|
+
const s = stats && typeof stats === "object" ? stats : {};
|
|
123
|
+
const str = (k) => String(s[k] ?? "").trim() || null;
|
|
124
|
+
return { releaseBase: str("ledger_release_base"), releaseHead: str("ledger_release_head") ?? (String(branches?.staging ?? "").trim() || null),
|
|
125
|
+
ciWorkflows: list(s.ledger_ci_workflows), deployWorkflow: str("ledger_deploy_workflow"), deployJob: str("ledger_deploy_job") };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const wfMatch = (run, name) => { const n = lcs(name), p = lcs(run.path); return lcs(run.name) === n || p === n || p.endsWith(`/${n}`); };
|
|
129
|
+
const ranRun = (r) => r.status === "completed" && !["skipped", "action_required", "stale"].includes(lcs(r.conclusion));
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Which runs belong to the ledger (pure): the CI runs of each release PR and the deploy runs. A release PR is a PR into
|
|
133
|
+
* `base` (from `cfg.releaseHead` when set) opened in the window. Its CI runs are the PR-event runs that name it (or, for
|
|
134
|
+
* runs that name no PR, its head branch while it was open); a repo whose CI only runs on push falls back to the push runs
|
|
135
|
+
* of the head branch while the PR was open. The deploy workflow is `cfg.deployWorkflow`, else the non-PR workflow on `base`
|
|
136
|
+
* whose name or file says deploy/publish/release with the most runs.
|
|
137
|
+
* @returns {{releases: {pr: object, ci: object[]}[], deploy: object[], deployWorkflow: string|null, need: number[]}}
|
|
138
|
+
*/
|
|
139
|
+
export function planLedger({ prs = [], runs = [], base, cfg = {}, untilMs = Date.now() }) {
|
|
140
|
+
const wanted = (r) => !cfg.ciWorkflows?.length || cfg.ciWorkflows.some((n) => wfMatch(r, n));
|
|
141
|
+
const nonPr = runs.filter((r) => DEPLOY_EVENTS.includes(r.event));
|
|
142
|
+
let deployWorkflow = cfg.deployWorkflow ?? null;
|
|
143
|
+
if (!deployWorkflow) {
|
|
144
|
+
const counts = new Map();
|
|
145
|
+
for (const r of nonPr) if ((r.head_branch === base || r.event !== "push") && (DEPLOY_NAME_RE.test(r.name ?? "") || DEPLOY_NAME_RE.test(r.path ?? "")) && ranRun(r)) counts.set(r.path ?? r.name, (counts.get(r.path ?? r.name) ?? 0) + 1);
|
|
146
|
+
deployWorkflow = [...counts].sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])))[0]?.[0] ?? null;
|
|
147
|
+
}
|
|
148
|
+
const isDeploy = (r) => Boolean(deployWorkflow) && wfMatch(r, deployWorkflow);
|
|
149
|
+
const deploy = nonPr.filter(isDeploy).sort((a, b) => t(a.created_at) - t(b.created_at));
|
|
150
|
+
const rel = prs.filter((p) => p.base_ref === base && (!cfg.releaseHead || p.head_ref === cfg.releaseHead)).sort((a, b) => t(a.created_at) - t(b.created_at));
|
|
151
|
+
const releases = rel.map((pr) => {
|
|
152
|
+
const from = t(pr.created_at), to = t(pr.closed_at ?? pr.merged_at) || untilMs;
|
|
153
|
+
const open = (r) => r.head_branch === pr.head_ref && t(r.created_at) >= from && t(r.created_at) <= to;
|
|
154
|
+
let ci = runs.filter((r) => CI_EVENTS.includes(r.event) && wanted(r) && ((r.prs ?? []).includes(pr.number) || (!(r.prs ?? []).length && open(r))));
|
|
155
|
+
if (!ci.length) ci = runs.filter((r) => r.event === "push" && wanted(r) && !isDeploy(r) && open(r));
|
|
156
|
+
return { pr, ci };
|
|
157
|
+
});
|
|
158
|
+
const need = [...new Set([...releases.flatMap((x) => x.ci), ...deploy].filter(ranRun).map((r) => r.id))];
|
|
159
|
+
return { releases, deploy, deployWorkflow, need };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const round1 = (x, d = 1) => (x == null ? null : Math.round(x * 10 ** d) / 10 ** d);
|
|
163
|
+
const latest = (run, jobs) => (jobs ?? []).filter((j) => (j.run_attempt ?? 1) === (run.run_attempt ?? 1));
|
|
164
|
+
const first = (jobs) => (jobs ?? []).filter((j) => (j.run_attempt ?? 1) === 1);
|
|
165
|
+
/** Wall span of a run's first attempt: created -> the end of its first-attempt jobs (a later rerun must not stretch the round). */
|
|
166
|
+
function runSpan(run, jobs) {
|
|
167
|
+
const start = t(run.created_at);
|
|
168
|
+
const ends = (run.run_attempt ?? 1) > 1 ? first(jobs).filter(M.jobRan).map((j) => t(j.completed_at)) : [t(run.updated_at)];
|
|
169
|
+
const end = ends.length ? Math.max(...ends) : t(run.updated_at);
|
|
170
|
+
return { start, end };
|
|
171
|
+
}
|
|
172
|
+
/** The job that rolls out: `cfg.deployJob` (regex), else the longest ran job whose name says deploy, else the longest ran job. */
|
|
173
|
+
export function deployJobOf(jobs, cfg = {}) {
|
|
174
|
+
const ran = (jobs ?? []).filter(M.jobRan).sort((a, b) => M.jobSeconds(b) - M.jobSeconds(a));
|
|
175
|
+
const want = re(cfg.deployJob);
|
|
176
|
+
if (want) return ran.find((j) => want.test(j.name)) ?? null;
|
|
177
|
+
return ran.find((j) => DEPLOY_NAME_RE.test(j.name)) ?? ran[0] ?? null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The ledger report (pure). `data`: {repo, sinceMs, untilMs, base, prs, runs, jobs: {<run id>: job[]}, ledger?: [{pr, deployAttempts, live}]}.
|
|
182
|
+
* Every metric is null without a sample; `n` carries each sample size. Nothing is estimated.
|
|
183
|
+
*/
|
|
184
|
+
export function computeReleaseLedger(data, cfg = {}) {
|
|
185
|
+
const { repo, sinceMs, untilMs, base, jobs = {} } = data;
|
|
186
|
+
const plan = planLedger({ prs: data.prs, runs: data.runs, base, cfg, untilMs });
|
|
187
|
+
const jobsOf = (r) => jobs[r.id] ?? [];
|
|
188
|
+
const n = {}, m = {}, notes = [];
|
|
189
|
+
const ciRuns = [...new Map(plan.releases.flatMap((x) => x.ci).filter(ranRun).map((r) => [r.id, r])).values()];
|
|
190
|
+
const ciJobs = ciRuns.flatMap(jobsOf);
|
|
191
|
+
|
|
192
|
+
// rounds: one per (release PR, head sha)
|
|
193
|
+
const rounds = [], pushes = [];
|
|
194
|
+
for (const { pr, ci } of plan.releases) {
|
|
195
|
+
const bySha = new Map();
|
|
196
|
+
for (const r of ci) { if (!bySha.has(r.head_sha)) bySha.set(r.head_sha, []); bySha.get(r.head_sha).push(r); }
|
|
197
|
+
if (bySha.size) pushes.push({ pr: pr.number, pushes: bySha.size });
|
|
198
|
+
for (const [sha, rs] of bySha) {
|
|
199
|
+
const done = rs.filter(ranRun);
|
|
200
|
+
if (!done.length || rs.some((r) => r.status !== "completed")) continue;
|
|
201
|
+
const spans = done.map((r) => runSpan(r, jobsOf(r)));
|
|
202
|
+
const outcome = done.some((r) => M.isFailedConclusion(r.conclusion)) ? "fail" : done.some((r) => lcs(r.conclusion) === "cancelled") ? "cancelled" : "pass";
|
|
203
|
+
rounds.push({ pr: pr.number, sha, outcome, runs: done, wallMin: (Math.max(...spans.map((s) => s.end)) - Math.min(...spans.map((s) => s.start))) / 60000,
|
|
204
|
+
jobMin: done.flatMap((r) => first(jobsOf(r))).reduce((a, j) => a + M.jobSeconds(j), 0) / 60 });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const judged = rounds.filter((r) => r.outcome !== "cancelled");
|
|
208
|
+
m.ci_round_wall_min_p50 = round1(p50(judged.map((r) => r.wallMin))); m.ci_round_wall_min_p90 = round1(p90(judged.map((r) => r.wallMin)));
|
|
209
|
+
m.ci_round_job_min_p50 = round1(p50(judged.map((r) => r.jobMin)));
|
|
210
|
+
m.ci_round_fail_rate = judged.length ? round1(judged.filter((r) => r.outcome === "fail").length / judged.length, 3) : null;
|
|
211
|
+
n.rounds = judged.length;
|
|
212
|
+
m.pushes_per_release_pr_p50 = round1(p50(pushes.map((x) => x.pushes))); m.pushes_per_release_pr_max = pushes.length ? Math.max(...pushes.map((x) => x.pushes)) : null;
|
|
213
|
+
n.release_prs = plan.releases.length; n.release_prs_with_ci = pushes.length;
|
|
214
|
+
|
|
215
|
+
const sh = M.minuteShares(ciJobs);
|
|
216
|
+
m.failed_minute_share = round1(sh.failedShare, 3); m.cancelled_minute_share = round1(sh.cancelledShare, 3); m.ci_job_minutes = round1(sh.seconds / 60, 0);
|
|
217
|
+
n.ci_runs = ciRuns.length; n.ci_jobs = ciJobs.filter(M.jobRan).length;
|
|
218
|
+
|
|
219
|
+
// critical path: the job that ends last in each judged round (latest attempt of every run of that head)
|
|
220
|
+
const crit = new Map(), byName = new Map();
|
|
221
|
+
for (const r of ciRuns) for (const j of latest(r, jobsOf(r)).filter(M.jobRan)) { if (!byName.has(j.name)) byName.set(j.name, []); byName.get(j.name).push(j); }
|
|
222
|
+
let critRuns = 0;
|
|
223
|
+
for (const rd of judged) {
|
|
224
|
+
const c = M.criticalJob(rd.runs.flatMap((r) => latest(r, jobsOf(r))));
|
|
225
|
+
if (c) { critRuns++; crit.set(c.name, (crit.get(c.name) ?? 0) + 1); }
|
|
226
|
+
}
|
|
227
|
+
const critical_path = [...crit].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5).map(([job, runs]) => {
|
|
228
|
+
const js = byName.get(job) ?? [];
|
|
229
|
+
return { job, rounds: runs, of: critRuns, min_p50: round1(p50(js.map((j) => M.jobSeconds(j) / 60))), fail_rate: js.length ? round1(js.filter((j) => M.isFailedConclusion(j.conclusion)).length / js.length, 3) : null };
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
// deploy
|
|
233
|
+
const deployRuns = plan.deploy.filter(ranRun).filter((r) => jobsOf(r).some(M.jobRan));
|
|
234
|
+
const attempts = deployRuns.map((r) => {
|
|
235
|
+
const js = latest(r, jobsOf(r)), dj = deployJobOf(js, cfg);
|
|
236
|
+
const live = lcs(r.conclusion) === "success" && Boolean(dj) && lcs(dj.conclusion) === "success";
|
|
237
|
+
return { run: r, jobs: js, dj, live, liveAt: live ? t(dj.completed_at) : null };
|
|
238
|
+
});
|
|
239
|
+
const liveAttempts = attempts.filter((a) => a.live);
|
|
240
|
+
n.deploy_attempts = attempts.length; n.deploy_live = liveAttempts.length;
|
|
241
|
+
m.deploy_live_rate = attempts.length ? round1(liveAttempts.length / attempts.length, 3) : null;
|
|
242
|
+
m.deploy_pregate_min_p50 = round1(p50(liveAttempts.map((a) => (t(a.dj.started_at) - t(a.run.run_started_at ?? a.run.created_at)) / 60000)));
|
|
243
|
+
m.deploy_job_min_p50 = round1(p50(liveAttempts.map((a) => M.jobSeconds(a.dj) / 60)));
|
|
244
|
+
m.deploy_run_min_p50 = round1(p50(liveAttempts.map((a) => (t(a.run.updated_at) - t(a.run.run_started_at ?? a.run.created_at)) / 60000)));
|
|
245
|
+
const stepSecs = new Map();
|
|
246
|
+
for (const a of liveAttempts) for (const s of a.dj.steps ?? []) {
|
|
247
|
+
const sec = (t(s.completed_at) - t(s.started_at)) / 1000;
|
|
248
|
+
if (!(sec > 0)) continue;
|
|
249
|
+
if (!stepSecs.has(s.name)) stepSecs.set(s.name, []);
|
|
250
|
+
stepSecs.get(s.name).push(sec);
|
|
251
|
+
}
|
|
252
|
+
const deploy_steps = [...stepSecs].map(([step, v]) => ({ step, min_p50: round1(p50(v) / 60, 2), n: v.length })).sort((a, b) => b.min_p50 - a.min_p50).slice(0, 10);
|
|
253
|
+
|
|
254
|
+
// setup, queue, image build: over every ledger job that ran
|
|
255
|
+
const allJobs = [...ciJobs, ...deployRuns.flatMap(jobsOf)].filter(M.jobRan);
|
|
256
|
+
m.queue_s_p90 = round1(p90(allJobs.map(M.queueSeconds).filter((x) => x != null)), 0); m.queue_s_p50 = round1(p50(allJobs.map(M.queueSeconds).filter((x) => x != null)), 0);
|
|
257
|
+
const setup = {};
|
|
258
|
+
for (const [kind, js] of [["self_hosted", allJobs.filter(M.isSelfHosted)], ["hosted", allJobs.filter((j) => !M.isSelfHosted(j))]]) {
|
|
259
|
+
const per = js.map(M.jobSetup).filter((s) => s.total > 0);
|
|
260
|
+
const cls = (k) => round1(p50(per.map((s) => s[k]).filter((x) => x > 0)), 0);
|
|
261
|
+
setup[kind] = { jobs: per.length, checkout_s: cls("checkout"), toolchain_s: cls("toolchain"), deps_s: cls("deps"), };
|
|
262
|
+
setup[kind].total_s = per.length ? (setup[kind].checkout_s ?? 0) + (setup[kind].toolchain_s ?? 0) + (setup[kind].deps_s ?? 0) : null; // the sum of the three class medians, as the plan states it
|
|
263
|
+
m[`setup_${kind}_s`] = setup[kind].total_s;
|
|
264
|
+
}
|
|
265
|
+
const img = allJobs.map((j) => (j.steps ?? []).filter((s) => M.classifyStep(s.name) === "image-build").reduce((a, s) => a + Math.max(0, t(s.completed_at) - t(s.started_at)) / 60000, 0)).filter((x) => x > 0);
|
|
266
|
+
m.image_build_min_p50 = round1(p50(img)); n.image_build_jobs = img.length;
|
|
267
|
+
|
|
268
|
+
// failure surfacing: when a failed run ends (what an agent sees today) vs when its first failed step ended
|
|
269
|
+
const surfaced = [], firstStep = [], mech = [];
|
|
270
|
+
for (const r of ciRuns.filter((x) => M.isFailedConclusion(x.conclusion))) {
|
|
271
|
+
const ff = M.firstFailedStep(latest(r, jobsOf(r)));
|
|
272
|
+
if (!ff) continue;
|
|
273
|
+
const start = t(r.run_started_at ?? r.created_at), end = (t(r.updated_at) - start) / 1000;
|
|
274
|
+
surfaced.push(end); firstStep.push((t(ff.at) - start) / 1000);
|
|
275
|
+
if (M.MECHANICAL_CLASSES.includes(ff.cls)) mech.push(end);
|
|
276
|
+
}
|
|
277
|
+
m.failure_surfaced_s_p50 = round1(p50(surfaced), 0); m.first_failed_step_s_p50 = round1(p50(firstStep), 0);
|
|
278
|
+
m.mechanical_failure_surfaced_s = round1(p50(mech), 0); n.failed_runs = surfaced.length; n.mechanical_failures = mech.length;
|
|
279
|
+
|
|
280
|
+
// releases: opened -> live
|
|
281
|
+
const merged = plan.releases.map((x) => x.pr).filter((p) => p.merged_at);
|
|
282
|
+
const ledgerBy = new Map((data.ledger ?? []).filter((l) => l?.pr != null).map((l) => [Number(l.pr), l]));
|
|
283
|
+
const releases = merged.map((pr, i) => {
|
|
284
|
+
const next = merged[i + 1] ? t(merged[i + 1].merged_at) : Infinity;
|
|
285
|
+
let own = attempts.filter((a) => a.run.head_sha === pr.merge_commit_sha);
|
|
286
|
+
if (!own.length) own = attempts.filter((a) => t(a.run.created_at) >= t(pr.merged_at) && t(a.run.created_at) < next);
|
|
287
|
+
const firstLive = own.find((a) => a.live);
|
|
288
|
+
const liveAt = plan.deployWorkflow ? firstLive?.liveAt ?? null : t(pr.merged_at);
|
|
289
|
+
const led = ledgerBy.get(pr.number);
|
|
290
|
+
const tries = Math.max(own.length, Number(led?.deployAttempts) || 0);
|
|
291
|
+
return { pr: pr.number, opened: pr.created_at, merged: pr.merged_at, live: liveAt ? new Date(liveAt).toISOString() : null, hours: liveAt ? round1((liveAt - t(pr.created_at)) / 3600000, 2) : null,
|
|
292
|
+
pushes: pushes.find((x) => x.pr === pr.number)?.pushes ?? null, deploy_attempts: tries, clean: Boolean(liveAt) && tries <= 1 && (!own.length || own[0].live) };
|
|
293
|
+
});
|
|
294
|
+
if (!plan.deployWorkflow) notes.push("no deploy workflow found: live = the release PR's merge time (set stats.ledger_deploy_workflow)");
|
|
295
|
+
else if (!cfg.deployWorkflow) notes.push(`deploy workflow detected: ${plan.deployWorkflow} (set stats.ledger_deploy_workflow to pin it)`);
|
|
296
|
+
const wentLive = releases.filter((r) => r.hours != null), clean = wentLive.filter((r) => r.clean);
|
|
297
|
+
m.pr_to_live_h_median = round1(p50(wentLive.map((r) => r.hours)), 2); m.pr_to_live_h_p90 = round1(p90(wentLive.map((r) => r.hours)), 2);
|
|
298
|
+
m.pr_to_live_clean_h_median = round1(p50(clean.map((r) => r.hours)), 2); m.pr_to_live_clean_h_p90 = round1(p90(clean.map((r) => r.hours)), 2);
|
|
299
|
+
n.live_releases = wentLive.length; n.clean_releases = clean.length;
|
|
300
|
+
const missing = plan.need.filter((id) => !jobs[id]).length;
|
|
301
|
+
if (missing) notes.push(`${missing} run(s) without job data (not fetched): job-level metrics exclude them`);
|
|
302
|
+
|
|
303
|
+
return { v: 1, repo, base, window: { since: new Date(sinceMs).toISOString(), until: new Date(untilMs).toISOString(), days: round1((untilMs - sinceMs) / 86400000) },
|
|
304
|
+
deploy_workflow: plan.deployWorkflow, n, metrics: m, table: ledgerTable(m), critical_path, setup, deploy_steps, releases, notes };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const fmtVal = (unit, v) => (v == null ? "n/a" : unit === "pct" ? `${(v * 100).toFixed(1)}%` : unit === "n" ? String(v) : `${v} ${unit}`);
|
|
308
|
+
/** Rows of the Targets table: today vs phase 1 vs end, with `status` end-met | phase1-met | not-met | no-target | n/a. */
|
|
309
|
+
export function ledgerTable(metrics, defs = LEDGER_METRICS) {
|
|
310
|
+
return defs.map((d) => {
|
|
311
|
+
const v = metrics[d.key] ?? null;
|
|
312
|
+
const meets = (target) => (d.higherBetter ? v >= target : v <= target);
|
|
313
|
+
const status = d.end == null ? "no-target" : v == null ? "n/a" : meets(d.end) ? "end-met" : meets(d.phase1) ? "phase1-met" : "not-met";
|
|
314
|
+
return { key: d.key, label: d.label, unit: d.unit, today: v, phase1: d.phase1 ?? null, end: d.end ?? null, status };
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const mdTable = (head, rows) => { const line = (r) => `| ${r.join(" | ")} |`; return [line(head), line(head.map(() => "---")), ...rows.map(line)]; };
|
|
319
|
+
const tgt = (unit, v, hb) => (v == null ? "-" : `${hb ? ">=" : "<="} ${fmtVal(unit, v)}`);
|
|
320
|
+
export function renderReleaseLedger(r) {
|
|
321
|
+
const defs = new Map(LEDGER_METRICS.map((d) => [d.key, d]));
|
|
322
|
+
const out = [`Release ledger: ${r.repo}, ${r.window.since.slice(0, 10)} to ${r.window.until.slice(0, 10)} (${r.window.days} days), release base ${r.base}`,
|
|
323
|
+
`${r.n.release_prs} release PR(s), ${r.n.live_releases} live (${r.n.clean_releases} clean); ${r.n.ci_runs} CI run(s), ${r.n.ci_jobs} job(s), ${r.n.rounds} round(s); ${r.n.deploy_attempts} deploy attempt(s), ${r.n.deploy_live} reached live`, "",
|
|
324
|
+
...mdTable(["Stage", "Today (measured)", "Phase 1 target", "End target", "Status"], r.table.map((x) => { const hb = defs.get(x.key)?.higherBetter; return [x.label, fmtVal(x.unit, x.today), tgt(x.unit, x.phase1, hb), tgt(x.unit, x.end, hb), x.status]; }))];
|
|
325
|
+
const s = r.setup;
|
|
326
|
+
out.push("", "Job setup p50 (checkout + toolchain + dependencies):");
|
|
327
|
+
for (const k of ["self_hosted", "hosted"]) out.push(` ${k.replace("_", "-")}: ${s[k].jobs ? `${s[k].checkout_s ?? "n/a"} s + ${s[k].toolchain_s ?? "n/a"} s + ${s[k].deps_s ?? "n/a"} s (total ${s[k].total_s} s, ${s[k].jobs} job(s))` : "n/a"}`);
|
|
328
|
+
out.push(`CI round: wall p50 ${fmtVal("min", r.metrics.ci_round_wall_min_p50)}, p90 ${fmtVal("min", r.metrics.ci_round_wall_min_p90)}, ${fmtVal("min", r.metrics.ci_round_job_min_p50)} of jobs p50; pushes per release PR p50 ${r.metrics.pushes_per_release_pr_p50 ?? "n/a"} (max ${r.metrics.pushes_per_release_pr_max ?? "n/a"})`);
|
|
329
|
+
out.push(`Failures: surfaced at run end p50 ${fmtVal("s", r.metrics.failure_surfaced_s_p50)}; the first failed step ended at p50 ${fmtVal("s", r.metrics.first_failed_step_s_p50)} (${r.n.failed_runs} failed run(s), ${r.n.mechanical_failures} mechanical)`);
|
|
330
|
+
out.push(`Queue: p50 ${fmtVal("s", r.metrics.queue_s_p50)}, p90 ${fmtVal("s", r.metrics.queue_s_p90)}`);
|
|
331
|
+
if (r.critical_path.length) out.push("", "Critical path (the job that ends last):", ...mdTable(["Job", "Rounds", "p50", "Fails"], r.critical_path.map((c) => [c.job, `${c.rounds} of ${c.of}`, fmtVal("min", c.min_p50), fmtVal("pct", c.fail_rate)])));
|
|
332
|
+
if (r.deploy_steps.length) out.push("", `Deploy job by step (p50 over ${r.n.deploy_live} live deploy(s); run p50 ${fmtVal("min", r.metrics.deploy_run_min_p50)}):`, ...mdTable(["Step", "p50"], r.deploy_steps.map((d) => [d.step, fmtVal("min", d.min_p50)])));
|
|
333
|
+
for (const note of r.notes) out.push("", `note: ${note}`);
|
|
334
|
+
return out.join("\n");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Baseline record of a report: what `--baseline compare` reads back. */
|
|
338
|
+
export const baselineOf = (r, now = Date.now()) => ({ v: 1, saved_at: new Date(now).toISOString(), repo: r.repo, window: r.window, n: r.n, metrics: r.metrics });
|
|
339
|
+
/** Before/after per metric, measured the same way: verdict improved | regressed | flat (within 5%, or 2 points for a share) | null when either side is missing. */
|
|
340
|
+
export function compareBaseline(base, r, defs = LEDGER_METRICS) {
|
|
341
|
+
const rows = defs.map((d) => {
|
|
342
|
+
const before = base?.metrics?.[d.key] ?? null, after = r.metrics[d.key] ?? null;
|
|
343
|
+
let verdict = null, delta = null;
|
|
344
|
+
if (before != null && after != null) {
|
|
345
|
+
delta = round1(after - before, 3);
|
|
346
|
+
const rel = d.unit === "pct" ? Math.abs(delta) <= 0.02 : before === 0 ? after === 0 : Math.abs(delta / before) <= 0.05;
|
|
347
|
+
verdict = rel ? "flat" : (delta < 0) === !d.higherBetter ? "improved" : "regressed";
|
|
348
|
+
}
|
|
349
|
+
return { key: d.key, label: d.label, unit: d.unit, before, after, delta, verdict };
|
|
350
|
+
});
|
|
351
|
+
return { baseline: { saved_at: base?.saved_at ?? null, window: base?.window ?? null, n: base?.n ?? null }, rows };
|
|
352
|
+
}
|
|
353
|
+
export function renderBaselineCompare(c, r) {
|
|
354
|
+
const w = (x) => (x ? `${x.since.slice(0, 10)} to ${x.until.slice(0, 10)}` : "n/a");
|
|
355
|
+
return [`Release ledger before/after: ${r.repo}`, `before: ${w(c.baseline.window)} (saved ${c.baseline.saved_at ?? "n/a"}); after: ${w(r.window)}`, "",
|
|
356
|
+
...mdTable(["Stage", "Before", "After", "Verdict"], c.rows.map((x) => [x.label, fmtVal(x.unit, x.before), fmtVal(x.unit, x.after), x.verdict ?? "n/a"]))].join("\n");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const PR_JQ = ".[] | {number, title, state, created_at, merged_at, closed_at, merge_commit_sha, head_ref: .head.ref, head_sha: .head.sha, base_ref: .base.ref} | @json";
|
|
360
|
+
const jsonLines = (out) => String(out ?? "").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
|
|
361
|
+
/** PRs into `base` opened since `sinceMs`, newest first; stops paging at the first page that reaches the window's start. */
|
|
362
|
+
export async function listReleasePrs({ gh, repo, base, sinceMs }) {
|
|
363
|
+
const out = [];
|
|
364
|
+
for (let page = 1; page <= 50; page++) {
|
|
365
|
+
const rows = jsonLines(await gh(["api", `repos/${repo}/pulls?state=all&base=${encodeURIComponent(base)}&sort=created&direction=desc&per_page=100&page=${page}`, "--jq", PR_JQ]));
|
|
366
|
+
out.push(...rows.filter((p) => t(p.created_at) >= sinceMs));
|
|
367
|
+
if (rows.length < 100 || t(rows[rows.length - 1].created_at) < sinceMs) break;
|
|
368
|
+
}
|
|
369
|
+
return out;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const JOBS_CACHE = "actions-jobs.json";
|
|
373
|
+
function loadJobsCache(repo, env) { try { const c = JSON.parse(readFileSync(join(cacheDir(repo, env), JOBS_CACHE), "utf8")); return c?.v === 1 && c.runs ? c : { v: 1, runs: {} }; } catch { return { v: 1, runs: {} }; } }
|
|
374
|
+
function saveJobsCache(repo, cache, env) { try { const dir = cacheDir(repo, env); mkdirSync(dir, { recursive: true }); const tmp = join(dir, `${JOBS_CACHE}.${process.pid}.tmp`); writeFileSync(tmp, JSON.stringify(cache)); renameSync(tmp, join(dir, JOBS_CACHE)); } catch { /* the cache is optional */ } }
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Reads everything the ledger needs: the release PRs, the runs of the release head branches and of the base (paginated, one
|
|
378
|
+
* query per branch and event) and the jobs of the ledger's runs only (4 at a time). Jobs of a completed run never change, so they are cached per (run, attempt) next to the stats cache;
|
|
379
|
+
* `maxRuns` bounds the job fetches of one call (newest first) and the report notes what was left out.
|
|
380
|
+
*/
|
|
381
|
+
export async function gatherReleaseLedger({ gh, repo, sinceMs, untilMs = Date.now(), cfg = {}, env = process.env, useCache = true, maxRuns = 600, onProgress = () => {}, ledger = [] }) {
|
|
382
|
+
const base = cfg.releaseBase ?? String(await gh(["api", `repos/${repo}`, "--jq", ".default_branch"])).trim();
|
|
383
|
+
const prs = await listReleasePrs({ gh, repo, base, sinceMs });
|
|
384
|
+
// Scoped reads: PR-event runs of each release head branch (push runs only where a head has none) and the non-PR runs of the base.
|
|
385
|
+
const heads = [...new Set(prs.filter((p) => !cfg.releaseHead || p.head_ref === cfg.releaseHead).map((p) => p.head_ref))], seen = new Map();
|
|
386
|
+
const read = async (branch, event) => { for (const r of await M.listRuns({ gh, repo, sinceMs, untilMs, branch, event })) seen.set(r.id, r); };
|
|
387
|
+
for (const head of heads) {
|
|
388
|
+
const before = seen.size;
|
|
389
|
+
for (const e of CI_EVENTS) await read(head, e);
|
|
390
|
+
if (seen.size === before) await read(head, "push");
|
|
391
|
+
}
|
|
392
|
+
for (const e of DEPLOY_EVENTS) await read(base, e);
|
|
393
|
+
const runs = [...seen.values()];
|
|
394
|
+
const plan = planLedger({ prs, runs, base, cfg, untilMs });
|
|
395
|
+
const byId = new Map(runs.map((r) => [r.id, r]));
|
|
396
|
+
const cache = useCache ? loadJobsCache(repo, env) : { v: 1, runs: {} };
|
|
397
|
+
const key = (r) => `${r.id}:${r.run_attempt ?? 1}`;
|
|
398
|
+
const jobs = {}, todo = [];
|
|
399
|
+
for (const id of plan.need) { const r = byId.get(id), hit = cache.runs[key(r)]; if (hit) jobs[id] = hit; else todo.push(r); }
|
|
400
|
+
todo.sort((a, b) => t(b.created_at) - t(a.created_at));
|
|
401
|
+
const batch = todo.slice(0, maxRuns);
|
|
402
|
+
let done = 0;
|
|
403
|
+
const worker = async () => { for (let r; (r = batch.shift());) { jobs[r.id] = await M.listRunJobs({ gh, repo, runId: r.id }); cache.runs[key(r)] = jobs[r.id]; onProgress({ done: ++done, total: done + batch.length }); } };
|
|
404
|
+
await Promise.all(Array.from({ length: 4 }, worker));
|
|
405
|
+
if (useCache && done) saveJobsCache(repo, cache, env);
|
|
406
|
+
return { repo, sinceMs, untilMs, base, prs, runs, jobs, ledger };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** `--since` of the ledger: a date (YYYY-MM-DD[T...]) or a window (`21d`, `36h`); default 21 days. */
|
|
410
|
+
export function ledgerSince(since, now = Date.now()) {
|
|
411
|
+
if (!since) return now - 21 * 86400000;
|
|
412
|
+
const w = /^(\d+)([dh])$/.exec(since);
|
|
413
|
+
if (w) return now - Number(w[1]) * (w[2] === "d" ? 86400000 : 3600000);
|
|
414
|
+
const ms = /^\d{4}-\d{2}-\d{2}/.test(since) ? Date.parse(since) : NaN;
|
|
415
|
+
if (Number.isNaN(ms)) throw new Error(`--since must be a date (YYYY-MM-DD) or a window (21d, 36h) with --release-ledger: ${since}`);
|
|
416
|
+
return ms;
|
|
417
|
+
}
|
|
418
|
+
export const baselinePath = (repo, file, env = process.env) => file ?? join(cacheDir(repo, env), "release-ledger-baseline.json");
|
|
419
|
+
|
|
420
|
+
/** `forgedock stats --release-ledger`: 0, 1 on a read failure, 2 when `--baseline compare` has no baseline. */
|
|
421
|
+
export async function runReleaseLedger(opts, deps = {}) {
|
|
422
|
+
const now = deps.now?.() ?? Date.now(), env = deps.env ?? process.env, write = deps.write ?? ((s) => process.stdout.write(s));
|
|
423
|
+
const cfg = { ...(deps.config ?? {}), ...(opts.deployWorkflow ? { deployWorkflow: opts.deployWorkflow } : {}), ...(opts.releaseHead ? { releaseHead: opts.releaseHead === "any" ? null : opts.releaseHead } : {}) };
|
|
424
|
+
const data = await gatherReleaseLedger({ gh: deps.gh, repo: opts.repo, sinceMs: ledgerSince(opts.since, now), untilMs: now, cfg, env, useCache: opts.cache !== false, onProgress: deps.onProgress, ledger: deps.ledger ?? [] });
|
|
425
|
+
const report = computeReleaseLedger(data, cfg);
|
|
426
|
+
const file = baselinePath(opts.repo, opts.baselineFile, env);
|
|
427
|
+
if (opts.baseline === "compare") {
|
|
428
|
+
let base = null;
|
|
429
|
+
try { base = JSON.parse(readFileSync(file, "utf8")); } catch { /* reported below */ }
|
|
430
|
+
if (!base?.metrics) { process.stderr.write(`forgedock stats: no baseline at ${file} (run --release-ledger --baseline save first)\n`); return 2; }
|
|
431
|
+
const cmp = compareBaseline(base, report);
|
|
432
|
+
write(`${opts.json ? JSON.stringify({ ...report, compare: cmp }, null, 2) : `${renderBaselineCompare(cmp, report)}\n\n${renderReleaseLedger(report)}`}\n`);
|
|
433
|
+
return 0;
|
|
434
|
+
}
|
|
435
|
+
if (opts.baseline === "save") { mkdirSync(dirname(file), { recursive: true }); writeFileSync(file, `${JSON.stringify(baselineOf(report, now), null, 2)}\n`); }
|
|
436
|
+
write(`${opts.json ? JSON.stringify(report, null, 2) : renderReleaseLedger(report)}\n`);
|
|
437
|
+
if (opts.baseline === "save" && !opts.json) write(`\nbaseline saved: ${file}\n`);
|
|
438
|
+
return 0;
|
|
439
|
+
}
|