forgedock 1.56.0 → 1.58.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.
Files changed (140) hide show
  1. package/bin/config-schema.mjs +1 -1
  2. package/bin/engine/outcome-codes.mjs +2 -1
  3. package/bin/engine/phases.mjs +4 -3
  4. package/bin/engine-cli.mjs +48 -12
  5. package/bin/forgedock.mjs +52 -3
  6. package/bin/gc.mjs +43 -6
  7. package/bin/help-text.mjs +4 -2
  8. package/bin/lean/batch-health.mjs +5 -1
  9. package/bin/lean/batch-health.test.mjs +7 -1
  10. package/bin/lean/batch.mjs +7 -2
  11. package/bin/lean/batch.test.mjs +45 -0
  12. package/bin/lean/conformance.e2e.test.mjs +3 -2
  13. package/bin/lean/conformance.mjs +118 -20
  14. package/bin/lean/conformance.test.mjs +172 -3
  15. package/bin/lean/decisions.mjs +98 -1
  16. package/bin/lean/decisions.test.mjs +30 -1
  17. package/bin/lean/depcache.mjs +124 -13
  18. package/bin/lean/depcache.test.mjs +121 -3
  19. package/bin/lean/design-gate.mjs +144 -0
  20. package/bin/lean/design-gate.test.mjs +169 -0
  21. package/bin/lean/effects-cap.test.mjs +17 -0
  22. package/bin/lean/effects.mjs +58 -13
  23. package/bin/lean/heavy.mjs +25 -8
  24. package/bin/lean/hostload.test.mjs +28 -0
  25. package/bin/lean/intake.mjs +97 -0
  26. package/bin/lean/intake.test.mjs +105 -0
  27. package/bin/lean/interfaces.mjs +181 -0
  28. package/bin/lean/interfaces.test.mjs +192 -0
  29. package/bin/lean/issuewatch-install.mjs +52 -12
  30. package/bin/lean/issuewatch-install.test.mjs +50 -0
  31. package/bin/lean/issuewatch-parity.mjs +16 -3
  32. package/bin/lean/issuewatch-parity.test.mjs +32 -0
  33. package/bin/lean/issuewatch-reconcile.mjs +29 -1
  34. package/bin/lean/issuewatch-reconcile.test.mjs +21 -0
  35. package/bin/lean/issuewatch.mjs +34 -3
  36. package/bin/lean/issuewatch.test.mjs +49 -1
  37. package/bin/lean/lanecheck.test.mjs +15 -4
  38. package/bin/lean/lean.mjs +110 -24
  39. package/bin/lean/lean.test.mjs +183 -4
  40. package/bin/lean/orchestrate-blocked.test.mjs +18 -2
  41. package/bin/lean/orchestrate-owned.test.mjs +14 -5
  42. package/bin/lean/orchestrate.mjs +26 -4
  43. package/bin/lean/orphan-pr.mjs +3 -2
  44. package/bin/lean/orphan-pr.test.mjs +8 -1
  45. package/bin/lean/pagegate.mjs +35 -12
  46. package/bin/lean/pagegate.test.mjs +39 -1
  47. package/bin/lean/preflight.mjs +35 -1
  48. package/bin/lean/preflight.test.mjs +27 -1
  49. package/bin/lean/prompts.mjs +2 -1
  50. package/bin/lean/reap.test.mjs +39 -0
  51. package/bin/lean/recovery.test.mjs +28 -3
  52. package/bin/lean/release-config.mjs +169 -0
  53. package/bin/lean/release-config.test.mjs +132 -0
  54. package/bin/lean/release-control.mjs +171 -0
  55. package/bin/lean/release-control.test.mjs +167 -0
  56. package/bin/lean/release-deploy.mjs +209 -0
  57. package/bin/lean/release-deploy.test.mjs +217 -0
  58. package/bin/lean/release-fence.mjs +50 -0
  59. package/bin/lean/release-fence.test.mjs +105 -0
  60. package/bin/lean/release-flakes.mjs +139 -0
  61. package/bin/lean/release-flakes.test.mjs +116 -0
  62. package/bin/lean/release-gates.mjs +230 -0
  63. package/bin/lean/release-gates.test.mjs +146 -0
  64. package/bin/lean/release-ledger.mjs +176 -0
  65. package/bin/lean/release-ledger.test.mjs +226 -0
  66. package/bin/lean/release-minutes.mjs +102 -0
  67. package/bin/lean/release-minutes.test.mjs +107 -0
  68. package/bin/lean/release-nightly.mjs +75 -0
  69. package/bin/lean/release-nightly.test.mjs +48 -0
  70. package/bin/lean/release-postmerge.mjs +8 -2
  71. package/bin/lean/release-review.e2e.test.mjs +1 -0
  72. package/bin/lean/release-review.mjs +54 -7
  73. package/bin/lean/release-review.test.mjs +76 -7
  74. package/bin/lean/release-status.mjs +300 -0
  75. package/bin/lean/release-status.test.mjs +220 -0
  76. package/bin/lean/release-unitmap.mjs +35 -0
  77. package/bin/lean/release-unitmap.test.mjs +41 -0
  78. package/bin/lean/release-verify.mjs +221 -0
  79. package/bin/lean/release-verify.test.mjs +176 -0
  80. package/bin/lean/release.mjs +244 -22
  81. package/bin/lean/release.test.mjs +44 -0
  82. package/bin/lean/render.mjs +3 -1
  83. package/bin/lean/run-issue-placement.test.mjs +82 -0
  84. package/bin/lean/sandbox-remote.mjs +16 -0
  85. package/bin/lean/schedd.mjs +1 -1
  86. package/bin/lean/seam.mjs +115 -0
  87. package/bin/lean/seam.test.mjs +118 -0
  88. package/bin/lean/selftest-journey.mjs +40 -2
  89. package/bin/lean/selftest-journey.test.mjs +43 -3
  90. package/bin/lean/statuscomment.mjs +168 -0
  91. package/bin/lean/statuscomment.test.mjs +133 -0
  92. package/bin/lean/ui-quality.mjs +57 -0
  93. package/bin/lean/ui-quality.test.mjs +55 -0
  94. package/bin/lean/visual-gate.test.mjs +63 -0
  95. package/bin/pool/agent.mjs +16 -2
  96. package/bin/pool/router.mjs +5 -1
  97. package/bin/review-staging.mjs +5 -3
  98. package/bin/stats/card.mjs +117 -0
  99. package/bin/stats/card.test.mjs +109 -0
  100. package/bin/stats/conformance-outcomes.test.mjs +2 -1
  101. package/bin/stats/depth.mjs +1 -1
  102. package/bin/stats/gh-retry.test.mjs +152 -0
  103. package/bin/stats/github-source.mjs +147 -14
  104. package/bin/stats/index.mjs +35 -2
  105. package/bin/stats/stats.test.mjs +31 -3
  106. package/bin/vendor/js-yaml/LICENSE +21 -0
  107. package/bin/vendor/js-yaml/PIN.md +7 -0
  108. package/bin/vendor/js-yaml/js-yaml.mjs +3851 -0
  109. package/commands/design-render-critique-loop.md +2 -0
  110. package/commands/design.md +2 -0
  111. package/commands/issue.md +1 -1
  112. package/commands/milestone.md +1 -1
  113. package/commands/review-pr-agents/frontend.md +1 -0
  114. package/commands/review-pr-staging.md +5 -0
  115. package/docs/CONFIG.md +95 -2
  116. package/docs/ISSUE-WATCH.md +7 -0
  117. package/docs/OUTCOME-CODES.md +1 -0
  118. package/docs/STATS.md +10 -0
  119. package/docs/design/visual-gate.md +25 -0
  120. package/docs/eval/adversarial-bench.md +2 -2
  121. package/docs/eval/corpus/adversarial-v1.json +3 -3
  122. package/docs/site/start-a-new-project.md +7 -0
  123. package/docs/spec/forge-protocol-v1.md +31 -0
  124. package/package.json +1 -1
  125. package/pool/README.md +2 -0
  126. package/scripts/acceptance-red-green.sh +15 -1
  127. package/scripts/acceptance-red-green.test.sh +12 -0
  128. package/scripts/bench-adversarial.mjs +4 -0
  129. package/scripts/bench-lightlane.mjs +4 -1
  130. package/scripts/bootstrap-create.mjs +8 -2
  131. package/scripts/ci-local/scoping.mjs +19 -0
  132. package/scripts/ci-local.test.sh +16 -3
  133. package/scripts/fixtures/ci-local/gha-dorny/.github/workflows/ci.yml +4 -0
  134. package/scripts/plan-validate-live.mjs +9 -6
  135. package/scripts/review-prepare.sh +7 -1
  136. package/scripts/review-roster.sh +5 -2
  137. package/scripts/review-roster.test.sh +9 -0
  138. package/scripts/visual-gate.mjs +64 -0
  139. package/templates/bootstrap/technical-spike.md +17 -0
  140. package/templates/contracts/seam-check.mjs +236 -0
@@ -0,0 +1,217 @@
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 { deployStep, parseLiveRelease, liveMatches } from "./release-deploy.mjs";
6
+ import { validatePolicy } from "./release-config.mjs";
7
+
8
+ const SHA = "a".repeat(40), OLD = "b".repeat(40);
9
+ const POLICY = { live_release_command: "live", freeze_variable: "DEPLOY_FREEZE", start_timeout_s: 10, stage_timeout_s: 100, recovery: { rerun_max: 2, max_attempts: 3, signatures: ["429 Too Many"] }, pipelines: { full: { workflow: "deploy.yml", trigger: "push" } } };
10
+
11
+ /** World: `live` is a queue (last repeats) of live shas; `runs` a queue of run rows; `freeze` the variable value. */
12
+ function world(o = {}) {
13
+ const w = { live: [OLD, SHA], runs: [{ databaseId: 9, status: "completed", conclusion: "success" }], freeze: "", log: "", gh: [], ran: [], ...o };
14
+ const io = {
15
+ print: () => {}, sleep: async () => {}, git: () => "{}",
16
+ rehearse: async (cmd) => { w.ran.push(cmd); if (cmd === "live") { const v = w.live.length > 1 ? w.live.shift() : w.live[0]; return v == null ? { ok: false, output: "" } : { ok: true, output: v }; } if (w.failCheck) return { ok: false, output: "boom" }; return { ok: true, output: "{}" }; },
17
+ gh: async (a) => {
18
+ w.gh.push(a.join(" "));
19
+ if (a[0] === "variable") { if (!w.freeze) throw new Error("HTTP 404"); return w.freeze; }
20
+ if (a[0] === "run" && a[1] === "list") { const r = w.runs[Math.min(w.reran ?? 0, w.runs.length - 1)]; return JSON.stringify(r ? [r] : []); }
21
+ if (a[0] === "run" && a[1] === "view") return w.log;
22
+ if (a[0] === "run" && a[1] === "rerun") { w.reran = (w.reran ?? 0) + 1; return ""; }
23
+ if (a[0] === "workflow" || a[0] === "pr") return "";
24
+ throw new Error(`unexpected gh ${a.join(" ")}`);
25
+ },
26
+ };
27
+ return { w, io };
28
+ }
29
+ const mk = (io, over = {}, deploy = POLICY) => ({ io, repo: "o/r", def: "main", config: { deploy, deployBounds: { pollMs: 1, runPollMs: 1 } }, state: { steps: { "post-merge": { result: { merge: SHA } }, "release-pr": { result: { pr: 7 } } } }, save() {}, ...over });
30
+ const active = (o) => ({ content: Buffer.from(JSON.stringify(o)).toString("base64") });
31
+ const fence = (calls = []) => ({ lctx: { io: { api: async () => active({ epoch: 3, lease: { holder: "h", epoch: 3 } }) }, repo: "o/r" }, lease: { holder: "h", epoch: 3, release: "r" }, now: () => "t", record: async (r) => calls.push(r) });
32
+
33
+ describe("release deploy stages (#5560)", () => {
34
+ it("skips without a deploy policy and leaves no trace", async () => {
35
+ const { io } = world(); const c = mk(io, {}, null);
36
+ assert.deepEqual(await deployStep(c), { skipped: true }); assert.equal(c.state.deploy, undefined);
37
+ });
38
+ it("MERGED -> LIVE: records the rollback target, observes the run, passes LIVE_CHECK, and, without a verify policy, writes no FORGE:VERIFIED (#5562)", async () => {
39
+ const { w, io } = world(); const c = mk(io);
40
+ const out = await deployStep(c);
41
+ assert.equal(out.live, true); assert.equal(c.state.deploy.target.sha, OLD); assert.equal(c.state.deploy.phase, "LIVE");
42
+ assert.ok(!w.gh.some((g) => g.startsWith("pr comment") || g.includes("FORGE:VERIFIED")));
43
+ assert.ok(!w.gh.some((g) => g.startsWith("workflow run")), "an observed push run is never redispatched");
44
+ });
45
+ it("I9: an unknown rollback target blocks before any dispatch", async () => {
46
+ const { w, io } = world({ live: [null], runs: [] });
47
+ const out = await deployStep(mk(io));
48
+ assert.match(out.reason, /rollback target unknown/); assert.ok(!w.gh.some((g) => g.startsWith("workflow run")));
49
+ });
50
+ it("I28 + I26: a freeze-skipped success fails LIVE_CHECK and is never rerun or redispatched", async () => {
51
+ const { w, io } = world({ live: [OLD], freeze: "" });
52
+ w.gh.push; const orig = io.gh; io.gh = async (a) => { if (a[0] === "run" && a[1] === "list") w.freeze = "1"; return orig(a); }; // the run sets the freeze
53
+ const out = await deployStep(mk(io));
54
+ assert.equal(out.blocked, true); assert.match(out.reason, /LIVE_CHECK failed/); assert.match(out.reason, /override_freeze|I26/);
55
+ assert.equal(w.reran, undefined); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
56
+ });
57
+ it("a success run with a stale live record (no freeze) is a failed deploy, not retried", async () => {
58
+ const { w, io } = world({ live: [OLD] });
59
+ const out = await deployStep(mk(io));
60
+ assert.match(out.reason, /live is bbbbbbbb/); assert.equal(w.reran, undefined);
61
+ });
62
+ it("a transient build failure is rerun once and reaches LIVE with no human", async () => {
63
+ const { w, io } = world({ live: [OLD, SHA], log: "build: 429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
64
+ const out = await deployStep(mk(io));
65
+ assert.equal(out.live, true); assert.equal(out.reruns, 1); assert.equal(w.reran, 1);
66
+ });
67
+ it("rerun_max bounds the reruns, then escalates", async () => {
68
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
69
+ const out = await deployStep(mk(io));
70
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 2);
71
+ });
72
+ it("max_attempts bounds the actions", async () => {
73
+ const { w, io } = world({ live: [OLD], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
74
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { ...POLICY.recovery, rerun_max: 5, max_attempts: 1 } }));
75
+ assert.match(out.reason, /recovery spent/); assert.equal(w.reran, 1);
76
+ });
77
+ it("a failure without a transient signature is not rerun", async () => {
78
+ const { w, io } = world({ live: [OLD], log: "tsc error", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
79
+ const out = await deployStep(mk(io));
80
+ assert.match(out.reason, /never retried blindly/); assert.equal(w.reran, undefined);
81
+ });
82
+ it("dispatches (fenced, with forge_epoch) only when no run appears, and never an override input", async () => {
83
+ const { w, io } = world({ runs: [] }); const calls = [];
84
+ w.runs = []; const orig = io.gh; io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 11, status: "completed", conclusion: "success" }]; return r; };
85
+ const out = await deployStep(mk(io, { fence: fence(calls) }));
86
+ const d = w.gh.filter((g) => g.startsWith("workflow run")); assert.equal(out.live, true); assert.equal(d.length, 1);
87
+ assert.match(d[0], /forge_epoch=3/); assert.ok(!/override_|acknowledge_/.test(d[0]));
88
+ assert.ok(calls.some((r) => r.key.endsWith(`:deploy:3:deploy:${SHA}`)));
89
+ });
90
+ it("a stale epoch refuses the dispatch", async () => {
91
+ const { io } = world({ runs: [] });
92
+ const f = fence(); f.lctx = { io: { api: async () => active({ lease: { holder: "other", epoch: 4 }, epoch: 4 }) }, repo: "o/r" };
93
+ const out = await deployStep(mk(io, { fence: f }));
94
+ assert.match(out.reason, /fenced|refused/);
95
+ });
96
+ it("chaos: a throw at every boundary, then a resume, repeats no dispatch or rerun", async () => {
97
+ for (const dieOn of ["variable", "run list", "run view", "run rerun", "live"]) {
98
+ const { w, io } = world({ live: [OLD, SHA], log: "429 Too Many Requests", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
99
+ let armed = true; const g0 = io.gh, r0 = io.rehearse;
100
+ const maybe = (k) => { if (armed && k === dieOn) { armed = false; throw new Error("kill -9"); } };
101
+ io.gh = async (a) => { maybe(a.slice(0, 2).join(" ").replace(/^variable get$/, "variable")); return g0(a); };
102
+ io.rehearse = async (c, o) => { if (c === "live" && w.ran.length >= 3) maybe("live"); return r0(c, o); };
103
+ const c = mk(io);
104
+ try { await deployStep(c); } catch { /* killed */ }
105
+ const out = await deployStep(c);
106
+ assert.equal(out.live, true, dieOn);
107
+ assert.ok((w.reran ?? 0) <= 1, `${dieOn}: one rerun`);
108
+ assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0, dieOn);
109
+ }
110
+ });
111
+ });
112
+
113
+ describe("deploy observation and recovery (#5560)", () => {
114
+ it("trigger dispatch (service/hotfix) dispatches at once with unit inputs and forge_epoch, fenced under (release, step, epoch)", async () => {
115
+ const { w, io } = world({ runs: [] }); const calls = []; const orig = io.gh;
116
+ io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 11, status: "completed", conclusion: "success" }]; return r; };
117
+ const pol = { ...POLICY, pipelines: { service: { workflow: "deploy.yml", trigger: "dispatch", inputs: { unit: "api" } } } };
118
+ const out = await deployStep(mk(io, { fence: fence(calls), config: { deploy: pol, deployPipeline: "service", deployBounds: { pollMs: 1, runPollMs: 1 } } }));
119
+ const d = w.gh.filter((g) => g.startsWith("workflow run")); assert.equal(out.live, true); assert.equal(d.length, 1);
120
+ assert.match(d[0], /unit=api/); assert.match(d[0], /forge_epoch=3/);
121
+ assert.ok(calls.some((r) => r.key.endsWith(`:deploy:3:deploy:${SHA}`)));
122
+ });
123
+ it("R2: a dispatch intent without a visible run is never redispatched on resume", async () => {
124
+ const { w, io } = world({ runs: [] });
125
+ const pol = { ...POLICY, pipelines: { service: { workflow: "deploy.yml", trigger: "dispatch" } } };
126
+ const intents = [{ key: `r:deploy:2:deploy:${SHA}`, action: "dispatch", epoch: 2 }];
127
+ const out = await deployStep(mk(io, { fence: fence(), state: { intents, steps: { "post-merge": { result: { merge: SHA } } } }, config: { deploy: pol, deployPipeline: "service", deployBounds: { pollMs: 1, runPollMs: 1 } } }));
128
+ assert.ok(out.blocked); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
129
+ });
130
+ it("a skipped push run is expected: it is not a run, so the deploy is dispatched", async () => {
131
+ const { w, io } = world({ runs: [{ databaseId: 5, status: "completed", conclusion: "skipped" }] }); const orig = io.gh;
132
+ io.gh = async (a) => { const r = await orig(a); if (a[0] === "workflow") w.runs = [{ databaseId: 12, status: "completed", conclusion: "success" }]; return r; };
133
+ const out = await deployStep(mk(io, { fence: fence() }));
134
+ assert.equal(out.live, true); assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 1);
135
+ });
136
+ it("a run cancelled by a newer concurrency-group run is expected: no rerun", async () => {
137
+ const { w, io } = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "429 Too Many Requests" }); const orig = io.gh;
138
+ io.gh = async (a) => (a[0] === "run" && a[1] === "list" && !a.includes("--commit") ? JSON.stringify([{ databaseId: 10, status: "in_progress" }]) : orig(a));
139
+ const out = await deployStep(mk(io));
140
+ assert.match(out.reason, /cancelled by a newer run/); assert.equal(w.reran, undefined);
141
+ });
142
+ it("another cancelled run is checked against live first: a matching live passes, a mismatch may be rerun only when transient", async () => {
143
+ const ok = world({ live: [OLD, SHA], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }] });
144
+ assert.equal((await deployStep(mk(ok.io))).live, true); assert.equal(ok.w.reran, undefined);
145
+ const bad = world({ live: [OLD], runs: [{ databaseId: 9, status: "completed", conclusion: "cancelled" }], log: "the runner received a shutdown signal" });
146
+ const out = await deployStep(mk(bad.io));
147
+ assert.equal(bad.w.reran, 2); assert.match(out.reason, /recovery spent/);
148
+ });
149
+ it("shared INFRA_SIGNATURES count as transient without any configured signature", async () => {
150
+ const { w, io } = world({ live: [OLD, SHA], log: "fatal: ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }, { databaseId: 9, status: "completed", conclusion: "success" }] });
151
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 2, max_attempts: 3 } }));
152
+ assert.equal(out.live, true); assert.equal(w.reran, 1);
153
+ });
154
+ it("a deterministic build failure and a migration failure hold with an owner ask and needs-agent", async () => {
155
+ for (const [log, kind] of [["tsc error TS2304", "deterministic"], ["migration 0042 failed", "migration"]]) {
156
+ const { w, io } = world({ live: [OLD], log, runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
157
+ const out = await deployStep(mk(io));
158
+ assert.equal(out.hold?.kind, kind); assert.equal(out.hold.label, "needs-agent"); assert.match(out.reason, /owner ask/); assert.equal(w.reran, undefined);
159
+ }
160
+ });
161
+ it("max_attempts hands off to the rollback ladder", async () => {
162
+ const { io } = world({ live: [OLD], log: "ECONNRESET", runs: [{ databaseId: 9, status: "completed", conclusion: "failure" }] });
163
+ const out = await deployStep(mk(io, {}, { ...POLICY, recovery: { rerun_max: 5, max_attempts: 1 } }));
164
+ assert.match(out.reason, /rollback ladder/);
165
+ });
166
+ it("unreadable freeze-independent guard: an unreadable live record blocks LIVE_CHECK (I5)", async () => {
167
+ const { io } = world({ live: [OLD, null] });
168
+ const out = await deployStep(mk(io));
169
+ assert.equal(out.blocked, true); assert.match(out.reason, /unreadable/);
170
+ });
171
+ });
172
+
173
+ describe("deploy reconcile (#5560)", () => {
174
+ it("a LIVE_CHECKED phase whose live record moved is re-observed without a dispatch, then re-checked", async () => {
175
+ const { w, io } = world({ live: [OLD] });
176
+ const c = mk(io); c.state.deploy = { phase: "LIVE_CHECKED", attempts: 0, reruns: 0, target: { sha: OLD, images: {} }, expected: null, merge: SHA, freezeBefore: "" };
177
+ const out = await deployStep(c);
178
+ assert.equal(out.blocked, true); assert.match(out.reason, /LIVE_CHECK failed/);
179
+ assert.equal(w.gh.filter((g) => g.startsWith("workflow run")).length, 0);
180
+ });
181
+ });
182
+
183
+ describe("deploy VERIFYING (#5562)", () => {
184
+ it("a configured verify policy gates LIVE: the VERIFIED marker is written and the issue closes only after the layers pass", async () => {
185
+ const { w, io } = world(); const issue = { state: "OPEN", body: "", comments: [] };
186
+ const og = io.gh; io.gh = async (a) => {
187
+ if (a[0] === "issue" && a[1] === "view") return JSON.stringify(issue);
188
+ if (a[0] === "issue" && a[1] === "comment") { issue.comments.push({ body: a[a.indexOf("--body") + 1] }); return ""; }
189
+ if (a[0] === "issue" && a[1] === "close") { issue.state = "CLOSED"; return ""; }
190
+ return og(a);
191
+ };
192
+ const c = mk(io); c.config.verify = { close_requires: "verified" }; c.state.release = { issues: [7] };
193
+ const out = await deployStep(c);
194
+ assert.equal(out.live, true); assert.equal(out.verify.verified, true); assert.equal(issue.state, "CLOSED");
195
+ assert.ok(issue.comments.some((m) => m.body.includes(`FORGE:VERIFIED ${SHA}`)));
196
+ });
197
+ it("a blocked verification keeps the release out of LIVE", async () => {
198
+ const { io } = world(); const c = mk(io); c.config.verify = { results: [{ workflow: "smoke.yml", kind: "smoke" }] };
199
+ const og = io.gh; io.gh = async (a) => (a.includes("smoke.yml") ? "[]" : og(a));
200
+ const out = await deployStep(c);
201
+ assert.equal(out.blocked, true); assert.match(out.reason, /no completed run/); assert.equal(c.state.deploy.phase, "VERIFYING");
202
+ });
203
+ });
204
+
205
+ describe("deploy helpers", () => {
206
+ it("parseLiveRelease reads JSON and a bare sha; liveMatches prefers expected digests", () => {
207
+ assert.deepEqual(parseLiveRelease(`{"sha":"abc1234","images":{"api":"d1"}}`), { sha: "abc1234", images: { api: "d1" } });
208
+ assert.equal(parseLiveRelease("garbage!"), null);
209
+ assert.equal(liveMatches({ sha: "x".repeat(8), images: { api: "d1" } }, SHA, { api: "d1" }), true);
210
+ assert.equal(liveMatches({ sha: SHA, images: { api: "d0" } }, SHA, { api: "d1" }), false);
211
+ });
212
+ it("the policy schema accepts the typed recovery block and rejects a string rerun_max", () => {
213
+ const base = { schema: 1, deploy: { ...POLICY } };
214
+ assert.deepEqual(validatePolicy(base).filter((f) => /deploy\.recovery/.test(f)), []);
215
+ assert.ok(validatePolicy({ ...base, deploy: { ...POLICY, recovery: { rerun_max: "2" } } }).some((f) => /rerun_max/.test(f)));
216
+ });
217
+ });
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Lease-epoch fencing (#5553, epic #5549 Phase 0, invariants I5/I7): every irreversible release action (merge, workflow
5
+ * dispatch, rerun, rollback, flag flip, intake release) re-reads `forge-ledger/_active`, aborts unless the lease is still this
6
+ * driver's epoch, records a write-ahead intent naming the epoch, re-checks immediately before acting, and hands the epoch to
7
+ * the effect so it travels with the action (`Forge-Epoch` merge trailer, `forge_epoch` dispatch input, comment marker).
8
+ * A host that cannot read `_active` performs nothing. Without a fence (unmanaged release) the effect just runs.
9
+ */
10
+ import { readActive } from "./release-ledger.mjs";
11
+ import { holdCheck } from "./release-control.mjs";
12
+
13
+ export const epochTrailer = (epoch) => `Forge-Epoch: ${epoch}`;
14
+ export const epochMarker = (epoch) => `<!-- FORGE:EPOCH ${epoch} -->`;
15
+
16
+ /** @returns {{ok: true, epoch} | {fenced: true, current} | {unreadable: string}} */
17
+ export async function fenceCheck(ctx, lease) {
18
+ let active;
19
+ try { active = await readActive(ctx); } catch (e) { return { unreadable: String(e?.message ?? e) }; }
20
+ if (active?.lease?.holder !== lease.holder || active?.lease?.epoch !== lease.epoch) return { fenced: true, current: active?.epoch ?? null };
21
+ return { ok: true, epoch: lease.epoch };
22
+ }
23
+
24
+ /** fenceCheck, then the hold flag of the lease's release (#5556, I24): `{refused}` or null. */
25
+ async function gate(ctx, lease) {
26
+ const c = await fenceCheck(ctx, lease);
27
+ if (!c.ok) return refusal(c, lease);
28
+ try { const h = await holdCheck(ctx, lease.release); return h ? `refused: ${h}` : null; } catch (e) { return refusal({ unreadable: String(e?.message ?? e) }, lease); }
29
+ }
30
+
31
+ const refusal = (c, lease) => (c.unreadable ? `refused: cannot read _active (${c.unreadable})` : `refused: fenced (epoch ${lease.epoch} is not current, ${c.current ?? "unknown"} is)`);
32
+
33
+ /**
34
+ * Run `effect(epoch)` only while `fence` ({lctx, lease, record, now}) is the current lease. `record` persists the intent before
35
+ * the effect (and its completion after). No fence: `effect(null)`.
36
+ * @returns {{ok: true, value} | {refused: string}} an effect error propagates
37
+ */
38
+ export async function fenced(fence, { action, key }, effect) {
39
+ if (!fence) return { ok: true, value: await effect(null) };
40
+ const { lctx, lease } = fence;
41
+ let why = await gate(lctx, lease);
42
+ if (why) return { refused: why };
43
+ const intent = { key, action, epoch: lease.epoch, holder: lease.holder, at: fence.now() };
44
+ await fence.record(intent);
45
+ why = await gate(lctx, lease); // the window between the first read and the intent write is where a takeover can slip in
46
+ if (why) return { refused: why };
47
+ const value = await effect(lease.epoch);
48
+ await fence.record({ ...intent, done: true });
49
+ return { ok: true, value };
50
+ }
@@ -0,0 +1,105 @@
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 { readFileSync } from "node:fs";
6
+ import { postMergeStep } from "./release-postmerge.mjs";
7
+ import { fenceCheck, fenced, epochTrailer, epochMarker } from "./release-fence.mjs";
8
+
9
+ const mkCtx = (active) => ({ repo: "o/r", credential: "driver", io: { api: async (_m, path) => {
10
+ if (!/contents\/active\.json\?ref=_active$/.test(path)) throw new Error(`unrouted ${path}`);
11
+ if (active.get() instanceof Error) throw active.get();
12
+ return { content: Buffer.from(JSON.stringify(active.get())).toString("base64") };
13
+ } } });
14
+ const cell = (v) => ({ v, get() { return this.v; } });
15
+ const act = (holder, epoch) => ({ epoch, lease: { holder, epoch } });
16
+ const LEASE = { holder: "A", epoch: 1 };
17
+ const mkFence = (active, rec = []) => ({ lctx: mkCtx(active), lease: LEASE, now: () => "t", record: async (r) => { rec.push(r); } });
18
+
19
+ describe("release fence (#5553)", () => {
20
+ it("fenceCheck: ok for the current lease, fenced after a takeover, unreadable when _active cannot be read", async () => {
21
+ const a = cell(act("A", 1)), ctx = mkCtx(a);
22
+ assert.deepEqual(await fenceCheck(ctx, LEASE), { ok: true, epoch: 1 });
23
+ a.v = act("B", 2);
24
+ assert.deepEqual(await fenceCheck(ctx, LEASE), { fenced: true, current: 2 });
25
+ a.v = new Error("HTTP 503");
26
+ assert.match((await fenceCheck(ctx, LEASE)).unreadable, /503/);
27
+ });
28
+
29
+ it("the intent is written before the effect, names the epoch, and the effect receives it", async () => {
30
+ const order = [], a = cell(act("A", 1)), f = mkFence(a);
31
+ f.record = async (r) => { order.push(`record:${r.action}:${r.epoch}:${!!r.done}`); };
32
+ const r = await fenced(f, { action: "merge", key: "k" }, async (e) => { order.push(`effect:${e}`); return "v"; });
33
+ assert.deepEqual(r, { ok: true, value: "v" });
34
+ assert.deepEqual(order, ["record:merge:1:false", "effect:1", "record:merge:1:true"]);
35
+ });
36
+
37
+ it("zombie: after a takeover the effect and the intent are never run", async () => {
38
+ const rec = [], a = cell(act("B", 2));
39
+ let ran = 0;
40
+ const r = await fenced(mkFence(a, rec), { action: "dispatch", key: "k" }, async () => { ran++; });
41
+ assert.match(r.refused, /fenced/);
42
+ assert.equal(ran, 0);
43
+ assert.equal(rec.length, 0);
44
+ });
45
+
46
+ it("a takeover that slips in between the first read and the intent write is caught by the re-check", async () => {
47
+ const a = cell(act("A", 1)), f = mkFence(a);
48
+ f.record = async () => { a.v = act("B", 2); };
49
+ let ran = 0;
50
+ assert.match((await fenced(f, { action: "merge", key: "k" }, async () => { ran++; })).refused, /fenced/);
51
+ assert.equal(ran, 0);
52
+ });
53
+
54
+ it("I5: an unreadable _active performs no irreversible action", async () => {
55
+ let ran = 0;
56
+ const r = await fenced(mkFence(cell(new Error("partition"))), { action: "rerun", key: "k" }, async () => { ran++; });
57
+ assert.match(r.refused, /cannot read _active/);
58
+ assert.equal(ran, 0);
59
+ });
60
+
61
+ it("#5556 I24: a held release performs no irreversible action", async () => {
62
+ let ran = 0;
63
+ const a = cell({ ...act("A", 1), holds: { r1: { reason: "incident" } } });
64
+ const f = mkFence(a); f.lease = { holder: "A", epoch: 1, release: "r1" };
65
+ const r = await fenced(f, { action: "merge", key: "k" }, async () => { ran++; });
66
+ assert.match(r.refused, /held \(incident\)/);
67
+ assert.equal(ran, 0);
68
+ });
69
+
70
+ it("without a fence (unmanaged release) the effect just runs with no epoch", async () => {
71
+ assert.deepEqual(await fenced(null, { action: "merge", key: "k" }, async (e) => e), { ok: true, value: null });
72
+ });
73
+
74
+ it("the epoch carriers", () => {
75
+ assert.equal(epochTrailer(3), "Forge-Epoch: 3");
76
+ assert.equal(epochMarker(3), "<!-- FORGE:EPOCH 3 -->");
77
+ });
78
+
79
+ it("publish.yml accepts forge_epoch and rejects a stale one as its first step", () => {
80
+ const y = readFileSync(new URL("../../.github/workflows/publish.yml", import.meta.url), "utf8");
81
+ assert.match(y, /workflow_dispatch:[^\n]*\n\s+inputs:\n\s+forge_epoch:/);
82
+ assert.match(y, / steps:\n - name: Reject a stale forge_epoch/);
83
+ assert.match(y, /ref=_active/);
84
+ });
85
+
86
+ it("post-merge dispatch carries forge_epoch; a fenced host dispatches nothing", async () => {
87
+ const run = async (active) => {
88
+ const calls = []; let listed = 0;
89
+ const io = { print() {}, sleep: async () => {}, gh: async (a) => {
90
+ calls.push(a);
91
+ if (a[0] === "pr" && a[1] === "view") return JSON.stringify({ state: "MERGED", mergeCommit: { oid: "m".repeat(40) } });
92
+ if (a[0] === "run" && a[1] === "list") return JSON.stringify(++listed <= 2 ? [] : [{ databaseId: 5, status: "completed", conclusion: "success" }]);
93
+ return "";
94
+ } };
95
+ const ctx = { io, repo: "o/r", def: "main", staging: "staging", config: { postMerge: { publishPolls: 2, runPolls: 2 } }, state: { steps: { "release-pr": { result: { pr: 7 } } } }, fence: mkFence(cell(active)) };
96
+ return { out: await postMergeStep(ctx), calls };
97
+ };
98
+ const good = await run(act("A", 1));
99
+ assert.equal(good.out.published, true);
100
+ assert.deepEqual(good.calls.find((a) => a[0] === "workflow").slice(-2), ["-f", "forge_epoch=1"]);
101
+ const zombie = await run(act("B", 2));
102
+ assert.equal(zombie.out.blocked, true);
103
+ assert.equal(zombie.calls.some((a) => a[0] === "workflow"), false);
104
+ });
105
+ });
@@ -0,0 +1,139 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Flake policy for managed releases (#5568, epic #5549 5.5, I15/I20/I29, R2). Pure functions plus `gh`-injected reads; no model call.
5
+ * Flips and infra signatures go to `flakes.json` (on `_active`); an infra flake is rerun once per job inside `ci.rerun_budget_min`;
6
+ * a repeated flake files one `flake` issue, and only then may a test be quarantined (expiring, capped, never an unskippable class).
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { readActive, updateActive } from "./release-ledger.mjs";
10
+
11
+ export const FLAKE_LABEL = "flake";
12
+ export const FLAKE_MARKER = "FORGE:FLAKE";
13
+ export const UNSKIPPABLE_CLASSES = ["migration", "security", "rollback", "backup-restore", "secrets"];
14
+ const DAY_MS = 86_400_000;
15
+ const json = (s) => { try { return JSON.parse(String(s)); } catch { return null; } };
16
+ const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : d; };
17
+
18
+ /** Known infra signatures (artifact upload outage, runner cancel, Postgres init race, apt/network). */
19
+ export const INFRA_SIGNATURES = [
20
+ ["artifact-upload", /artifact.*(upload|storage)|upload-artifact|unable to upload/i],
21
+ ["runner-cancel", /runner.*(lost communication|shutdown|received a shutdown signal)|operation was canceled|the job was canceled/i],
22
+ ["postgres-init", /pg_isready|database system is starting up|connection refused.*5432|postgres.*(not ready|init)/i],
23
+ ["network", /ETIMEDOUT|ECONNRESET|EAI_AGAIN|apt-get.*(failed|unable)|temporary failure in name resolution|could not resolve host|502 bad gateway|503 service unavailable/i],
24
+ ];
25
+
26
+ /** forge.yaml policy -> {rerunBudgetMin, quarantineAfter, windowDays, quarantineDays, quarantineMax, unskippable}. */
27
+ export function parseFlakeConfig(policy) {
28
+ const ci = policy?.ci ?? {}, f = ci.flake ?? {}, q = policy?.quarantine ?? {};
29
+ return {
30
+ rerunBudgetMin: num(ci.rerun_budget_min, 0), quarantineAfter: num(f.quarantine_after, 3), windowDays: num(f.window_days, 14),
31
+ quarantineDays: num(q.days, 14), quarantineMax: num(q.max, 15), unskippable: [...UNSKIPPABLE_CLASSES, ...(Array.isArray(ci.unskippable) ? ci.unskippable : [])],
32
+ };
33
+ }
34
+
35
+ /** True when `check` is, or is under (`class:x`, `class/x`), an unskippable class; the one matcher for exempt and quarantine. */
36
+ export const isUnskippable = (check, classes = UNSKIPPABLE_CLASSES) => classes.some((c) => check === c || check.startsWith(`${c}:`) || check.startsWith(`${c}/`));
37
+
38
+ /** @returns {{class: "infra"|"unknown", signature: string|null}} from failure text (log tail or annotations). */
39
+ export function classifyFailure(text) {
40
+ const hit = INFRA_SIGNATURES.find(([, re]) => re.test(String(text ?? "")));
41
+ return hit ? { class: "infra", signature: hit[0] } : { class: "unknown", signature: null };
42
+ }
43
+ export const signatureHash = (check, test, signature) => createHash("sha256").update([check, test ?? "", signature ?? ""].join("\0")).digest("hex").slice(0, 16);
44
+
45
+ /** Same-SHA flips in `runs` [{sha, check, test?, conclusion, id, at}]: a check that failed and then passed on one sha. */
46
+ export function detectSameShaFlip(runs) {
47
+ const by = new Map();
48
+ for (const r of [...runs].sort((a, b) => Date.parse(a.at) - Date.parse(b.at))) {
49
+ const k = `${r.sha}\0${r.check}\0${r.test ?? ""}`, g = by.get(k) ?? { fail: [], flipped: false, r };
50
+ if (r.conclusion === "failure") g.fail.push(r); else if (r.conclusion === "success" && g.fail.length) g.flipped = true;
51
+ g.runs = [...(g.runs ?? []), r.id]; by.set(k, g);
52
+ }
53
+ return [...by.values()].filter((g) => g.flipped).map((g) => ({ check: g.r.check, test: g.r.test ?? null, sha: g.r.sha, run_ids: g.runs }));
54
+ }
55
+
56
+ /** One `flakes.json` entry. */
57
+ export const flakeEntry = ({ check, test = null, signature = null, kind, sha = null, runIds = [], at, rerun = false }) =>
58
+ ({ check, test, signature, signature_hash: signatureHash(check, test, signature), kind, sha, run_ids: runIds, at, ...(rerun ? { rerun: true } : {}) });
59
+
60
+ /** Append entries to `flakes.json` and the `_active` `flakes` key in one commit. */
61
+ export async function recordFlakes(lctx, entries, now = Date.now()) {
62
+ if (!entries.length) return { ok: true, recorded: 0 };
63
+ const r = await updateActive(lctx, ["flakes"], (a) => {
64
+ const flakes = [...(a.flakes ?? []), ...entries];
65
+ return { patch: { flakes }, files: { "flakes.json": `${JSON.stringify({ updated: new Date(now).toISOString(), flakes }, null, 2)}\n` } };
66
+ });
67
+ return r.ok ? { ok: true, recorded: entries.length } : { ok: false, error: r.refused ?? "lost the race recording flakes" };
68
+ }
69
+
70
+ /**
71
+ * Which failed jobs to `rerun --failed`: infra class only, once per job (`done` = keys of jobs already rerun), and only while the
72
+ * minutes already spent stay inside `ci.rerun_budget_min`. Every job gets a decision, so a skipped rerun is never silent.
73
+ * @param {{jobs: {key, name, class, minutes?}[], done?: Set|string[], spentMin?: number, budgetMin: number}} p
74
+ */
75
+ export function planRerun({ jobs, done = [], spentMin = 0, budgetMin }) {
76
+ const seen = new Set(done);
77
+ let spent = spentMin;
78
+ return jobs.map((j) => {
79
+ if (j.class !== "infra") return { ...j, rerun: false, why: "not an infra flake" };
80
+ if (seen.has(j.key)) return { ...j, rerun: false, why: "already rerun once" };
81
+ const cost = j.minutes ?? 0;
82
+ if (!(budgetMin > 0) || spent + cost > budgetMin) return { ...j, rerun: false, why: `ci.rerun_budget_min ${budgetMin} exhausted (${spent} spent)` };
83
+ spent += cost; seen.add(j.key);
84
+ return { ...j, rerun: true, why: "infra flake, first rerun" };
85
+ });
86
+ }
87
+
88
+ const targetOf = (f) => f.test ? `${f.check}:${f.test}` : f.check;
89
+
90
+ /** Targets with >= quarantine_after flips inside window_days: [{target, check, test, count, evidence}]. Infra reruns do not count as flips. */
91
+ export function repeatedFlakes(flakes, cfg, now = Date.now()) {
92
+ const groups = new Map();
93
+ for (const f of flakes ?? []) {
94
+ if (f.kind !== "flip" && f.kind !== "test") continue;
95
+ if (now - Date.parse(f.at) > cfg.windowDays * DAY_MS) continue;
96
+ const g = groups.get(targetOf(f)) ?? { target: targetOf(f), check: f.check, test: f.test ?? null, count: 0, evidence: [] };
97
+ g.count++; g.evidence.push(...(f.run_ids ?? [])); groups.set(g.target, g);
98
+ }
99
+ return [...groups.values()].filter((g) => g.count >= cfg.quarantineAfter);
100
+ }
101
+
102
+ const markerFor = (target) => `<!-- ${FLAKE_MARKER} target=${target} -->`;
103
+
104
+ /** The open `flake` issue of `target`, else a new one (label `flake`, evidence). @returns {{issue, created}|null} null for an unskippable target. */
105
+ export async function fileFlakeIssue({ gh, repo, target, evidence = [], count = 0, owner = null, cfg }) {
106
+ if (isUnskippable(target, cfg?.unskippable)) return null;
107
+ const mark = markerFor(target);
108
+ const open = json(await gh(["issue", "list", "--repo", repo, "--label", FLAKE_LABEL, "--state", "open", "--json", "number,body", "--limit", "100"])) ?? [];
109
+ const found = open.find((i) => String(i.body ?? "").includes(mark));
110
+ if (found) return { issue: found.number, created: false };
111
+ const body = `${mark}\nRepeated flake: \`${target}\` flipped ${count} time(s) inside the window.${owner ? `\nOwner: ${owner}` : ""}\nRuns: ${evidence.join(", ") || "none"}\n`;
112
+ const url = String(await gh(["issue", "create", "--repo", repo, "--label", FLAKE_LABEL, "--title", `flake: ${target} is flaky`, "--body", body])).trim();
113
+ return { issue: Number(/(\d+)$/.exec(url)?.[1]) || null, created: true };
114
+ }
115
+
116
+ /** An exemption is live until `until`; a quarantine also lapses `quarantine.days` after it was recorded (fail closed: blocking again). */
117
+ export function isLive(e, cfg, now = Date.now()) {
118
+ if (!e || !(Date.parse(e.until) > now)) return false;
119
+ return e.mode !== "quarantine" || now - Date.parse(e.at) <= cfg.quarantineDays * DAY_MS;
120
+ }
121
+ export const activeQuarantines = (exemptions, cfg, now = Date.now()) => Object.entries(exemptions ?? {}).filter(([, e]) => e?.mode === "quarantine" && isLive(e, cfg, now)).map(([k]) => k);
122
+
123
+ /**
124
+ * May `target` be quarantined? Refused for an unskippable class, without an existing open `flake` issue, or at the cap.
125
+ * @returns {{ok: true} | {ok: false, why: string}}
126
+ */
127
+ export function canQuarantine({ target, exemptions, issueLabels = [], issueOpen = true, cfg, now = Date.now() }) {
128
+ if (isUnskippable(target, cfg.unskippable)) return { ok: false, why: `${target} is an unskippable class and can never be quarantined` };
129
+ if (!issueOpen || !issueLabels.includes(FLAKE_LABEL)) return { ok: false, why: `quarantine needs an open issue labelled ${FLAKE_LABEL} (file it first)` };
130
+ const live = activeQuarantines(exemptions, cfg, now);
131
+ if (live.length >= cfg.quarantineMax && !live.includes(target)) return { ok: false, why: `quarantine cap ${cfg.quarantineMax} reached` };
132
+ return { ok: true };
133
+ }
134
+
135
+ /** I29: a run that needed an in-runner retry or a rerun (a `FLAKE:` annotation) never writes a cache marker. */
136
+ export const shouldWriteMarker = ({ retried = false, flakeAnnotated = false, rerun = false, passed = true } = {}) => passed && !retried && !flakeAnnotated && !rerun;
137
+
138
+ /** Live flakes ledger from `_active` (empty when unreadable). */
139
+ export async function readFlakes(lctx) { try { return (await readActive(lctx)).flakes ?? []; } catch { return []; } }
@@ -0,0 +1,116 @@
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 { parseFlakeConfig, classifyFailure, detectSameShaFlip, flakeEntry, planRerun, repeatedFlakes, fileFlakeIssue, canQuarantine, activeQuarantines, shouldWriteMarker, isUnskippable, recordFlakes, UNSKIPPABLE_CLASSES } from "./release-flakes.mjs";
6
+ import { rerunInfraFlakes } from "./release.mjs";
7
+
8
+ const NOW = Date.parse("2026-11-12T00:00:00Z"), DAY = 86_400_000;
9
+ const cfg = parseFlakeConfig({ ci: { rerun_budget_min: 30 } });
10
+
11
+ describe("release flakes (#5568)", () => {
12
+ it("defaults and overrides", () => {
13
+ assert.deepEqual([cfg.quarantineAfter, cfg.windowDays, cfg.quarantineDays, cfg.quarantineMax], [3, 14, 14, 15]);
14
+ assert.equal(parseFlakeConfig({ quarantine: { days: 7, max: 2 }, ci: { unskippable: ["x"] } }).unskippable.includes("x"), true);
15
+ });
16
+
17
+ it("records a same-SHA fail-then-pass flip but not a plain failure or a different sha", () => {
18
+ const r = (sha, conclusion, id, at) => ({ sha, check: "unit", conclusion, id, at });
19
+ const flips = detectSameShaFlip([r("a", "failure", 1, "2026-11-01T00:00:00Z"), r("a", "success", 2, "2026-11-01T01:00:00Z"), r("b", "failure", 3, "2026-11-02T00:00:00Z"), r("c", "failure", 4, "2026-11-02T00:00:00Z"), r("d", "success", 5, "2026-11-02T00:00:00Z")]);
20
+ assert.deepEqual(flips, [{ check: "unit", test: null, sha: "a", run_ids: [1, 2] }]);
21
+ });
22
+
23
+ it("infra signatures are classified and hashed stably", () => {
24
+ assert.deepEqual(classifyFailure("Error: pg_isready: no response"), { class: "infra", signature: "postgres-init" });
25
+ assert.equal(classifyFailure("Unable to upload artifact").class, "infra");
26
+ assert.equal(classifyFailure("AssertionError: 1 !== 2").class, "unknown");
27
+ assert.equal(flakeEntry({ check: "c", signature: "s", kind: "infra", at: "t" }).signature_hash, flakeEntry({ check: "c", signature: "s", kind: "infra", at: "u" }).signature_hash);
28
+ });
29
+
30
+ it("rerun: once per job, infra only, inside the budget, every job decided", () => {
31
+ const jobs = [{ key: "a", class: "infra", minutes: 10 }, { key: "b", class: "unknown" }, { key: "c", class: "infra", minutes: 10 }, { key: "d", class: "infra", minutes: 50 }];
32
+ const p = planRerun({ jobs, done: ["c"], spentMin: 5, budgetMin: 30 });
33
+ assert.deepEqual(p.map((d) => d.rerun), [true, false, false, false]);
34
+ assert.match(p[3].why, /rerun_budget_min/); assert.match(p[2].why, /once/);
35
+ assert.equal(planRerun({ jobs: [jobs[0]], budgetMin: 0 })[0].rerun, false);
36
+ });
37
+
38
+ it("repeated flakes inside the window file one flake issue (deduped)", async () => {
39
+ const at = (d) => new Date(NOW - d * DAY).toISOString();
40
+ const fl = [1, 2, 3].map((d) => flakeEntry({ check: "e2e", test: "t1", kind: "flip", at: at(d), runIds: [d] })).concat(flakeEntry({ check: "e2e", test: "old", kind: "flip", at: at(40) }));
41
+ const rep = repeatedFlakes(fl, cfg, NOW);
42
+ assert.equal(rep.length, 1); assert.equal(rep[0].target, "e2e:t1");
43
+ const issues = []; const calls = [];
44
+ const gh = async (a) => { calls.push(a); if (a[1] === "list") return JSON.stringify(issues); issues.push({ number: 7, body: a[a.indexOf("--body") + 1] }); return "https://github.com/o/r/issues/7"; };
45
+ const first = await fileFlakeIssue({ gh, repo: "o/r", ...rep[0], cfg });
46
+ assert.deepEqual(first, { issue: 7, created: true }); assert.ok(calls.at(-1).includes("flake"));
47
+ assert.deepEqual(await fileFlakeIssue({ gh, repo: "o/r", ...rep[0], cfg }), { issue: 7, created: false });
48
+ assert.equal(await fileFlakeIssue({ gh, repo: "o/r", target: "migration:x", cfg }), null);
49
+ });
50
+
51
+ it("quarantine needs the flake issue, respects the cap and never takes unskippable classes", () => {
52
+ const base = { target: "e2e:t1", exemptions: {}, issueLabels: ["flake"], cfg, now: NOW };
53
+ assert.equal(canQuarantine(base).ok, true);
54
+ assert.match(canQuarantine({ ...base, issueLabels: [] }).why, /flake/);
55
+ assert.equal(canQuarantine({ ...base, issueOpen: false }).ok, false);
56
+ for (const c of UNSKIPPABLE_CLASSES) assert.equal(canQuarantine({ ...base, target: `${c}:x` }).ok, false, c);
57
+ const live = (i) => [`t${i}`, { mode: "quarantine", at: new Date(NOW - DAY).toISOString(), until: new Date(NOW + DAY).toISOString() }];
58
+ const full = Object.fromEntries(Array.from({ length: 15 }, (_, i) => live(i)));
59
+ assert.match(canQuarantine({ ...base, exemptions: full }).why, /cap 15/);
60
+ assert.equal(canQuarantine({ ...base, target: "t3", exemptions: full }).ok, true);
61
+ assert.equal(isUnskippable("migration"), true);
62
+ });
63
+
64
+ it("a quarantine is blocking again at its 14 day expiry, or at `until`", () => {
65
+ const q = (ageD, untilD) => ({ x: { mode: "quarantine", at: new Date(NOW - ageD * DAY).toISOString(), until: new Date(NOW + untilD * DAY).toISOString() } });
66
+ assert.deepEqual(activeQuarantines(q(1, 5), cfg, NOW), ["x"]);
67
+ assert.deepEqual(activeQuarantines(q(15, 5), cfg, NOW), []);
68
+ assert.deepEqual(activeQuarantines(q(1, -1), cfg, NOW), []);
69
+ });
70
+
71
+ it("a retry-pass run writes no cache marker (I29)", () => {
72
+ assert.equal(shouldWriteMarker({ passed: true }), true);
73
+ for (const k of ["retried", "flakeAnnotated", "rerun"]) assert.equal(shouldWriteMarker({ passed: true, [k]: true }), false, k);
74
+ assert.equal(shouldWriteMarker({ passed: false }), false);
75
+ });
76
+
77
+ it("recordFlakes commits flakes.json with active.json", async () => {
78
+ const files = {};
79
+ const io = { api: async (m, p, b) => {
80
+ if (m === "GET" && /git\/ref\/heads/.test(p)) return { object: { sha: "h" } };
81
+ if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from("{}").toString("base64") };
82
+ if (m === "GET") return { tree: { sha: "t" } };
83
+ if (/git\/trees/.test(p)) { for (const t of b.tree) files[t.path] = t.content; return { sha: "t1" }; }
84
+ return { sha: "c1" };
85
+ } };
86
+ const r = await recordFlakes({ io, repo: "o/r", credential: "driver" }, [flakeEntry({ check: "c", kind: "infra", at: "t" })]);
87
+ assert.equal(r.ok, true);
88
+ assert.equal(JSON.parse(files["flakes.json"]).flakes.length, 1); assert.ok(files["active.json"]);
89
+ });
90
+
91
+ it("rerunInfraFlakes reruns an infra-failed run once, skips a real failure, records the flake", async () => {
92
+ const calls = [], files = {};
93
+ const logs = { 1: "Unable to upload artifact", 2: "AssertionError" };
94
+ const active = { epoch: 1, lease: { holder: "A", epoch: 1, release: "r1" } };
95
+ const api = async (m, p, b) => {
96
+ if (m === "GET" && /git\/ref\/heads/.test(p)) return { object: { sha: "h" } };
97
+ if (m === "GET" && /contents\/active\.json/.test(p)) return { content: Buffer.from(JSON.stringify(active)).toString("base64") };
98
+ if (m === "GET") return { tree: { sha: "t" } };
99
+ if (/git\/trees/.test(p)) { for (const t of b.tree) files[t.path] = t.content; return { sha: "t1" }; }
100
+ return { sha: "c1" };
101
+ };
102
+ const io = { now: () => NOW, api, gh: async (a) => {
103
+ calls.push(a);
104
+ if (a[1] === "list") return JSON.stringify([{ databaseId: 1, name: "unit" }, { databaseId: 2, name: "lint" }]);
105
+ if (a[1] === "view") return logs[a[2]];
106
+ return "";
107
+ } };
108
+ const fence = { lctx: { io, repo: "o/r", credential: "driver" }, lease: { holder: "A", epoch: 1, release: "r1" }, record: async () => {}, now: () => "t" };
109
+ const r = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: { ci: { rerun_budget_min: 30 } } });
110
+ assert.deepEqual(r.reran, ["unit"]); assert.equal(r.skipped[0].name, "lint");
111
+ assert.deepEqual(calls.filter((c) => c[1] === "rerun"), [["run", "rerun", "1", "--repo", "o/r", "--failed"]]);
112
+ assert.equal(JSON.parse(files["flakes.json"]).flakes[0].signature, "artifact-upload");
113
+ const none = await rerunInfraFlakes({ io, repo: "o/r", head: "abc", fence, policy: {} });
114
+ assert.deepEqual(none, { reran: [], skipped: [] }); // no ci.rerun_budget_min: no rerun
115
+ });
116
+ });