forgedock 1.65.0 → 1.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/config-schema.mjs +2 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +143 -19
- package/bin/forgedock.mjs +7 -0
- package/bin/help-text.mjs +3 -3
- package/bin/introspect-schedule.mjs +98 -0
- package/bin/introspect-schedule.test.mjs +67 -0
- package/bin/lean/advisory.test.mjs +49 -0
- package/bin/lean/amendment-schema.mjs +31 -0
- package/bin/lean/attempts.mjs +159 -0
- package/bin/lean/attempts.test.mjs +127 -0
- package/bin/lean/basered.mjs +55 -0
- package/bin/lean/basered.test.mjs +68 -1
- package/bin/lean/batch-health.mjs +13 -5
- package/bin/lean/batch-health.test.mjs +16 -0
- package/bin/lean/batch.mjs +62 -0
- package/bin/lean/batch.test.mjs +119 -3
- package/bin/lean/capwait.mjs +14 -3
- package/bin/lean/capwait.test.mjs +20 -0
- package/bin/lean/clear-breaker.mjs +14 -0
- package/bin/lean/commentstate.mjs +41 -0
- package/bin/lean/commentstate.test.mjs +32 -0
- package/bin/lean/concurrency.mjs +89 -0
- package/bin/lean/concurrency.test.mjs +113 -0
- package/bin/lean/conformance.e2e.test.mjs +4 -2
- package/bin/lean/conformance.mjs +35 -3
- package/bin/lean/conformance.test.mjs +52 -0
- package/bin/lean/depcache.mjs +9 -0
- package/bin/lean/efficiency.mjs +162 -0
- package/bin/lean/efficiency.test.mjs +79 -0
- package/bin/lean/execution.mjs +31 -13
- package/bin/lean/execution.test.mjs +46 -0
- package/bin/lean/failure-stop.mjs +46 -0
- package/bin/lean/failure-stop.test.mjs +45 -0
- package/bin/lean/fixtures/capacity-storm.json +609 -0
- package/bin/lean/lean.mjs +130 -30
- package/bin/lean/lean.test.mjs +138 -47
- package/bin/lean/liveness.mjs +37 -0
- package/bin/lean/liveness.test.mjs +33 -0
- package/bin/lean/orchestrate-attempts.test.mjs +74 -0
- package/bin/lean/orchestrate-envhold.test.mjs +17 -0
- package/bin/lean/orchestrate-pause.test.mjs +84 -0
- package/bin/lean/orchestrate-reconcile.test.mjs +147 -0
- package/bin/lean/orchestrate.mjs +202 -28
- package/bin/lean/phaseledger.mjs +6 -0
- package/bin/lean/phaseledger.test.mjs +13 -1
- package/bin/lean/prompts.mjs +6 -10
- package/bin/lean/reconcile.mjs +90 -0
- package/bin/lean/recurrence.mjs +38 -2
- package/bin/lean/recurrence.test.mjs +56 -1
- package/bin/lean/sandbox-remote.mjs +33 -2
- package/bin/lean/sched.mjs +19 -0
- package/bin/lean/sched.test.mjs +11 -1
- package/bin/lean/schedd-health.mjs +8 -1
- package/bin/lean/schedd-health.test.mjs +19 -0
- package/bin/lean/schedd.mjs +97 -10
- package/bin/lean/schedd.test.mjs +138 -1
- package/bin/lean/slo.mjs +126 -0
- package/bin/lean/slo.test.mjs +112 -0
- package/bin/lean/statuscomment.mjs +37 -0
- package/bin/lean/statuscomment.test.mjs +48 -1
- package/bin/lean/verify.mjs +2 -1
- package/bin/pool/agent.mjs +46 -8
- package/bin/pool/cache-sweep.mjs +41 -4
- package/bin/pool/cli.mjs +28 -1
- package/bin/pool/health.mjs +18 -0
- package/bin/pool/lane-tools.mjs +21 -0
- package/bin/pool/mirror-seed.mjs +21 -2
- package/bin/pool/router.mjs +6 -2
- package/bin/stats/attempts.mjs +54 -0
- package/bin/stats/attempts.test.mjs +30 -0
- package/bin/stats/churn.mjs +49 -0
- package/bin/stats/churn.test.mjs +31 -0
- package/bin/stats/index.mjs +11 -3
- package/commands/orchestrate.md +21 -18
- package/docs/CONFIG.md +1 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/package.json +1 -1
- package/pool/image/entrypoint.sh +2 -1
- package/scripts/check-devdocs-freshness.sh +1 -1
package/bin/lean/execution.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
211
|
-
|
|
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
|
-
|
|
738
|
-
|
|
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
|
|
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
|
+
});
|