forgedock 1.66.0 → 1.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/bin/config-schema.mjs +2 -0
  2. package/bin/engine/outcome-codes.mjs +1 -0
  3. package/bin/engine-cli.mjs +96 -17
  4. package/bin/forgedock.mjs +7 -0
  5. package/bin/help-text.mjs +3 -3
  6. package/bin/introspect-schedule.mjs +98 -0
  7. package/bin/introspect-schedule.test.mjs +67 -0
  8. package/bin/lean/advisory.test.mjs +49 -0
  9. package/bin/lean/amendment-schema.mjs +31 -0
  10. package/bin/lean/attempts.mjs +159 -0
  11. package/bin/lean/attempts.test.mjs +127 -0
  12. package/bin/lean/basered.mjs +55 -0
  13. package/bin/lean/basered.test.mjs +68 -1
  14. package/bin/lean/batch-health.mjs +3 -0
  15. package/bin/lean/batch-health.test.mjs +16 -0
  16. package/bin/lean/batch.mjs +45 -0
  17. package/bin/lean/batch.test.mjs +54 -3
  18. package/bin/lean/capwait.mjs +14 -3
  19. package/bin/lean/capwait.test.mjs +20 -0
  20. package/bin/lean/clear-breaker.mjs +14 -0
  21. package/bin/lean/commentstate.mjs +41 -0
  22. package/bin/lean/commentstate.test.mjs +32 -0
  23. package/bin/lean/concurrency.mjs +89 -0
  24. package/bin/lean/concurrency.test.mjs +113 -0
  25. package/bin/lean/conformance.e2e.test.mjs +4 -2
  26. package/bin/lean/conformance.mjs +35 -3
  27. package/bin/lean/conformance.test.mjs +52 -0
  28. package/bin/lean/efficiency.mjs +162 -0
  29. package/bin/lean/efficiency.test.mjs +79 -0
  30. package/bin/lean/execution.mjs +31 -13
  31. package/bin/lean/execution.test.mjs +46 -0
  32. package/bin/lean/failure-stop.mjs +46 -0
  33. package/bin/lean/failure-stop.test.mjs +45 -0
  34. package/bin/lean/fixtures/capacity-storm.json +609 -0
  35. package/bin/lean/lean.mjs +123 -24
  36. package/bin/lean/lean.test.mjs +137 -46
  37. package/bin/lean/liveness.mjs +37 -0
  38. package/bin/lean/liveness.test.mjs +33 -0
  39. package/bin/lean/orchestrate-attempts.test.mjs +74 -0
  40. package/bin/lean/orchestrate-pause.test.mjs +23 -0
  41. package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
  42. package/bin/lean/orchestrate.mjs +170 -26
  43. package/bin/lean/phaseledger.mjs +6 -0
  44. package/bin/lean/phaseledger.test.mjs +13 -1
  45. package/bin/lean/prompts.mjs +6 -10
  46. package/bin/lean/reconcile.mjs +90 -0
  47. package/bin/lean/recurrence.mjs +38 -2
  48. package/bin/lean/recurrence.test.mjs +56 -1
  49. package/bin/lean/sandbox-remote.mjs +33 -2
  50. package/bin/lean/sched.mjs +19 -0
  51. package/bin/lean/sched.test.mjs +11 -1
  52. package/bin/lean/schedd-health.mjs +4 -4
  53. package/bin/lean/schedd-health.test.mjs +8 -4
  54. package/bin/lean/schedd.mjs +34 -2
  55. package/bin/lean/schedd.test.mjs +55 -2
  56. package/bin/lean/slo.mjs +126 -0
  57. package/bin/lean/slo.test.mjs +112 -0
  58. package/bin/lean/statuscomment.mjs +37 -0
  59. package/bin/lean/statuscomment.test.mjs +48 -1
  60. package/bin/lean/verify.mjs +2 -1
  61. package/bin/pool/agent.mjs +2 -2
  62. package/bin/pool/cli.mjs +16 -1
  63. package/bin/pool/lane-tools.mjs +21 -0
  64. package/bin/stats/attempts.mjs +54 -0
  65. package/bin/stats/attempts.test.mjs +30 -0
  66. package/bin/stats/churn.mjs +49 -0
  67. package/bin/stats/churn.test.mjs +31 -0
  68. package/bin/stats/index.mjs +11 -3
  69. package/commands/orchestrate.md +21 -18
  70. package/docs/OUTCOME-CODES.md +1 -0
  71. package/package.json +1 -1
  72. package/scripts/check-devdocs-freshness.sh +1 -1
@@ -0,0 +1,162 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * Batch efficiency ledger (#5987): a pure fold of a batch's `log.jsonl` rows, its state and the schedd's pool samples into a
5
+ * versioned `efficiency.json` (schema in devdocs/modules/lean.md). The failure/stall gates (batch-health.mjs) say a batch is broken;
6
+ * this says it is slow: achieved vs ceiling concurrency, idle slot-minutes by cause, attempts per merge, engine comments per
7
+ * issue, repeated failure signatures, operator interventions, phase p50/p90 vs a baseline, merged/hour, wasted lane-hours, $ per merge.
8
+ *
9
+ * Row fields read are the ones the orchestrator's `update(row)` writes to log.jsonl (all optional): `at`, `issue`, `outcome` (a terminal
10
+ * lane row; `merged` is a good end; `added`, `breaker`, `deferred` are engine/operator notes), `code`, `detail`, `minutes`, `cost_usd`,
11
+ * `phases:{id:{ms}}`. "Engine comments per issue" = the status updates (rows with a `detail`) the engine emitted for the issue.
12
+ * Operator interventions = `--add` rows, `run.interrupted` rows (schedd restart), FORGE:DECISION text in a `detail`, plus `operator`
13
+ * events the caller reads from the batch files (`requeue`, `hold-info`, `parallel`, see `operatorEvents`). Samples `{t, running, ceiling, ready, cause?}` are pushed by the daemon each pass and persisted in the file.
14
+ */
15
+ import { existsSync, readFileSync, statSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { writeAtomic } from "./batch.mjs";
18
+
19
+ export const EFFICIENCY_FILE = "efficiency.json";
20
+ export const EFFICIENCY_VERSION = 1;
21
+ export const IDLE_CAUSES = ["capacity", "lease-held", "base.red", "hold", "breaker", "auth-pause", "no-ready"];
22
+ const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
23
+ /** Rows that are progress notes, not the end of a run; never counted as a failed attempt. */
24
+ const NOTE_OUTCOME = new Set(["recovering", "added", "breaker", "planned", "plan-failed", "pool-offline", "host-overloaded", "sched", "integration", "drift", "budget"]);
25
+ const OPERATOR_ROW = (r) => r.outcome === "added" || r.code === "run.interrupted" || /FORGE:DECISION/.test(String(r.detail ?? ""));
26
+ const num = (v) => (Number.isFinite(Number(v)) && v !== null && v !== "" ? Number(v) : null);
27
+ const round = (v, d = 2) => (v === null || !Number.isFinite(v) ? null : Math.round(v * 10 ** d) / 10 ** d);
28
+ const atMs = (r) => { const t = Date.parse(r?.at ?? ""); return Number.isFinite(t) ? t : null; };
29
+
30
+ export function percentile(sorted, p) {
31
+ if (!sorted.length) return null;
32
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
33
+ }
34
+
35
+ /** Phase durations (ms) by phase id over `rows`. */
36
+ export function phaseSpans(rows) {
37
+ const by = {};
38
+ for (const r of rows) for (const [id, v] of Object.entries(r?.phases ?? {})) { const ms = num(v?.ms); if (ms !== null && ms >= 0) (by[id] ??= []).push(ms); }
39
+ const out = {};
40
+ for (const [id, xs] of Object.entries(by)) { xs.sort((a, b) => a - b); out[id] = { n: xs.length, p50: percentile(xs, 0.5), p90: percentile(xs, 0.9) }; }
41
+ return out;
42
+ }
43
+
44
+ const runMinutes = (r) => num(r.minutes) ?? (Object.entries(r.phases ?? {}).reduce((s, [id, v]) => (id === "queue_wait" ? s : s + (num(v?.ms) ?? 0)), 0) / MIN);
45
+
46
+ /** Time-weighted `{achieved, ceiling, ratio}` over the samples since `since`; each sample holds until the next one (or `now`). */
47
+ export function concurrencyOver(samples, since, now) {
48
+ let dt = 0, run = 0, cap = 0;
49
+ samples.forEach((s, i) => {
50
+ const from = Math.max(s.t, since), to = Math.min(samples[i + 1]?.t ?? now, now);
51
+ if (to <= from) return;
52
+ dt += to - from; run += (num(s.running) ?? 0) * (to - from); cap += (num(s.ceiling) ?? 0) * (to - from);
53
+ });
54
+ return dt ? { achieved: round(run / dt), ceiling: round(cap / dt), ratio: cap ? round(run / cap, 3) : null } : { achieved: null, ceiling: null, ratio: null };
55
+ }
56
+
57
+ /**
58
+ * Compute the ledger. `prev`: the prior efficiency.json (carries samples and SLO filing state), `sample`: this pass's pool sample,
59
+ * `baseline`: `{phase: {p90}}` over the previous 14 days (default: this log's rows from the 14 days before the last 24 h), `concurrencyMin`: threshold used
60
+ * for `lowSinceMin`. Pure; never throws on malformed rows.
61
+ */
62
+ export function computeEfficiency({ rows = [], state = null, prev = null, sample = null, now = Date.now(), batchId = null, repo = null, operator = [], baseline = null, concurrencyMin = 0.6, windowMin = 15 } = {}) {
63
+ const list = (Array.isArray(rows) ? rows : []).filter((r) => r && typeof r === "object");
64
+ const samples = [...(Array.isArray(prev?.samples) ? prev.samples : []), ...(sample ? [{ ...sample, t: sample.t ?? now }] : [])]
65
+ .filter((s) => Number.isFinite(s?.t) && s.t > now - DAY).slice(-1500);
66
+ const day = list.filter((r) => (atMs(r) ?? now) > now - DAY);
67
+ const terminal = day.filter((r) => r.outcome && r.issue != null && !NOTE_OUTCOME.has(r.outcome));
68
+ const merged = new Set(terminal.filter((r) => r.outcome === "merged").map((r) => r.issue));
69
+ for (const [n, v] of Object.entries(state?.results ?? {})) if (v?.outcome === "merged") merged.add(Number(n));
70
+ const mergedNow = new Set([...merged].filter((n) => terminal.some((r) => r.issue === n && r.outcome === "merged")));
71
+
72
+ // concurrency and idle slot-minutes by cause (24 h)
73
+ const conc = concurrencyOver(samples, now - windowMin * MIN, now);
74
+ const ready = num(samples.at(-1)?.ready) ?? (Array.isArray(state?.pending) ? state.pending.length : 0);
75
+ let lowSince = null;
76
+ for (let i = samples.length - 1; i >= 0; i--) { const s = samples[i]; if (!(num(s.ready) > 0) || !(num(s.ceiling) > 0) || num(s.running) / num(s.ceiling) >= concurrencyMin) break; lowSince = s.t; }
77
+ const idle = {}; let slot = 0;
78
+ samples.forEach((s, i) => {
79
+ const to = Math.min(samples[i + 1]?.t ?? now, now), dt = (to - s.t) / MIN;
80
+ if (dt <= 0) return;
81
+ const cap = num(s.ceiling) ?? 0, run = num(s.running) ?? 0;
82
+ slot += cap * dt;
83
+ if (cap > run) { const c = s.cause ?? (num(s.ready) > 0 ? "capacity" : "no-ready"); idle[c] = (idle[c] ?? 0) + (cap - run) * dt; }
84
+ });
85
+ const idleByCause = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, round(m, 1)]));
86
+ const idleShare = Object.fromEntries(Object.entries(idle).map(([c, m]) => [c, slot ? round(m / slot, 3) : 0]));
87
+
88
+ // attempts, comments, signatures, interventions
89
+ const attempts = terminal.filter((r) => mergedNow.has(r.issue)).length;
90
+ const comments = {};
91
+ for (const r of day) if (r.issue != null) { if (typeof r.detail === "string" && r.detail) comments[r.issue] = (comments[r.issue] ?? 0) + 1; }
92
+ const sigs = {};
93
+ for (const r of terminal) if (r.outcome !== "merged") { const sig = String(r.signature ?? `${r.outcome}:${r.code ?? r.reason ?? r.error ?? ""}`).slice(0, 160); (sigs[sig] ??= new Set()).add(r.issue); (sigs[sig].n = (sigs[sig].n ?? 0) + 1); }
94
+ const repeats = Object.entries(sigs).map(([signature, s]) => ({ signature, count: s.n, issues: [...s].sort((a, b) => a - b) })).sort((a, b) => b.count - a.count);
95
+ const opAt = (e) => (typeof e?.at === "number" ? e.at : Date.parse(e?.at ?? ""));
96
+ const interventions = day.filter(OPERATOR_ROW).length + (Array.isArray(operator) ? operator : []).filter((e) => opAt(e) > now - DAY && opAt(e) <= now).length;
97
+ const capacityRefusals = list.filter((r) => (atMs(r) ?? 0) > now - HOUR && /capacity/.test(String(r.code ?? ""))).length;
98
+
99
+ // phases vs baseline
100
+ const cur = phaseSpans(day);
101
+ const base = baseline ?? Object.fromEntries(Object.entries(phaseSpans(list.filter((r) => { const t = atMs(r) ?? now; return t <= now - DAY && t > now - 15 * DAY; }))).map(([id, v]) => [id, { p90: v.p90 }]));
102
+ const phases = Object.fromEntries(Object.entries(cur).map(([id, v]) => [id, { ...v, baselineP90: base[id]?.p90 ?? null, ratio: base[id]?.p90 ? round(v.p90 / base[id].p90) : null }]));
103
+
104
+ // merged/hour, wasted lane-hours, $ per merge
105
+ const spanH = Math.max(1, Math.min(24, (now - Math.min(now, ...day.map((r) => atMs(r) ?? now))) / HOUR));
106
+ let wastedLater = 0, wastedNever = 0, usd = 0;
107
+ for (const r of terminal) {
108
+ usd += num(r.cost_usd) ?? 0;
109
+ if (r.outcome === "merged") continue;
110
+ (merged.has(r.issue) ? (wastedLater += runMinutes(r)) : (wastedNever += runMinutes(r)));
111
+ }
112
+ const running = state?.running && typeof state.running === "object" ? Object.keys(state.running).length : null;
113
+ return {
114
+ v: EFFICIENCY_VERSION, at: new Date(now).toISOString(), batch: batchId, repo,
115
+ concurrency: { ...conc, windowMin, running, ready, lowSinceMin: lowSince === null ? 0 : round((now - lowSince) / MIN, 1), min: concurrencyMin },
116
+ idle: { slotMinutes: round(slot, 1), byCause: idleByCause, share: idleShare },
117
+ limiters: Object.entries(idleByCause).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([c]) => c),
118
+ attemptsPerMerged: mergedNow.size ? round(attempts / mergedNow.size) : null, merged: mergedNow.size,
119
+ commentsPerIssue: { max: Math.max(0, ...Object.values(comments)), issues: Object.entries(comments).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([n, c]) => ({ issue: Number(n), comments: c })) },
120
+ repeats: repeats.slice(0, 10), interventionsPerDay: interventions, capacityRefusalsPerHour: capacityRefusals,
121
+ phases, mergedPerHour: round(mergedNow.size / spanH),
122
+ wastedLaneHours: { laterMerged: round(wastedLater / 60), neverMerged: round(wastedNever / 60) },
123
+ usdPerMerge: mergedNow.size ? round(usd / mergedNow.size) : null,
124
+ samples, slo: prev?.slo ?? { sigs: {} }, breaches: prev?.breaches ?? [],
125
+ };
126
+ }
127
+
128
+ /** Idle cause of the pool right now, from the batch's recent log rows (last 10 min); undefined when none applies (capacity/no-ready are inferred from `ready`). */
129
+ export function idleCause(rows, now = Date.now()) {
130
+ const recent = (Array.isArray(rows) ? rows : []).filter((r) => r && (atMs(r) ?? 0) > now - 10 * MIN).reverse();
131
+ const brk = recent.find((r) => r.outcome === "breaker");
132
+ if (brk && !/cleared/.test(String(brk.detail ?? ""))) return "breaker";
133
+ for (const r of recent) {
134
+ const d = String(r.detail ?? "");
135
+ if (/base\.red|base is red/.test(`${r.code ?? ""} ${d}`)) return "base.red";
136
+ if (r.outcome === "deferred" && /live lane in batch/.test(d)) return "lease-held";
137
+ if (/capacity/.test(String(r.code ?? ""))) return "capacity";
138
+ }
139
+ return undefined;
140
+ }
141
+
142
+ /** Operator actions recorded in a batch dir's files: `requeue` entries, `hold-info` (non-engine owners), the `parallel` file (`--set-parallel`). `[{at, kind}]`. */
143
+ export function operatorEvents(dir) {
144
+ const out = [], j = (n) => { try { return JSON.parse(readFileSync(join(dir, n), "utf8")); } catch { return null; } };
145
+ for (const e of Array.isArray(j("requeue")) ? j("requeue") : []) if (typeof e?.at === "string") out.push({ at: Date.parse(e.at), kind: "requeue" });
146
+ for (const e of Object.values(j("hold-info") ?? {})) if (e && e.owner !== "engine" && typeof e.since === "string") out.push({ at: Date.parse(e.since), kind: "hold" });
147
+ try { out.push({ at: statSync(join(dir, "parallel")).mtimeMs, kind: "set" }); } catch { /* none */ }
148
+ return out.filter((e) => Number.isFinite(e.at));
149
+ }
150
+
151
+ export const readEfficiency = (dir) => { try { const v = JSON.parse(readFileSync(join(dir, EFFICIENCY_FILE), "utf8")); return v && v.v === EFFICIENCY_VERSION ? v : null; } catch { return null; } };
152
+ export const writeEfficiency = (dir, eff) => writeAtomic(join(dir, EFFICIENCY_FILE), JSON.stringify(eff) + "\n", { private: true });
153
+ export const hasEfficiency = (dir) => existsSync(join(dir, EFFICIENCY_FILE));
154
+
155
+ /** The `forgedock status` line: `efficiency: 3/12 lanes (25%) - limiter a b; 2 SLO breaches -> FD#NNNN`. null with no ledger. */
156
+ export function efficiencyLine(eff) {
157
+ const c = eff?.concurrency;
158
+ if (!c || c.running == null && c.achieved == null) return null;
159
+ const run = c.running ?? Math.round(c.achieved), cap = Math.round(c.ceiling ?? 0), pct = cap ? Math.round((run / cap) * 100) : 0;
160
+ const n = (eff.breaches ?? []).length, issues = [...new Set((eff.breaches ?? []).map((b) => b.issue).filter(Boolean))];
161
+ return `efficiency: ${run}/${cap} lanes (${pct}%)${eff.limiters?.length ? ` - limiter ${eff.limiters.join(" ")}` : ""}${n ? `; ${n} SLO breach${n === 1 ? "" : "es"}${issues.length ? ` -> ${issues.map((i) => `FD#${i}`).join(" ")}` : ""}` : ""}`;
162
+ }
@@ -0,0 +1,79 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ import { describe, it } from "node:test";
4
+ import assert from "node:assert/strict";
5
+ import { computeEfficiency, efficiencyLine, concurrencyOver, idleCause, operatorEvents } from "./efficiency.mjs";
6
+ import { tmpDir } from "../tests/_tmp.mjs";
7
+ import { evaluateSlo, DEFAULT_SLO } from "./slo.mjs";
8
+
9
+ const NOW = Date.parse("2026-11-24T12:00:00Z"), MIN = 60000;
10
+ const iso = (agoMin) => new Date(NOW - agoMin * MIN).toISOString();
11
+ const row = (agoMin, r) => ({ at: iso(agoMin), ...r });
12
+ const samples = (n, running, ceiling, ready) => Array.from({ length: n }, (_, i) => ({ t: NOW - (n - i) * MIN, running, ceiling, ready }));
13
+
14
+ // 11-20..11-24 batches: 3 of 12 lanes busy, one failure signature retried, retries before the merges, operator churn.
15
+ export const slowRows = () => [
16
+ ...[1, 2, 3, 4].map((i) => row(300 - i, { issue: 7, outcome: "engine-error", code: "sandbox.capacity", minutes: 30, phases: { setup: { ms: 600000 } } })),
17
+ row(200, { issue: 7, outcome: "merged", minutes: 20, cost_usd: 4 }),
18
+ row(190, { issue: 8, outcome: "ci-failed", minutes: 10 }), row(180, { issue: 8, outcome: "merged", minutes: 10, cost_usd: 2 }),
19
+ row(110, { issue: null, outcome: "added", detail: "9" }), row(105, { issue: 9, outcome: "deferred", code: "run.interrupted", detail: "interrupted: upgrade; requeued" }),
20
+ ...Array.from({ length: 22 }, (_, i) => row(90 - i, { issue: 9, outcome: "recovering", detail: `recovering (ci), attempt ${i}/30` })),
21
+ ];
22
+ // operator actions the daemon reads from the batch files (requeue entries, hold-info, parallel file)
23
+ export const slowOperator = () => Array.from({ length: 5 }, (_, i) => ({ at: NOW - (100 - i) * MIN, kind: i % 2 ? "requeue" : "hold" }));
24
+ export const healthyRows = () => [row(60, { issue: 1, outcome: "merged", minutes: 20, cost_usd: 2 }), row(30, { issue: 2, outcome: "merged", minutes: 20, cost_usd: 2 })];
25
+
26
+ describe("#5987 efficiency ledger", () => {
27
+ it("time-weights concurrency over the window", () => {
28
+ const s = [{ t: NOW - 10 * MIN, running: 0, ceiling: 4 }, { t: NOW - 5 * MIN, running: 4, ceiling: 4 }];
29
+ assert.equal(concurrencyOver(s, NOW - 15 * MIN, NOW).ratio, 0.5);
30
+ });
31
+
32
+ it("slow batch: low concurrency, repeats, attempts, comments and interventions all breach", () => {
33
+ const eff = computeEfficiency({ rows: slowRows(), operator: slowOperator(), prev: { samples: samples(40, 3, 12, 5) }, now: NOW, batchId: "b1", repo: "o/r" });
34
+ assert.equal(eff.v, 1);
35
+ assert.equal(eff.concurrency.ratio, 0.25);
36
+ assert.ok(eff.concurrency.lowSinceMin >= 30);
37
+ assert.equal(eff.attemptsPerMerged, 3.5);
38
+ assert.equal(eff.interventionsPerDay, 7);
39
+ assert.equal(eff.repeats[0].count, 4);
40
+ assert.ok(eff.wastedLaneHours.laterMerged > 2);
41
+ assert.equal(eff.usdPerMerge, 3);
42
+ assert.equal(eff.limiters[0], "capacity");
43
+ const codes = evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }).map((b) => b.code);
44
+ for (const c of ["concurrency", "repeat", "attempts", "interventions", "comments"]) assert.ok(codes.includes(c), `${c} in ${codes}`);
45
+ assert.match(efficiencyLine({ ...eff, concurrency: { ...eff.concurrency, running: 3 }, breaches: [{ issue: 12 }] }), /^efficiency: 3\/12 lanes \(25%\) - limiter capacity.*; 1 SLO breach -> FD#12$/);
46
+ });
47
+
48
+ it("healthy batch: no breaches", () => {
49
+ const eff = computeEfficiency({ rows: healthyRows(), prev: { samples: samples(40, 11, 12, 5) }, now: NOW, batchId: "b2", repo: "o/r" });
50
+ assert.deepEqual(evaluateSlo(eff, DEFAULT_SLO, { repo: "o/r" }), []);
51
+ assert.equal(eff.attemptsPerMerged, 1);
52
+ });
53
+
54
+ it("malformed rows and no samples never throw", () => {
55
+ const eff = computeEfficiency({ rows: [null, "x", { at: "bad" }, { issue: 1, outcome: "merged", phases: { a: { ms: "q" } } }], now: NOW });
56
+ assert.equal(eff.concurrency.ratio, null);
57
+ assert.equal(efficiencyLine(eff), null);
58
+ });
59
+
60
+ it("idleCause reads breaker, lease-held, capacity and base.red from real rows; cleared breaker and old rows give none", () => {
61
+ const r = (o, a = 1) => [row(a, o)];
62
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "tripped" }), NOW), "breaker");
63
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker", detail: "circuit breaker cleared" }), NOW), undefined);
64
+ assert.equal(idleCause(r({ issue: 3, outcome: "deferred", detail: "#3 has a live lane in batch b2; retried in 30s" }), NOW), "lease-held");
65
+ assert.equal(idleCause(r({ issue: 3, outcome: "deferred", code: "sandbox.capacity" }), NOW), "capacity");
66
+ assert.equal(idleCause(r({ issue: 3, outcome: "needs-human", code: "base.red" }), NOW), "base.red");
67
+ assert.equal(idleCause(r({ issue: null, outcome: "breaker" }, 60), NOW), undefined);
68
+ });
69
+
70
+ it("operatorEvents reads requeue, hold-info and parallel files", async () => {
71
+ const { writeFileSync } = await import("node:fs"), { join } = await import("node:path");
72
+ const d = tmpDir("opev-");
73
+ writeFileSync(join(d, "requeue"), JSON.stringify([{ issue: 4, at: iso(5) }, { issue: "x" }]));
74
+ writeFileSync(join(d, "hold-info"), JSON.stringify({ 5: { owner: "operator", since: iso(4) }, 6: { owner: "engine", since: iso(3) } }));
75
+ writeFileSync(join(d, "parallel"), "4\n");
76
+ assert.deepEqual(operatorEvents(d).map((e) => e.kind).sort(), ["hold", "requeue", "set"]);
77
+ assert.deepEqual(operatorEvents(join(d, "none")), []);
78
+ });
79
+ });
@@ -70,6 +70,7 @@ import { classifyStep, heavyConfig, memAvailableMb } from "./heavy.mjs";
70
70
  import { detectPins } from "./toolchain.mjs";
71
71
  import { parseContractComment, noComments } from "./render.mjs";
72
72
  import { parseRelayCommands } from "./relay.mjs";
73
+ import { classifyTransportLoss, AGENT_UP_WINDOW_MS } from "./liveness.mjs";
73
74
  import { detectUsageLimit, parseSessionLimitResetEpochMs } from "../runner.mjs";
74
75
 
75
76
  export const EXECUTION_MODES = Object.freeze(["local", "remote", "hybrid"]);
@@ -141,6 +142,7 @@ export function parseExecution(sec = {}) {
141
142
  onBudget: str(s.on_budget) === "local" ? "local" : "stop", costPerMinute: cpm ?? 0 };
142
143
  const capList = (v) => (Array.isArray(v) ? v : str(v) ? str(v).split(",") : []).map((x) => str(x).toLowerCase()).filter((x) => CAPABILITY_RE.test(x));
143
144
  const hostCapabilities = [...new Set(capList(s.host_capabilities))];
145
+ const offloadWrappers = [...new Set(capList(s.offload_wrappers))]; // unclog: host commands that only send work elsewhere (e.g. a remote-run wrapper); a sandbox runs their argument directly
144
146
  const patRaw = Array.isArray(s.host_capability_patterns) ? s.host_capability_patterns : str(s.host_capability_patterns) ? str(s.host_capability_patterns).split(",") : [];
145
147
  const hostCapabilityPatterns = patRaw.map((x) => { const t = str(x), i = t.indexOf(":"); return { name: t.slice(0, i).trim().toLowerCase(), pattern: t.slice(i + 1).trim() }; })
146
148
  .filter((x) => CAPABILITY_RE.test(x.name) && x.pattern && safeRegExp(x.pattern));
@@ -161,7 +163,7 @@ export function parseExecution(sec = {}) {
161
163
  const plan = ["free", "pro", "team", "enterprise"].includes(str(s.plan).toLowerCase()) ? str(s.plan).toLowerCase() : null;
162
164
  const publicDefault = str(s.public_default).toLowerCase() === "actions" ? "actions" : null; // #5900: opt-in only
163
165
  const dispatcher = /^[A-Za-z0-9][A-Za-z0-9-]*(\[bot\])?$/.test(str(s.dispatcher)) ? str(s.dispatcher) : null;
164
- return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
166
+ return { mode, maxRemote, provider, image, secrets, budget, ...(jobLimit ? { jobLimit } : {}), ...(ciReserve !== null ? { ciReserve } : {}), ...(plan ? { plan } : {}), ...(publicDefault ? { publicDefault } : {}), ...(dispatcher ? { dispatcher } : {}), ...(hostFallback !== null ? { hostFallback } : {}), ...(hostCapabilities.length ? { hostCapabilities } : {}), ...(offloadWrappers.length ? { offloadWrappers } : {}), ...(hostCapabilityPatterns.length ? { hostCapabilityPatterns } : {}), ...(endpoint ? { endpoint } : {}), ...(tokenEnv ? { tokenEnv } : {}), ...(tokenFile ? { tokenFile } : {}), ...(cacheStore ? { cacheStore } : {}), ...(allowActions ? { allowActions } : {}), ...(fallbackLocal ? { fallbackLocal } : {}), ...(capacityFallbackAfter !== null ? { capacityFallbackAfter } : {}), ...(heavy !== null ? { heavy } : {}), ...(unreachableWindowMin !== null ? { unreachableWindowMin } : {}), ...(Object.keys(relay).length ? { relay } : {}), ...(warmSandboxes ? { warmSandboxes } : {}), ...(repoSource ? { repoSource } : {}), ...(accountRotator ? { accountRotator } : {}), ...(lt.tools.length ? { laneTools: lt.tools } : {}), ...(lt.errors.length ? { laneToolsErrors: lt.errors } : {}) };
165
167
  }
166
168
 
167
169
  const round1 = (x) => Math.round(x * 10) / 10;
@@ -178,7 +180,7 @@ const KEEP_DAYS = 7;
178
180
 
179
181
  /**
180
182
  * The execution budget (#4255). `record(key, {minutes, cost_usd})` adds one lane attempt to today's host total; the key
181
- * (`<batch>#<sandbox id>#<startedAt>`) makes a repeated record a no-op. `admit({minutes, cost_usd, running})` gets the
183
+ * (`<batch>#<sandbox id>`) holds one entry per sandbox with its latest cumulative usage (#5987); an identical repeat is a no-op. `admit({minutes, cost_usd, running})` gets the
182
184
  * batch's settled + running usage (`running` the running part alone) and refuses once a batch cap, or a day cap with
183
185
  * today's host total plus this batch's running usage, is reached. A corrupt or unreadable day file refuses while a day
184
186
  * cap is set (a hard cap fails closed) and is ignored otherwise; it is never overwritten.
@@ -207,8 +209,10 @@ export function openExecutionBudget({ budget = {}, file = executionBudgetFile(),
207
209
  const r = read();
208
210
  if (!r.ok) return false;
209
211
  const d = utcDay(now()), today = { ...(r.days[d] ?? {}) };
210
- if (today[key]) return false;
211
- today[key] = { minutes: nonNeg(u?.minutes) ?? 0, cost_usd: nonNeg(u?.cost_usd) ?? 0, at: now() };
212
+ const min = nonNeg(u?.minutes) ?? 0, usd = nonNeg(u?.cost_usd) ?? 0;
213
+ // #5991: one row per key; a replay of the same sandbox keeps the larger usage instead of adding a row
214
+ if (today[key] && !(min > (nonNeg(today[key].minutes) ?? 0) || usd > (nonNeg(today[key].cost_usd) ?? 0))) return false;
215
+ today[key] = { minutes: Math.max(min, nonNeg(today[key]?.minutes) ?? 0), cost_usd: Math.max(usd, nonNeg(today[key]?.cost_usd) ?? 0), at: now() };
212
216
  const days = { [d]: today };
213
217
  for (const [k, v] of Object.entries(r.days)) if (k !== d && Date.parse(k) > now() - KEEP_DAYS * 86400000) days[k] = v;
214
218
  writeAtomic(file, JSON.stringify({ v: 1, days }, null, 2) + "\n");
@@ -699,7 +703,15 @@ const HALTED = { terminalReason: "deferred", detail: "batch halted (schedd hando
699
703
  * (`backendId`; the sandbox's own id kept as `laneBackendId`), so orchestrate can place lanes away from a limited pool.
700
704
  */
701
705
  export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env, secrets = [], pollMs = 5000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
702
- costPerMinute = 0, now = () => Date.now(), unreachableWindowMs = 300000, logTail = null, holdId = null }) {
706
+ costPerMinute = 0, now = () => Date.now(), unreachableWindowMs = 300000, logTail = null, holdId = null, agentOnline = null, suspendKept = null, resumeKept = null, phaseOf = null }) {
707
+ // #6008: a sandbox kept for adopt keeps running with no dispatcher: record it (issue, since, phase) and tell it to suspend (the lane refuses push/merge until adopted)
708
+ const keepNote = (r, n, h) => {
709
+ if (!Number.isInteger(n)) return r;
710
+ let phase = null; try { phase = phaseOf?.(n) ?? null; } catch { phase = null; }
711
+ const kept = { issue: n, since: now(), phase, ...(h?.id ? { id: h.id } : {}) };
712
+ try { Promise.resolve(suspendKept?.(n, kept)).catch(() => {}); } catch { /* best effort */ }
713
+ return { ...r, kept };
714
+ };
703
715
  const cpm = nonNeg(Number(costPerMinute)) ?? 0;
704
716
  // #4255: the sandbox's usage: the provider's `usage()`, else the billable minutes it put on the handle (#4254), else wall
705
717
  // clock since the handle's startedAt; cost is the provider's, else minutes x cost_per_minute.
@@ -734,22 +746,27 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
734
746
  try { const v = await fn(); st.waited = 0; st.tries = 0; return v; } catch (e) {
735
747
  if (!isTransportError(e)) throw e;
736
748
  // release review BUG-6: a 401 that outlasts the window is an auth failure (capped sandbox.auth), not an uncapped unreachable pool
737
- if (st.waited >= unreachableWindowMs) throw Object.assign(new Error(`unreachable for ${Math.round(st.waited / 1000)}s: ${errText(e)}`), { unreachable: true, ...(e?.status === 401 ? { auth: true, hop: e.hop } : {}) });
738
- const d = Math.min(pollMs * 2 ** Math.min(st.tries++, 10), 30000, Math.max(1, unreachableWindowMs - st.waited));
749
+ // #5991: once the wait reaches the agent-up window, ask the pool agent; an answering agent means this sandbox is gone
750
+ let up = null;
751
+ if (typeof agentOnline === "function" && st.waited >= AGENT_UP_WINDOW_MS && st.waited < unreachableWindowMs) { try { up = (await agentOnline(st.h)) === true; } catch { up = false; } }
752
+ if (classifyTransportLoss({ agentOnline: up, waitedMs: st.waited, windowMs: unreachableWindowMs }) === "unreachable") throw Object.assign(new Error(`unreachable for ${Math.round(st.waited / 1000)}s: ${errText(e)}`), { unreachable: true, ...(e?.status === 401 ? { auth: true, hop: e.hop } : {}) });
753
+ const d = Math.min(pollMs * 2 ** Math.min(st.tries++, 10), 30000, Math.max(1, unreachableWindowMs - st.waited),
754
+ typeof agentOnline === "function" && st.waited < AGENT_UP_WINDOW_MS ? AGENT_UP_WINDOW_MS - st.waited : Infinity); // land on the probe point
739
755
  st.waited += d;
740
756
  await sleep(d);
741
757
  }
742
758
  }
743
759
  };
744
- const unreachable = (h, e) => (e?.auth
760
+ const unreachable0 = (h, e) => (e?.auth
745
761
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_AUTH, retryInSeconds: 300, detail: `sandbox ${h.id} kept answering 401 (${e.hop === "agent" ? "the pool agent refused the router" : "check the pool token"}): ${errText(e)}; kept for adopt on resume` }
746
762
  : { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_UNREACHABLE, retryInSeconds: 60,
747
763
  detail: `sandbox ${h.id} ${errText(e)}; kept for adopt on resume` });
764
+ const unreachable = (h, e) => keepNote(unreachable0(h, e), h?.issue, h);
748
765
  const tailOf = async (h) => { try { return typeof logTail === "function" ? String(await logTail(h) ?? "") : ""; } catch { return ""; } };
749
766
  const settleClone = (r, id) => (r?.terminalReason === "engine-error" && r.code === undefined && isEgressTimeout(r.detail) ? egressDeferred(id, errLine(r.detail))
750
767
  : r?.terminalReason === "engine-error" && r.code === undefined && isCloneFailure(r.detail) ? cloneDeferred(id, errLine(r.detail)) : r);
751
768
  // #5669: a halted batch (schedd handover) stops polling; the sandbox is neither torn down nor released, so the next daemon adopts it.
752
- const wait = async (h, g = guard({ waited: 0, tries: 0 }), sig = null) => {
769
+ const wait = async (h, g = guard({ waited: 0, tries: 0, h }), sig = null) => {
753
770
  for (;;) {
754
771
  if (sig?.aborted) return null;
755
772
  const r = await g(() => provider.fetchResult(h));
@@ -779,7 +796,7 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
779
796
  const startFailed = (id, e) => ([401, 403].includes(e?.status)
780
797
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_AUTH, retryInSeconds: 300, detail: `sandbox ${id} could not start (auth): ${errText(e)}; ${e?.hop === "agent" ? "the pool agent refused the router (re-enroll or fix the agent token)" : "check the pool token (COMPUTESHARE_TOKEN or ~/.config/computeshare/forgedock.token)"}` }
781
798
  : e?.retryable === true
782
- ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, detail: `sandbox ${id} could not start (capacity): ${errText(e)}`, ...(Number(e.retryInSeconds) > 0 ? { retryInSeconds: Number(e.retryInSeconds) } : {}) }
799
+ ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_CAPACITY, detail: `sandbox ${id} could not start (capacity): ${errText(e)}`, ...(typeof e.poolCode === "string" ? { reason: e.poolCode.replace(/^pool\./, "").replace(/^disk_(low|cap)$/, "disk") } : {}), ...(e.live ? { live: e.live } : {}), ...(Number(e.retryInSeconds) > 0 ? { retryInSeconds: Number(e.retryInSeconds) } : {}) }
783
800
  // #5095: a 5xx from the pool router or agent is infrastructure: deferred with backoff (capped), never needs-human
784
801
  : (Number.isInteger(e?.status) && e.status >= 500 && e.status <= 599) || e?.transient === true || (isTransportError(e) && !isCloneFailure(errText(e))) // #5656: fetch failed, ECONNRESET, ETIMEDOUT; a clone timeout keeps its own code
785
802
  ? { terminalReason: "deferred", code: OUTCOME_CODES.SANDBOX_TRANSIENT, retryInSeconds: Number(e.retryInSeconds) > 0 ? Number(e.retryInSeconds) : TRANSIENT_RETRY_S,
@@ -817,7 +834,7 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
817
834
  started = true;
818
835
  ctx.onStart?.({ ...(Number.isInteger(h.pid) ? { pid: h.pid } : {}), handle: h, remote: true });
819
836
  r = settleClone(await wait(h, undefined, ctx.signal), base.id);
820
- if (ctx.signal?.aborted) return HALTED; // #5669: the sandbox stays for adopt, whatever `r` is
837
+ if (ctx.signal?.aborted) return keepNote(HALTED, n, h); // #5669: the sandbox stays for adopt, whatever `r` is
821
838
  } catch (e) {
822
839
  if (started && e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: no tear, the ledger keeps it
823
840
  r = started ? settleClone({ terminalReason: "engine-error", detail: `sandbox ${base.id}: ${errText(e)}` }, base.id) : startFailed(base.id, e);
@@ -836,17 +853,18 @@ export function providerLanes({ provider, laneArgs, ledgerFor, env = process.env
836
853
  saved = (ledgerFor(n)?.entries("sandbox") ?? []).find((e) => e.value === id && (e.provider ?? e.handle?.provider) === provider.name)?.handle;
837
854
  }
838
855
  if (!saved?.id || saved.provider !== provider.name) return null;
856
+ try { Promise.resolve(resumeKept?.(n)).catch(() => {}); } catch { /* best effort */ } // #6008: adopted: the lease is re-established
839
857
  // Usage runs from the sandbox's real start (persisted on the handle), not from this adopt.
840
858
  const h = { ...saved, ...(Number.isFinite(saved.startedAt) ? {} : Number.isFinite(rec?.startedAt) ? { startedAt: rec.startedAt } : {}) };
841
859
  const led = ledgerFor(n);
842
860
  led?.register("sandbox", h.id, { provider: provider.name, handle: { provider: h.provider, id: h.id, issue: h.issue, ...(Number.isFinite(h.startedAt) ? { startedAt: h.startedAt } : {}) } }); // now owned by this dispatcher
843
861
  let r;
844
- const g = guard({ waited: 0, tries: 0 });
862
+ const g = guard({ waited: 0, tries: 0, h });
845
863
  try {
846
864
  const ended = await g(() => provider.fetchResult(h));
847
865
  if (!ended && (await g(() => provider.status(h))) !== "running") r = null; // relaunched
848
866
  else { if (!ended) ctx.onLive?.(); r = await wait(h, g, ctx.signal); } // #4504: a live sandbox is awaited in the background
849
- if (ctx.signal?.aborted) return null; // #5669: halted: left for the next adopt, no tear
867
+ if (ctx.signal?.aborted) { keepNote(HALTED, n, h); return null; } // #5669: halted: left for the next adopt, no tear
850
868
  } catch (e) {
851
869
  if (e?.unreachable) return withUsage(unreachable(h, e), h); // #4672: same tolerance; no tear, left for the next adopt
852
870
  r = { terminalReason: "engine-error", detail: `sandbox ${h.id}: ${errText(e)}` };
@@ -7,6 +7,7 @@ import { mkdirSync, writeFileSync, existsSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { tmpDir } from "../tests/_tmp.mjs";
9
9
  import { renderContract } from "./render.mjs";
10
+ import { sandboxBudgetKey } from "./liveness.mjs";
10
11
  import { parseExecution, hostFallbackAllowed, SANDBOX_PROVIDERS, detectNeeds, hostCapabilityBlock, placementText, contractHostNeeds, placement, placeLane, validationWeight, hostHeadroom, scopedEnv, providerLanes, remoteHoldId, usageLimitInTail, isTransportError, isCloneFailure, isEgressTimeout, SANDBOX_EGRESS_TIMEOUT_CODE, containerProvider, providerByName, openExecutionBudget, poolCredential, remoteTransportFor, resolveDefaultExecution, repoIsPublic } from "./execution.mjs";
11
12
  import * as executionModule from "./execution.mjs";
12
13
  import { remoteProvider } from "./sandbox-remote.mjs";
@@ -126,6 +127,35 @@ describe("providerLanes: an unreachable provider is retried, then deferred witho
126
127
  assert.deepEqual(ledgerFor(7).entries("sandbox").map((e) => e.value), ["fake-7"]);
127
128
  });
128
129
 
130
+ it("#5991 transport failure with the agent answering ends sandbox.unreachable within 90 s; agent down keeps the window", async () => {
131
+ const run = async (agentOnline) => {
132
+ const prov = flaky(1e9); prov.start = async () => ({ provider: "fake", id: "fake-7", issue: 7 }); let total = 0;
133
+ const r = await providerLanes({ provider: prov, laneArgs: () => [], ledgerFor: ledgerIn(tmpDir("exec-up-")), pollMs: 5000, unreachableWindowMs: 300000, agentOnline, sleep: async (ms) => { total += ms; } }).runOne(7, "staging");
134
+ return { r, total };
135
+ };
136
+ const up = await run(async () => true);
137
+ assert.deepEqual([up.r.terminalReason, up.r.code], ["deferred", "sandbox.unreachable"]);
138
+ assert.ok(up.total <= 90000, `waited ${up.total}`);
139
+ for (const a of [async () => false, async () => { throw new Error("router down"); }, null]) {
140
+ const down = await run(a);
141
+ assert.equal(down.r.code, "sandbox.unreachable");
142
+ assert.ok(down.total >= 300000, `waited ${down.total}`);
143
+ }
144
+ });
145
+
146
+ it("#5991 24 replayed attempts of one sandbox leave one budget row within 5% of the real minutes", () => {
147
+ const file = join(tmpDir("exec-budget-"), "execution-budget.json");
148
+ const b = openExecutionBudget({ file, now: () => 0 });
149
+ for (let i = 1; i <= 24; i++) b.record(sandboxBudgetKey("b1", "fdrsbx-9"), { minutes: i * 5, cost_usd: 0 });
150
+ const rows = Object.values(JSON.parse(readFileSync(file, "utf8")).days).flatMap((d) => Object.keys(d));
151
+ assert.deepEqual(rows, ["b1#fdrsbx-9"]);
152
+ assert.ok(Math.abs(b.dayTotals().minutes - 120) / 120 <= 0.05);
153
+ assert.equal(b.record(sandboxBudgetKey("b1", "fdrsbx-9"), { minutes: 10 }), false); // a smaller replay changes nothing
154
+ const before = b.dayTotals().minutes;
155
+ b.record(sandboxBudgetKey("b1", "fdrsbx-9", 99), { minutes: 7 }); // #6023: a rerun reusing the sandbox id adds its own usage
156
+ assert.equal(b.dayTotals().minutes, before + 7);
157
+ });
158
+
129
159
  it("#5053 a 401 on status/result of a launched sandbox is retried, then ends sandbox.auth (capped), never engine-error", async () => {
130
160
  const e401 = () => Object.assign(new Error("sandbox status: HTTP 401 (agent a1 auth)"), { status: 401, hop: "agent", transient: true });
131
161
  const mk = (failPolls) => { const prov = flaky(0); let polls = 0; prov.start = async () => ({ provider: "fake", id: "fake-7", issue: 7 });
@@ -642,6 +672,13 @@ describe("execution budget and sandbox cost (#4255)", () => {
642
672
  const a = openExecutionBudget({ budget: { dayMinutes: 15 }, file, now });
643
673
  assert.equal(a.record("b1#fdsbx-1#100", { minutes: 10, cost_usd: 1 }), true);
644
674
  assert.equal(a.record("b1#fdsbx-1#100", { minutes: 10, cost_usd: 1 }), false);
675
+ // #5987: cumulative samples of one sandbox are one entry holding the latest usage; the day sum tracks the log's minutes
676
+ const u = openExecutionBudget({ budget: {}, file: join(tmpDir("exec-up-"), "b.json"), now });
677
+ for (const m of [1, 2, 3, 5, 8, 10]) u.record("b2#fdsbx-2", { minutes: m, cost_usd: m / 10 });
678
+ u.record("b2#fdsbx-3", { minutes: 20, cost_usd: 2 });
679
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(u.file, "utf8")).days["2026-10-20"]).sort(), ["b2#fdsbx-2", "b2#fdsbx-3"]);
680
+ const logMinutes = 10 + 20;
681
+ assert.ok(Math.abs(u.dayTotals().minutes - logMinutes) <= logMinutes * 0.05);
645
682
  const b = openExecutionBudget({ budget: { dayMinutes: 15 }, file, now }); // a fresh daemon
646
683
  assert.deepEqual(b.dayTotals(), { ok: true, day: "2026-10-20", minutes: 10, cost_usd: 1 });
647
684
  assert.equal(b.admit({ minutes: 0, cost_usd: 0, running: { minutes: 0, cost_usd: 0 } }).ok, true);
@@ -1150,6 +1187,15 @@ describe("#5095: launch 5xx and a pool usage limit are deferred, never needs-hum
1150
1187
  assert.equal((await lanesFor(prov).runOne(7, null)).code, "sandbox.capacity");
1151
1188
  });
1152
1189
 
1190
+ it("a pool refusal code and live figures ride the sandbox.capacity deferral row as reason/live (#5985)", async () => {
1191
+ const prov = fakeProvider();
1192
+ prov.start = async () => { throw Object.assign(new Error("sandbox launch: HTTP 503"), { status: 503, retryable: true, poolCode: "pool.host_load", live: { load_per_core: 2.1, mem_available_gb: 8 }, retryInSeconds: 60 }); };
1193
+ const r = await lanesFor(prov).runOne(7, null);
1194
+ assert.deepEqual([r.code, r.reason, r.live.load_per_core, r.retryInSeconds], ["sandbox.capacity", "host_load", 2.1, 60]);
1195
+ prov.start = async () => { throw Object.assign(new Error("x"), { status: 503, retryable: true, poolCode: "pool.disk_low" }); };
1196
+ assert.equal((await lanesFor(prov).runOne(7, null)).reason, "disk");
1197
+ });
1198
+
1153
1199
  it("usageLimitInTail reads the lean finish line and the CLI's own limit message", () => {
1154
1200
  assert.deepEqual(usageLimitInTail("x\n[lane] deferred: usage limit hit; resets at 3:20pm (UTC)\n"), { resetAt: "3:20pm (UTC)" });
1155
1201
  assert.equal(usageLimitInTail("sandbox exited 1\nclone ok"), null);
@@ -0,0 +1,46 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5979: identical-failure stop. A lane that ends needs-human with the same (code, normalised detail) as an earlier NEEDS_HUMAN
5
+ * or PARKED comment of the issue is parked with one consolidated comment instead of being recovered or relaunched. Pure.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+
9
+ export const SIG_RE = /\bsig=([0-9a-f]{12})\b/;
10
+ const MARKER_RE = /<!--\s*FORGE:(NEEDS_HUMAN|PARKED)(?![A-Za-z0-9_])/;
11
+
12
+ /** Detail without what differs between two runs of the same failure: shas, timestamps, numbers (costs, counts, ids), whitespace. */
13
+ export function normalizeDetail(detail) {
14
+ return String(detail ?? "")
15
+ .replace(/\b\d{4}-\d{2}-\d{2}T[\d:.]+Z?\b/g, "")
16
+ .replace(/\b[0-9a-f]{7,40}\b/g, "")
17
+ .replace(/\$\d+(\.\d+)?/g, "")
18
+ .replace(/\d+/g, "")
19
+ .replace(/\s+/g, " ")
20
+ .trim()
21
+ .toLowerCase();
22
+ }
23
+
24
+ /** 12 hex characters of sha256(code + normalised detail): a repeat fingerprint, not a security hash (sha256 keeps CodeQL js/weak-cryptographic-algorithm quiet). */
25
+ export function repeatSignature(code, detail) {
26
+ return createHash("sha256").update(`${code ?? ""}\n${normalizeDetail(detail)}`).digest("hex").slice(0, 12);
27
+ }
28
+
29
+ /** Earlier trusted NEEDS_HUMAN/PARKED comments carrying `sig=<hash>`. A PARKED summary counts as the failure it parked on. */
30
+ export function countIdentical(comments, sig, trusted = () => true) {
31
+ let n = 0;
32
+ for (const c of Array.isArray(comments) ? comments : []) {
33
+ const body = String(c?.body ?? "");
34
+ if (MARKER_RE.test(body) && SIG_RE.exec(body)?.[1] === sig && trusted(c)) n++;
35
+ }
36
+ return n;
37
+ }
38
+
39
+ /** True from the 2nd identical failure (`count` includes the one being handled). */
40
+ export const shouldPark = (count) => count >= 2;
41
+
42
+ /** The one consolidated comment: the attempts, the identical failure, and what would unblock it. */
43
+ export function summaryComment({ attempts, code, detail, unblock, sig = "" }) {
44
+ const n = Number.isInteger(attempts) ? attempts : 2;
45
+ return `## Parked: the same failure repeated\n**Attempts**: ${n} lane runs ended with the identical failure \`${code}\`; the engine stops relaunching it.\n**Failure**: ${String(detail ?? "").trim().slice(0, 1500)}\n**To unblock**: ${unblock || "a decision or input that changes what the lane can do (edit the issue or contract, supply the missing input), then remove the parked label to rerun."}${sig ? `\nsig=${sig}` : ""}`;
46
+ }
@@ -0,0 +1,45 @@
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 { repeatSignature, countIdentical, shouldPark, summaryComment } from "./failure-stop.mjs";
6
+ import { OUTCOME_CODES, RECOVERABLE_CODES, classifyNeedsHuman, parkedLabel } from "../engine/outcome-codes.mjs";
7
+
8
+ const D1 = "R3 unimplemented at 1e0c3e45 (cost $1.2345, 12 turns) 2026-11-25T10:00:00Z";
9
+ const D2 = "R3 unimplemented at 0703a2d8 (cost $9.99, 40 turns) 2026-11-26T11:11:11Z";
10
+ const nh = (sig) => ({ body: `<!-- FORGE:NEEDS_HUMAN -->\n## Needs human\nx\n\nsig=${sig}\n\n_cost $1_` });
11
+
12
+ describe("identical-failure stop (#5979)", () => {
13
+ it("the signature is stable across shas, costs and timestamps and differs across codes and details", () => {
14
+ assert.equal(repeatSignature("conformance.omission", D1), repeatSignature("conformance.omission", D2));
15
+ assert.notEqual(repeatSignature("conformance.omission", D1), repeatSignature("ci.red", D1));
16
+ assert.notEqual(repeatSignature("ci.red", "lint failed"), repeatSignature("ci.red", "tests failed"));
17
+ });
18
+ it("the 2nd identical failure parks, the 1st does not", () => {
19
+ const sig = repeatSignature("ci.red", "boom");
20
+ assert.equal(shouldPark(countIdentical([], sig) + 1), false);
21
+ assert.equal(shouldPark(countIdentical([nh(sig)], sig) + 1), true);
22
+ assert.equal(shouldPark(countIdentical([nh("ffffffffffff")], sig) + 1), false);
23
+ });
24
+ it("an untrusted comment or one without the marker does not count; a PARKED summary does", () => {
25
+ const sig = "abcabcabcabc";
26
+ assert.equal(countIdentical([nh(sig)], sig, () => false), 0);
27
+ assert.equal(countIdentical([{ body: `sig=${sig}` }], sig), 0);
28
+ assert.equal(countIdentical([{ body: `<!-- FORGE:PARKED -->\nsig=${sig}` }], sig), 1);
29
+ });
30
+ it("the summary names the attempts, the failure and what would unblock it", () => {
31
+ const s = summaryComment({ attempts: 2, code: "ci.red", detail: "boom", unblock: "decide X", sig: "abcabcabcabc" });
32
+ assert.match(s, /2 lane runs/);
33
+ assert.match(s, /`ci\.red`/);
34
+ assert.match(s, /boom/);
35
+ assert.match(s, /To unblock\*\*: decide X/);
36
+ assert.match(s, /sig=abcabcabcabc/);
37
+ });
38
+ it("failure.repeated is parked, never recoverable", () => {
39
+ assert.equal(RECOVERABLE_CODES.includes(OUTCOME_CODES.FAILURE_REPEATED), false);
40
+ const row = { outcome: "needs-human", code: OUTCOME_CODES.FAILURE_REPEATED };
41
+ assert.equal(classifyNeedsHuman(row), "terminal");
42
+ assert.equal(classifyNeedsHuman(row, { parked: true }), "parked");
43
+ assert.equal(parkedLabel(OUTCOME_CODES.FAILURE_REPEATED), "parked:failure.repeated");
44
+ });
45
+ });