forgedock 1.67.0 → 1.69.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 +1 -0
- package/bin/engine/outcome-codes.mjs +1 -0
- package/bin/engine-cli.mjs +103 -21
- package/bin/engine.mjs +10 -0
- package/bin/forgedock.mjs +17 -1
- package/bin/help-text.mjs +1 -0
- package/bin/lean/admission.mjs +21 -0
- package/bin/lean/admission.test.mjs +30 -0
- package/bin/lean/advisory.test.mjs +39 -15
- package/bin/lean/amendment-schema.mjs +3 -4
- package/bin/lean/attempts.mjs +34 -31
- package/bin/lean/attempts.test.mjs +33 -19
- package/bin/lean/basered.mjs +26 -0
- package/bin/lean/batch-health.mjs +17 -12
- package/bin/lean/batch-health.test.mjs +39 -11
- package/bin/lean/batch.mjs +11 -1
- package/bin/lean/batch.test.mjs +51 -2
- package/bin/lean/capsample.mjs +25 -0
- package/bin/lean/ci-gate.mjs +2 -90
- package/bin/lean/ci-gate.test.mjs +1 -127
- package/bin/lean/ci-precheck.mjs +25 -8
- package/bin/lean/ci-precheck.test.mjs +24 -0
- package/bin/lean/clear-breaker.test.mjs +4 -3
- package/bin/lean/commentstate.mjs +10 -5
- package/bin/lean/commentstate.test.mjs +12 -1
- package/bin/lean/conformance.e2e.test.mjs +9 -6
- package/bin/lean/conformance.mjs +62 -197
- package/bin/lean/conformance.test.mjs +46 -376
- package/bin/lean/depcache.mjs +102 -10
- package/bin/lean/depcache.test.mjs +105 -0
- package/bin/lean/docsgate.mjs +0 -32
- package/bin/lean/docsgate.test.mjs +2 -23
- package/bin/lean/effects-cap.test.mjs +9 -1
- package/bin/lean/effects-killtree.test.mjs +35 -0
- package/bin/lean/effects.mjs +57 -25
- package/bin/lean/engine-readmit.test.mjs +35 -0
- package/bin/lean/envgap.mjs +111 -0
- package/bin/lean/envgap.test.mjs +64 -0
- package/bin/lean/execution.mjs +13 -4
- package/bin/lean/execution.test.mjs +33 -0
- package/bin/lean/failure-census.mjs +170 -0
- package/bin/lean/failure-census.test.mjs +59 -0
- package/bin/lean/failure-stop.mjs +12 -1
- package/bin/lean/failure-stop.test.mjs +14 -1
- package/bin/lean/guardgate.test.mjs +2 -3
- package/bin/lean/heavy.mjs +33 -4
- package/bin/lean/heavy.test.mjs +38 -6
- package/bin/lean/hostconfig.mjs +54 -0
- package/bin/lean/hostconfig.test.mjs +67 -0
- package/bin/lean/hotarea.mjs +0 -36
- package/bin/lean/hotarea.test.mjs +1 -22
- package/bin/lean/issuewatch-verify.mjs +19 -4
- package/bin/lean/issuewatch.mjs +21 -4
- package/bin/lean/issuewatch.test.mjs +48 -1
- package/bin/lean/lane-audit-gap.mjs +66 -0
- package/bin/lean/lane-audit-gap.test.mjs +59 -0
- package/bin/lean/lane-audit-llm.mjs +52 -0
- package/bin/lean/lane-audit-llm.test.mjs +57 -0
- package/bin/lean/lane-audit-query.mjs +47 -0
- package/bin/lean/lane-audit-query.test.mjs +44 -0
- package/bin/lean/lane-audit-signatures.mjs +33 -0
- package/bin/lean/lane-audit.mjs +110 -0
- package/bin/lean/lane-audit.test.mjs +97 -0
- package/bin/lean/lane-recovery.test.mjs +33 -0
- package/bin/lean/lanecheck.mjs +5 -3
- package/bin/lean/lanecheck.test.mjs +6 -0
- package/bin/lean/lean.mjs +247 -152
- package/bin/lean/lean.test.mjs +502 -206
- package/bin/lean/limits.mjs +17 -0
- package/bin/lean/limits.test.mjs +15 -1
- package/bin/lean/live-execution.mjs +24 -2
- package/bin/lean/live-execution.test.mjs +62 -0
- package/bin/lean/orchestrate-attempts.test.mjs +17 -9
- package/bin/lean/orchestrate-dispatch-placement.test.mjs +81 -0
- package/bin/lean/orchestrate-envhold.test.mjs +62 -1
- package/bin/lean/orchestrate-heldroot.test.mjs +72 -0
- package/bin/lean/orchestrate-hostfallback.test.mjs +59 -1
- package/bin/lean/orchestrate-overload-recovery.test.mjs +37 -0
- package/bin/lean/orchestrate-pause.test.mjs +53 -1
- package/bin/lean/orchestrate-reconcile.test.mjs +17 -0
- package/bin/lean/orchestrate-relaunch-gates.test.mjs +57 -0
- package/bin/lean/orchestrate-stacking.test.mjs +10 -0
- package/bin/lean/orchestrate.mjs +215 -42
- package/bin/lean/postdeploy-check.test.mjs +1 -3
- package/bin/lean/precheck.mjs +20 -0
- package/bin/lean/preflight.mjs +110 -14
- package/bin/lean/preflight.test.mjs +64 -4
- package/bin/lean/prompts.mjs +11 -21
- package/bin/lean/recurrence.mjs +6 -148
- package/bin/lean/recurrence.test.mjs +11 -147
- package/bin/lean/release-deploy.mjs +35 -5
- package/bin/lean/release-deploy.test.mjs +50 -3
- package/bin/lean/release-flakes.mjs +48 -2
- package/bin/lean/release-flakes.test.mjs +45 -1
- package/bin/lean/release-ledger.mjs +19 -1
- package/bin/lean/release-ledger.test.mjs +23 -0
- package/bin/lean/release-preflight.mjs +28 -0
- package/bin/lean/release-preflight.test.mjs +42 -1
- package/bin/lean/release-review.mjs +40 -5
- package/bin/lean/release-review.test.mjs +43 -2
- package/bin/lean/release.mjs +45 -15
- package/bin/lean/release.test.mjs +32 -0
- package/bin/lean/retry.mjs +1 -1
- package/bin/lean/retry.test.mjs +6 -1
- package/bin/lean/rotator.mjs +9 -0
- package/bin/lean/rotator.test.mjs +11 -1
- package/bin/lean/sandbox-remote.mjs +51 -13
- package/bin/lean/schedd.mjs +13 -8
- package/bin/lean/schedd.test.mjs +65 -5
- package/bin/lean/selfreview.mjs +1 -1
- package/bin/lean/statuscomment.mjs +4 -1
- package/bin/lean/validate-catalog.mjs +108 -0
- package/bin/lean/validate-catalog.test.mjs +46 -1
- package/bin/lean/verify.mjs +1 -1
- package/bin/pool/affinity.test.mjs +91 -0
- package/bin/pool/agent.mjs +247 -23
- package/bin/pool/cache-sweep.mjs +31 -10
- package/bin/pool/ci-autoscale.mjs +160 -0
- package/bin/pool/cli.mjs +56 -9
- package/bin/pool/docker.mjs +5 -0
- package/bin/pool/engine-placement.test.mjs +94 -0
- package/bin/pool/image-manifest.mjs +24 -0
- package/bin/pool/image-manifest.test.mjs +20 -0
- package/bin/pool/lane-target.mjs +41 -0
- package/bin/pool/lane-tools.mjs +29 -5
- package/bin/pool/lane-tools.test.mjs +36 -7
- package/bin/pool/mirror-seed.mjs +15 -11
- package/bin/pool/project-layer.mjs +142 -0
- package/bin/pool/project-layer.test.mjs +73 -0
- package/bin/pool/router.mjs +106 -36
- package/bin/pool/version.mjs +72 -2
- package/bin/review-staging.mjs +11 -3
- package/bin/runner.mjs +59 -11
- package/bin/stats/release.mjs +7 -0
- package/bin/stats/release.test.mjs +20 -0
- package/bin/stats/scorecard.mjs +187 -0
- package/bin/stats/scorecard.test.mjs +89 -0
- package/bin/stats/tool-parks.mjs +29 -0
- package/bin/stats/tool-parks.test.mjs +21 -0
- package/docs/CONFIG.md +41 -0
- package/docs/OUTCOME-CODES.md +1 -0
- package/docs/STATS.md +17 -0
- package/package.json +1 -1
- package/pool/image/Dockerfile +15 -3
- package/pool/image/manifest.json +25 -0
- package/pool/image/mirror.sh +11 -2
- package/pool/install/install-agent.ps1 +11 -4
- package/scripts/ci-local/adapters/github-actions.mjs +8 -0
- package/scripts/ci-local/cli.mjs +1 -1
- package/scripts/ci-local/plan.mjs +3 -2
- package/scripts/ci-local.test.sh +14 -2
- package/scripts/failure-census.mjs +67 -0
- package/scripts/review-finalize.sh +5 -5
- package/scripts/review-finalize.test.sh +8 -1
- package/scripts/verify-phase-trail.sh +11 -0
- package/scripts/verify-phase-trail.test.sh +9 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// #6041: per-repo agent affinity (repos.<slug>.agents / exclude_agents) shared by launch, claim, seedAgent and the capacity views.
|
|
4
|
+
import { test } from "node:test";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import { createRouter } from "./router.mjs";
|
|
8
|
+
import { httpTransport } from "../lean/sandbox-remote.mjs";
|
|
9
|
+
import { tmpDir } from "../tests/_tmp.mjs";
|
|
10
|
+
|
|
11
|
+
const quiet = { info() {}, warn() {}, error() {} };
|
|
12
|
+
const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json" } });
|
|
13
|
+
const spec = (id, slug = "o/x") => ({ id, issue: 1, batch: "b", repo: { slug, url: `https://github.com/${slug}.git` }, command: ["x"] });
|
|
14
|
+
|
|
15
|
+
function fixture(repos, hosts = ["a", "b", "c"]) {
|
|
16
|
+
const posts = [];
|
|
17
|
+
const fetchFn = async (url, init) => {
|
|
18
|
+
const u = new URL(url);
|
|
19
|
+
if (u.pathname === "/capacity") return json({ cpus_free: 8 - hosts.indexOf(u.hostname), mem_free_gb: 16 });
|
|
20
|
+
posts.push(`${u.hostname}${u.pathname}`);
|
|
21
|
+
const p = JSON.parse(init.body);
|
|
22
|
+
return json({ id: p.spec.id, state: "running" }, u.pathname === "/warm/claim" ? 200 : 201);
|
|
23
|
+
};
|
|
24
|
+
const router = createRouter({ state_dir: tmpDir("cs-aff-"), lane: { cpus: 2, mem_gb: 3 }, enroll_token: "e", forgedock_token: "fd", repos }, { fetchFn, now: () => 5_000_000, log: quiet });
|
|
25
|
+
for (const n of hosts) router.store.data.agents[n] = { url: `http://${n}:7711`, token: "t" };
|
|
26
|
+
return { router, posts };
|
|
27
|
+
}
|
|
28
|
+
const placed = async (router, id, slug) => (await router.launch(spec(id, slug))).body.agent;
|
|
29
|
+
|
|
30
|
+
test("allowlist: every launch for the repo goes to an allowed agent", async () => {
|
|
31
|
+
const { router } = fixture({ "o/x": { agents: ["b"] } });
|
|
32
|
+
for (let i = 0; i < 3; i++) assert.equal(await placed(router, `l${i}`, "o/x"), "b");
|
|
33
|
+
assert.equal(await placed(router, "other", "o/y"), "a"); // another repo is unrestricted
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("allowlist with no live allowed agent defers, never lands elsewhere", async () => {
|
|
37
|
+
const { router, posts } = fixture({ "o/x": { agents: ["zz"] } });
|
|
38
|
+
const r = await router.launch(spec("d1"));
|
|
39
|
+
assert.equal(r.status, 503);
|
|
40
|
+
assert.deepEqual(posts, []);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("exclude list and both combine", async () => {
|
|
44
|
+
assert.equal(await placed(fixture({ "o/x": { exclude_agents: ["a"] } }).router, "e1", "o/x"), "b");
|
|
45
|
+
const { router } = fixture({ "o/x": { agents: ["a", "b"], exclude_agents: ["a"] } });
|
|
46
|
+
assert.equal(await placed(router, "e2", "o/x"), "b");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("unset, empty or non-array config keeps today's placement (best host first)", async () => {
|
|
50
|
+
for (const repos of [{}, { "o/x": {} }, { "o/x": { agents: [] } }, { "o/x": { agents: "b" } }]) {
|
|
51
|
+
assert.equal(await placed(fixture(repos).router, "u1", "o/x"), "a");
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("claim honours the allowlist", async () => {
|
|
56
|
+
const { router, posts } = fixture({ "o/x": { agents: ["c"] } });
|
|
57
|
+
const r = await router.claim(spec("c1"));
|
|
58
|
+
assert.equal(r.body.agent, "c");
|
|
59
|
+
assert.deepEqual(posts, ["c/warm/claim"]);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("seed pick honours the allowlist", async () => {
|
|
63
|
+
const { router, posts } = fixture({ "o/x": { agents: ["b"] } });
|
|
64
|
+
const call = (method, path, body) => new Promise((resolve) => {
|
|
65
|
+
const r = Readable.from(body ? [Buffer.from(JSON.stringify(body))] : []);
|
|
66
|
+
Object.assign(r, { method, url: path, headers: { authorization: "Bearer fd", "content-type": "application/json" }, socket: { remoteAddress: "127.0.0.1" } });
|
|
67
|
+
const chunks = []; const res = { writeHead() { return res; }, setHeader() {}, write(c) { chunks.push(c); }, end(c) { if (c) chunks.push(c); resolve(Buffer.concat(chunks.map(Buffer.from)).toString()); } };
|
|
68
|
+
router.handle(r, res);
|
|
69
|
+
});
|
|
70
|
+
await call("POST", "/sandboxes/s1/seed", { slug: "o/x", data_b64: "AA" });
|
|
71
|
+
assert.deepEqual(posts, ["b/mirrors/seed"]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("status(repo) counts only the allowed agents; no repo counts all", async () => {
|
|
75
|
+
const { router } = fixture({ "o/x": { agents: ["b", "c"], exclude_agents: ["c"] } });
|
|
76
|
+
assert.equal((await router.status()).total, 3);
|
|
77
|
+
const s = await router.status("o/x");
|
|
78
|
+
assert.equal(s.total, 1); assert.equal(s.online, 1); assert.equal(s.agents[0].name, "b");
|
|
79
|
+
assert.equal((await router.status("o/y")).total, 3);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("transport.capacity appends ?repo= to /status and /agents only when a repo is given", async () => {
|
|
83
|
+
const urls = [];
|
|
84
|
+
const fetchFn = async (url) => { urls.push(url); return json({ agents: [{ ok: true, name: "a" }] }); };
|
|
85
|
+
const t = httpTransport({ endpoint: "http://pool", fetchFn });
|
|
86
|
+
await t.capacity();
|
|
87
|
+
assert.deepEqual(urls, ["http://pool/status", "http://pool/agents"]);
|
|
88
|
+
urls.length = 0;
|
|
89
|
+
await t.capacity({ repo: "o/x y" });
|
|
90
|
+
assert.deepEqual(urls, ["http://pool/status?repo=o%2Fx%20y", "http://pool/agents?repo=o%2Fx%20y"]);
|
|
91
|
+
});
|
package/bin/pool/agent.mjs
CHANGED
|
@@ -6,7 +6,7 @@ const LANE_BUILD_RETRY_AFTER_S = 300;
|
|
|
6
6
|
import { randomBytes } from "node:crypto";
|
|
7
7
|
import { execFile, spawn } from "node:child_process";
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, statfsSync, lstatSync, writeFileSync } from "node:fs";
|
|
10
10
|
import { basename, dirname, join } from "node:path";
|
|
11
11
|
import { cpus, hostname } from "node:os";
|
|
12
12
|
import { bearerOk, call, readJson, route, sameSecret, send } from "./http.mjs";
|
|
@@ -14,13 +14,30 @@ import { repoRoot, versionOf, laneImageTag, laneBuildArgs } from "./version.mjs"
|
|
|
14
14
|
import { jsonStore } from "./store.mjs";
|
|
15
15
|
import { makeWarm } from "./warm.mjs";
|
|
16
16
|
import { resolveLaneImage, laneImageNow, laneToolsTag, isLaneToolsTagOf } from "./lane-tools.mjs";
|
|
17
|
+
import { projectLayerTag, projectLayerImageNow, isProjectLayerTagOf } from "./project-layer.mjs";
|
|
17
18
|
import { hostDiskFree, hostMemFree, ensureNatPin, netState } from "./health.mjs";
|
|
18
19
|
import { laneDiskUsedGb, planDiskCap, fstrimDue, runFstrim } from "./disk.mjs";
|
|
20
|
+
import { step as laneStep, drainState, pressured } from "./lane-target.mjs";
|
|
19
21
|
import { makeMirrorSeed, dockerRunner } from "./mirror-seed.mjs";
|
|
20
22
|
import { planIdleEviction, CACHE_LABEL, agentLabel } from "./cache-sweep.mjs";
|
|
23
|
+
import { cpuQuotaEnv } from "./docker.mjs";
|
|
21
24
|
|
|
22
25
|
const LABEL = "computeshare=1";
|
|
26
|
+
/** #5695: ephemeral CI runner containers; a different label than LABEL so the orphan reaper never removes them. */
|
|
27
|
+
const RUNNER_LABEL = "computeshare.runner=1";
|
|
28
|
+
const RUNNER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
29
|
+
const netSample = { at: 0, rx: 0 };
|
|
30
|
+
/** Host RX rate in MB/s since the previous call (null on the first call or when /proc/net/dev is unreadable). */
|
|
31
|
+
export function netRx(now = Date.now(), read = () => readFileSync("/proc/net/dev", "utf8")) {
|
|
32
|
+
try {
|
|
33
|
+
const rx = read().split("\n").slice(2).map((l) => l.trim().split(/[:\s]+/)).filter((c) => c[0] && c[0] !== "lo").reduce((a, c) => a + (Number(c[1]) || 0), 0);
|
|
34
|
+
const prev = { ...netSample }; netSample.at = now; netSample.rx = rx;
|
|
35
|
+
return prev.at && now > prev.at && rx >= prev.rx ? { rx_mbps: Math.round(((rx - prev.rx) / 1e6 / ((now - prev.at) / 1000)) * 100) / 100 } : null;
|
|
36
|
+
} catch { return null; }
|
|
37
|
+
}
|
|
23
38
|
const LOG_CHUNK = 256 * 1024;
|
|
39
|
+
const RUNS_IN_SANDBOX = "/root/.forge/runs/."; // #6117: where the lane engine writes its run log (docker cp source)
|
|
40
|
+
const RUNLOG_MAX = 20 * 1024 * 1024, TAIL_LINES = 200, GRAVE_LOG_MAX = 1024 * 1024;
|
|
24
41
|
const run = promisify(execFile);
|
|
25
42
|
|
|
26
43
|
/** What this machine/VM actually has (on WSL: the VM caps from .wslconfig). */
|
|
@@ -55,6 +72,15 @@ export function liveHeadroom(cfg = {}) {
|
|
|
55
72
|
} catch { return { ok: true }; }
|
|
56
73
|
}
|
|
57
74
|
export const dindName = (name) => `${name}-dind`;
|
|
75
|
+
/** #6062: rolls usageView rows up for one worker: admitted (reserved) vs used (summed lane avg and peak) and the utilization ratios. Read-only; null ratios when nothing is reserved. */
|
|
76
|
+
export function usageSummary(rows) {
|
|
77
|
+
const f = (x) => Math.round(x * 100) / 100, list = (rows ?? []).filter((r) => r && r.reserved);
|
|
78
|
+
const sum = (g) => f(list.reduce((a, r) => a + (Number.isFinite(g(r)) ? g(r) : 0), 0));
|
|
79
|
+
const admitted = { cpus: sum((r) => r.reserved.cpus), mem_gb: sum((r) => r.reserved.mem_gb) };
|
|
80
|
+
const used = { cpu_avg: sum((r) => r.cpu_avg), cpu_peak: sum((r) => r.cpu_peak), mem_avg_gb: sum((r) => r.mem_avg_gb), mem_peak_gb: sum((r) => r.mem_peak_gb) };
|
|
81
|
+
const ratio = (u, d) => (d > 0 ? f(u / d) : null);
|
|
82
|
+
return { lanes: list.length, admitted, used, utilization: { cpu: ratio(used.cpu_avg, admitted.cpus), mem: ratio(used.mem_avg_gb, admitted.mem_gb) } };
|
|
83
|
+
}
|
|
58
84
|
export const workVolume = (name) => `cs-work-${name.replace(/^cs-/, "")}`;
|
|
59
85
|
/** #5696: the lane worktree is a plain dir on the cache volume (one mount), so depcache hardlinks never hit EXDEV. */
|
|
60
86
|
export const workDirOf = (name) => `/cache/work/${name.replace(/^cs-/, "")}`;
|
|
@@ -104,16 +130,43 @@ export async function buildWithRetry(build, { sleep = (ms) => new Promise((r) =>
|
|
|
104
130
|
}
|
|
105
131
|
}
|
|
106
132
|
|
|
133
|
+
const BURY_TIMEOUT_MS = 30000; // evidence copy before a destroy (run logs out of the container) never holds the destroy longer
|
|
134
|
+
/** An fd for a regular file a lane may have written, opened without following a symlink and without blocking on a FIFO; null otherwise. Caller closes it. */
|
|
135
|
+
export function openLaneFile(path) {
|
|
136
|
+
let fd = null;
|
|
137
|
+
try {
|
|
138
|
+
if (!lstatSync(path).isFile()) return null;
|
|
139
|
+
fd = openSync(path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0));
|
|
140
|
+
if (fstatSync(fd).isFile()) return fd;
|
|
141
|
+
} catch { /* gone, a link, or not a file */ }
|
|
142
|
+
if (fd !== null) { try { closeSync(fd); } catch { /* closed */ } }
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
/** A regular file the lane may have written, read without following symlinks (a lane can plant a link to a host file); "" otherwise. */
|
|
146
|
+
export function readLaneFile(path) {
|
|
147
|
+
const fd = openLaneFile(path);
|
|
148
|
+
if (fd === null) return "";
|
|
149
|
+
try { return readFileSync(fd, "utf8"); } catch { return ""; } finally { try { closeSync(fd); } catch { /* closed */ } }
|
|
150
|
+
}
|
|
107
151
|
export function createAgent(cfg, { docker, now = () => Date.now(), log = console, live = liveHeadroom, hostDisk = null, hostMem = null, net = netState, vm = vmSize, trim = runFstrim, mirrorRunner = null } = {}) {
|
|
108
152
|
const stateDir = cfg.state_dir;
|
|
109
153
|
const store = jsonStore(join(stateDir, "state.json"), { sandboxes: {} });
|
|
110
154
|
const sb = () => store.data.sandboxes;
|
|
155
|
+
const usageView = (r) => {
|
|
156
|
+
const u = r.usage; const f = (x) => Math.round(x * 100) / 100;
|
|
157
|
+
return u?.samples ? { reserved: { cpus: r.cpus, mem_gb: r.mem_gb }, cpu_avg: f(u.cpu_sum / u.samples), cpu_peak: f(u.cpu_peak), mem_avg_gb: f(u.mem_sum / u.samples), mem_peak_gb: f(u.mem_peak), samples: u.samples } : null;
|
|
158
|
+
};
|
|
159
|
+
let pendingResize = null;
|
|
160
|
+
const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
|
|
161
|
+
let warm; // assigned below once launch/destroy exist
|
|
111
162
|
const activeRecs = () => Object.values(sb()).filter((s) => s.state !== "exited");
|
|
112
163
|
// Sandbox ids come from requests: read own keys only, so "__proto__" or "constructor" never resolves to an inherited member (#4566).
|
|
113
164
|
const own = (id) => (typeof id === "string" && Object.hasOwn(sb(), id) ? sb()[id] : warm.byAlias(id)); // #4912: a claimed warm sandbox also answers to its lane id
|
|
114
165
|
const leaseTtlMs = (cfg.lease_ttl_s ?? 600) * 1000;
|
|
115
166
|
const maxLifeMs = (cfg.max_lifetime_s ?? 6 * 3600) * 1000;
|
|
116
167
|
const keepExitedMs = (cfg.keep_exited_s ?? 2 * 3600) * 1000;
|
|
168
|
+
const keepLogMs = (cfg.keep_log_s ?? 600) * 1000; // #6117: a destroyed sandbox's last log, run log and result stay readable this long, so a late fetch still works
|
|
169
|
+
const graveyard = new Map(); // sandbox id -> {until, log: {from, size, text}, tail, runLog, result}
|
|
117
170
|
const keepPressureMs = (cfg.keep_disk_pressure_s ?? 24 * 3600) * 1000; // #5891: a disk-pressure stop keeps its worktree long enough for the requeue
|
|
118
171
|
const running = versionOf(cfg.code_root ?? repoRoot);
|
|
119
172
|
// The lane image tracks the installed ForgeDock version; only an explicit non-legacy cfg.image overrides it.
|
|
@@ -172,7 +225,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
172
225
|
if (rows.length < (cfg.estimate_min_samples ?? 3)) return { cpus: slice.cpus, mem: slice.mem, samples: rows.length };
|
|
173
226
|
return { cpus: Math.max(slice.cpus, pct(rows.map((x) => x.cpu_avg), 0.75)), mem: Math.max(slice.mem, pct(rows.map((x) => x.mem_peak_gb), 0.9)), samples: rows.length };
|
|
174
227
|
}
|
|
175
|
-
const
|
|
228
|
+
const runners = () => (store.data.runners ??= {}); // #5695: name -> {label, cpus, mem_gb, startedAt}; counted like a lane
|
|
229
|
+
const used = () => Object.values({ ...sb(), ...Object.fromEntries(Object.entries(runners()).map(([k, r]) => [`runner:${k}`, { cpus: r.cpus, mem_gb: r.mem_gb }])) }).filter((s) => s.state !== "exited").reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
176
230
|
// #5535: disk figures for the router inventory; optional, omitted when unreadable. Sandbox dirs are walked at most every 60s.
|
|
177
231
|
let diskCache = { at: 0, mb: {} };
|
|
178
232
|
let lastWorkSweep = -Infinity;
|
|
@@ -263,7 +317,55 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
263
317
|
const PRIORITIES = ["reserved", "normal", "borrow"];
|
|
264
318
|
const reservations = () => (Array.isArray(cfg.reservations) ? cfg.reservations.filter((r) => r && typeof r.name === "string" && r.cpus > 0 && r.mem_gb > 0) : []);
|
|
265
319
|
const prioOf = (r) => r.priority ?? "normal";
|
|
266
|
-
const
|
|
320
|
+
const peakUse = () => activeRecs().reduce((a, r) => { const e = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }); return { cpus: a.cpus + Math.max(r.cpus, e.cpus), mem: a.mem + Math.max(r.mem_gb, e.mem) }; }, { cpus: 0, mem: 0 });
|
|
321
|
+
// #6047: heavy tokens (cfg.elastic_lanes, default off). A lane is admitted on its base reservation; each heavy step leases a token
|
|
322
|
+
// (weight = max(default, p90 history - base)) from this host's pool. Tokens live in store.data.heavy and expire with their lease,
|
|
323
|
+
// when the sandbox exits or when it is destroyed.
|
|
324
|
+
const elastic = () => cfg.elastic_lanes === true;
|
|
325
|
+
const heavyTtlMs = () => (cfg.heavy_ttl_s ?? 300) * 1000;
|
|
326
|
+
const heavyDefault = () => ({ cpus: cfg.heavy_weight?.cpus ?? 1, mem: cfg.heavy_weight?.mem_gb ?? 2 });
|
|
327
|
+
const heavyTokens = () => (store.data.heavy ??= {});
|
|
328
|
+
function heavyHeld() {
|
|
329
|
+
let dropped = false;
|
|
330
|
+
for (const [k, t] of Object.entries(heavyTokens())) { const r = sb()[t.sandbox]; if (t.expires <= now() || !r || r.state === "exited") { delete heavyTokens()[k]; dropped = true; } }
|
|
331
|
+
if (dropped) store.save();
|
|
332
|
+
return Object.values(heavyTokens()).reduce((a, t) => ({ cpus: a.cpus + t.cpus, mem: a.mem + t.mem, n: a.n + 1 }), { cpus: 0, mem: 0, n: 0 });
|
|
333
|
+
}
|
|
334
|
+
const baseUse = () => activeRecs().reduce((a, r) => ({ cpus: a.cpus + r.cpus, mem: a.mem + r.mem_gb }), { cpus: 0, mem: 0 });
|
|
335
|
+
/** Elastic: base reservations plus held tokens; flat: each lane's projected peak (#5858). */
|
|
336
|
+
const projectedUse = () => { if (!elastic()) return peakUse(); const b = baseUse(), h = heavyHeld(); return { cpus: b.cpus + h.cpus, mem: b.mem + h.mem }; };
|
|
337
|
+
/** Lane ceiling derived from the token pool when elastic: a multiple of the default-weight heavy steps the host holds. */
|
|
338
|
+
function derivedCeiling() {
|
|
339
|
+
const e = effectiveCapacity(), w = heavyDefault();
|
|
340
|
+
return Math.max(1, Math.floor(Math.min((e.cpus - coTenant.cpus) / w.cpus, (e.mem - coTenant.mem_gb) / w.mem) * (cfg.elastic_lane_factor ?? 3)));
|
|
341
|
+
}
|
|
342
|
+
function heavyAcquire(r) {
|
|
343
|
+
const held = heavyHeld(), mine = Object.entries(heavyTokens()).find(([, t]) => t.sandbox === r.id);
|
|
344
|
+
const ttl = Math.round(heavyTtlMs() / 1000);
|
|
345
|
+
if (mine) { mine[1].refs = (mine[1].refs ?? 1) + 1; mine[1].expires = now() + heavyTtlMs(); store.save(); return { status: 200, body: { granted: true, token: mine[0], ttl_s: ttl } }; }
|
|
346
|
+
const est = estimateFor(r.repo ?? null, { cpus: r.cpus, mem: r.mem_gb }), d = heavyDefault();
|
|
347
|
+
const w = { cpus: Math.max(d.cpus, est.cpus - r.cpus), mem: Math.max(d.mem, est.mem - r.mem_gb) };
|
|
348
|
+
const e = effectiveCapacity(), b = baseUse(), live_ = live(cfg), ram = Number.isFinite(live_?.mem_available_gb) ? live_.mem_available_gb : Infinity;
|
|
349
|
+
const fits = b.cpus + held.cpus + w.cpus <= e.cpus - coTenant.cpus + 1e-9 && b.mem + held.mem + w.mem <= e.mem - coTenant.mem_gb + 1e-9 && w.mem <= ram + 1e-9;
|
|
350
|
+
if (held.n > 0 && !fits) return { status: 200, body: { granted: false, retry_after_s: 15, held: held.n } }; // the first holder always runs: a step larger than the host must not starve
|
|
351
|
+
const token = randomBytes(12).toString("hex");
|
|
352
|
+
heavyTokens()[token] = { sandbox: r.id, cpus: w.cpus, mem: w.mem, at: now(), refs: 1, expires: now() + heavyTtlMs() };
|
|
353
|
+
store.save();
|
|
354
|
+
return { status: 200, body: { granted: true, token, ttl_s: ttl, weight: { cpus: w.cpus, mem_gb: w.mem } } };
|
|
355
|
+
}
|
|
356
|
+
function heavyTouch(r, action, token) {
|
|
357
|
+
heavyHeld();
|
|
358
|
+
const t = heavyTokens()[token];
|
|
359
|
+
if (!t || t.sandbox !== r.id) return { status: 200, body: { ok: action === "release", granted: false } };
|
|
360
|
+
if (action === "release") { if ((t.refs = (t.refs ?? 1) - 1) <= 0) delete heavyTokens()[token]; } else t.expires = now() + heavyTtlMs();
|
|
361
|
+
store.save();
|
|
362
|
+
return { status: 200, body: { ok: true, granted: action === "renew" } };
|
|
363
|
+
}
|
|
364
|
+
function heavyView() {
|
|
365
|
+
if (!elastic()) return {};
|
|
366
|
+
const h = heavyHeld(), e = effectiveCapacity(), b = baseUse();
|
|
367
|
+
return { elastic_lanes: true, heavy_tokens: h.n, heavy_held: { cpus: r2(h.cpus), mem_gb: r2(h.mem) }, cpus_free_elastic: r2(e.cpus - b.cpus - h.cpus - coTenant.cpus), mem_free_gb_elastic: r2(e.mem - b.mem - h.mem - coTenant.mem_gb), lanes_ceiling_derived: derivedCeiling() };
|
|
368
|
+
}
|
|
267
369
|
const sumRecs = (rs) => rs.reduce((a, s) => ({ cpus: a.cpus + s.cpus, mem: a.mem + s.mem_gb }), { cpus: 0, mem: 0 });
|
|
268
370
|
const weighted = () => reservations().length > 0 || Boolean(cfg.idle_only);
|
|
269
371
|
const SHARES = () => ({ reserved: 4096, normal: 1024, borrow: 128, throttled: 2, ...(cfg.cpu_shares ?? {}) });
|
|
@@ -343,9 +445,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
343
445
|
}
|
|
344
446
|
/** #5886: a router-pushed policy (allowlisted keys, persisted beside the agent config). Its `paused` is separate from the owner's pause: the router can set or clear only its own, never the owner's. */
|
|
345
447
|
let policyPaused = Boolean(cfg.policy_paused);
|
|
448
|
+
const laneS = { target: null, greenSince: null, busySince: null };
|
|
449
|
+
const laneTargetOn = () => cfg.lane_autoscale !== false && Number.isInteger(cfg.max_lanes) && cfg.max_lanes >= 1;
|
|
450
|
+
const laneNow = () => laneS.target ?? Math.min(cfg.max_lanes, cfg.lane_start ?? 1);
|
|
346
451
|
function applyPolicy(body) {
|
|
347
452
|
const p = body && typeof body === "object" ? body : {}, int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi);
|
|
348
|
-
if ((p.cpus !== undefined && !int(p.cpus, 1, 256)) || (p.mem_gb !== undefined && !int(p.mem_gb, 1, 1024)) || (p.idle_only !== undefined && typeof p.idle_only !== "boolean") || (p.paused !== undefined && typeof p.paused !== "boolean")
|
|
453
|
+
if ((p.cpus !== undefined && !int(p.cpus, 1, 256)) || (p.mem_gb !== undefined && !int(p.mem_gb, 1, 1024)) || (p.idle_only !== undefined && typeof p.idle_only !== "boolean") || (p.paused !== undefined && typeof p.paused !== "boolean") || (p.elastic_lanes !== undefined && typeof p.elastic_lanes !== "boolean")
|
|
349
454
|
|| (p.floors !== undefined && !(p.floors && typeof p.floors === "object" && Object.keys(p.floors).every((k) => k === "host_disk_gb" && Number.isFinite(p.floors[k]) && p.floors[k] >= 0)))) return { status: 400, body: { error: "invalid policy" } };
|
|
350
455
|
const set = {};
|
|
351
456
|
if (p.cpus !== undefined) set.allow_cpus = p.cpus;
|
|
@@ -353,6 +458,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
353
458
|
if (p.idle_only !== undefined) set.idle_only = p.idle_only;
|
|
354
459
|
if (p.floors?.host_disk_gb !== undefined) set.host_disk_floor_gb = p.floors.host_disk_gb;
|
|
355
460
|
if (p.paused !== undefined) set.policy_paused = p.paused;
|
|
461
|
+
if (p.elastic_lanes !== undefined) set.elastic_lanes = p.elastic_lanes;
|
|
356
462
|
if (cfg.config_path) {
|
|
357
463
|
try { const c = JSON.parse(readFileSync(cfg.config_path, "utf8")); writeFileSync(cfg.config_path, JSON.stringify({ ...c, ...set }, null, 2), { mode: 0o600 }); }
|
|
358
464
|
catch (e) { log.warn?.(`policy not persisted: ${e.message}`); }
|
|
@@ -374,11 +480,12 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
374
480
|
const active = Object.values(sb()).filter((s) => s.state !== "exited").length;
|
|
375
481
|
const e = effectiveCapacity();
|
|
376
482
|
const h = live(cfg);
|
|
377
|
-
return { host: cfg.name ?? hostname(), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), net: readNet(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
483
|
+
return { host: cfg.name ?? hostname(), usage_summary: usageSummary(Object.values(sb()).filter((r) => r.state !== "exited").map(usageView)), ...running, vm: e.vm, ...(pendingResize ? { pending_resize: { cpus: pendingResize.cpus, mem_gb: pendingResize.mem_gb } } : {}), upgrading: upgrade.state, ...(upgrade.log && upgrade.state === "failed" ? { upgrade_log: upgrade.log } : {}), ...(upgrade.error ? { upgrade_error: upgrade.error } : {}), ...(prepull.error ? { prepull_error: prepull.error } : {}), ...(cacheErr.size ? { cache_sweep_error: [...cacheErr.values()][0] } : {}), ...(cacheInfo.size ? { cache_volumes: Object.fromEntries([...cacheInfo].map(([v, i]) => [v, { size_gb: Math.round(i.size_bytes / 107374182.4) / 10, ...(i.depcache_bytes ? { depcache_gb: Object.fromEntries(Object.entries(i.depcache_bytes).map(([k, b]) => [k, Math.round(b / 107374182.4) / 10])) } : {}) }])) } : {}), cpus_total: e.cpus, mem_total_gb: e.mem, cpus_free: r2(e.cpus - u.cpus - coTenant.cpus), mem_free_gb: r2(e.mem - u.mem - coTenant.mem_gb), configured: { cpus: cfg.allow_cpus, mem_gb: cfg.allow_mem_gb }, clamped: e.clamped, ...(coTenant.cpus || coTenant.mem_gb ? { cotenant: { cpus: r2(coTenant.cpus), mem_gb: r2(coTenant.mem_gb) } } : {}), active, ...priorityView(), ...throttleView(h), ...diskView(), ...laneDiskView(), ...hostDiskView(active), ...hostMemView(), ...heavyView(), runners: Object.entries(runners()).map(([name, r]) => ({ name, label: r.label })), net: (() => { const rx = netRx(now()); const n = readNet(); return rx ? { ...(n ?? {}), ...rx } : n; })(), paused: Boolean(cfg.paused || ownerPaused || policyPaused), owner_paused: ownerPaused, ...laneTargetView(), ...(Number.isFinite(h?.load_per_core) ? { load_per_core: h.load_per_core } : {}), ...(Number.isFinite(h?.mem_available_gb) ? { mem_available_gb: h.mem_available_gb } : {}), live: h, usage: Object.fromEntries(Object.values(sb()).filter((r) => r.usage?.samples).map((r) => [r.issue ?? r.id, { ...usageView(r), state: r.state }])) };
|
|
378
484
|
}
|
|
379
485
|
|
|
380
486
|
/** The image a spec's lanes run (the per-repo lane_tools tag when tools are listed), without building it. */
|
|
381
|
-
const
|
|
487
|
+
const laneBaseOf = (spec) => (spec.lane_tools?.length ? laneToolsTag(spec.image ?? image, spec.lane_tools) : (spec.image ?? image));
|
|
488
|
+
const envImageOf = (spec) => (spec.project_deps?.hash ? projectLayerTag(laneBaseOf(spec), spec.project_deps.hash) : laneBaseOf(spec));
|
|
382
489
|
const envEnsured = new Map(); // cache volume -> last ensure start
|
|
383
490
|
/**
|
|
384
491
|
* env.snapshots: start the snapshot helper for the repo, at most once per ENV_ENSURE_GAP_MS and one at a time per cache
|
|
@@ -391,6 +498,36 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
391
498
|
return Promise.resolve().then(() => docker.run(args)).then(() => log.info?.(`env snapshot helper started for ${spec.repo.slug}`), (e) => log.warn?.(`env snapshot helper: ${String(e.stderr || e.message).slice(0, 200)}`));
|
|
392
499
|
}
|
|
393
500
|
|
|
501
|
+
/** #5695: start one --ephemeral runner from a JIT config (one job, then the container exits and --rm removes it). */
|
|
502
|
+
async function startRunner({ name, label, jitconfig, cpus = 1, mem_gb = 2 } = {}) {
|
|
503
|
+
if (typeof name !== "string" || !RUNNER_NAME.test(name) || typeof label !== "string" || !RUNNER_NAME.test(label) || typeof jitconfig !== "string" || !/^[A-Za-z0-9+/=_-]+$/.test(jitconfig)) throw Object.assign(new Error("name, label and jitconfig are required"), { status: 400 });
|
|
504
|
+
if (!(cpus > 0 && mem_gb > 0)) throw Object.assign(new Error("cpus and mem_gb must be positive"), { status: 400 });
|
|
505
|
+
if (runners()[name]) return { status: 200, body: { name, state: "running" } };
|
|
506
|
+
const c = capacity();
|
|
507
|
+
if (c.paused || c.cpus_free < cpus || c.mem_free_gb < mem_gb) return { status: 503, body: { error: "no capacity", capacity: c }, retryAfter: 60 };
|
|
508
|
+
const dir = join(stateDir, "runners");
|
|
509
|
+
mkdirSync(dir, { recursive: true });
|
|
510
|
+
const envFile = join(dir, `${name}.env`); // the JIT config is a credential: an 0600 env file, never argv
|
|
511
|
+
writeFileSync(envFile, `ACTIONS_RUNNER_INPUT_JITCONFIG=${jitconfig}\n`, { mode: 0o600 });
|
|
512
|
+
try {
|
|
513
|
+
await docker.run(["--rm", "--name", `cs-runner-${name}`.slice(0, 120), "--label", RUNNER_LABEL, "--label", `computeshare.runner.label=${label}`, "--cpus", String(cpus), "--memory", `${Math.round(mem_gb * 1024)}m`, "--env-file", envFile, cfg.runner_image ?? "ghcr.io/actions/actions-runner:latest", "/home/runner/run.sh"]);
|
|
514
|
+
} finally { rmSync(envFile, { force: true }); }
|
|
515
|
+
runners()[name] = { label, cpus, mem_gb, startedAt: now() }; store.save();
|
|
516
|
+
return { status: 201, body: { name, state: "running" } };
|
|
517
|
+
}
|
|
518
|
+
async function stopRunner(name) {
|
|
519
|
+
if (!runners()[name]) return false;
|
|
520
|
+
try { await docker.remove(`cs-runner-${name}`.slice(0, 120)); } catch { /* already gone */ }
|
|
521
|
+
delete runners()[name]; store.save();
|
|
522
|
+
return true;
|
|
523
|
+
}
|
|
524
|
+
/** Forget runners whose container exited (an ephemeral runner ends after its job). */
|
|
525
|
+
async function sweepRunners() {
|
|
526
|
+
if (!Object.keys(runners()).length) return;
|
|
527
|
+
const live = new Set(await docker.listLabelled(RUNNER_LABEL));
|
|
528
|
+
for (const n of Object.keys(runners())) if (!live.has(`cs-runner-${n}`.slice(0, 120)) && now() - runners()[n].startedAt > 60000) delete runners()[n];
|
|
529
|
+
store.save();
|
|
530
|
+
}
|
|
394
531
|
/** cgroup cpu weight per class (docker --cpu-shares); a borrowed lane yields to a reserved one under contention. */
|
|
395
532
|
const sharesArgs = (prio) => (weighted() ? ["--cpu-shares", String(SHARES()[prio])] : []);
|
|
396
533
|
|
|
@@ -403,7 +540,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
403
540
|
} });
|
|
404
541
|
const seedFail = (e) => { if (e.status) throw Object.assign(new Error(e.message), { status: e.status, body: { error: e.message, ...(e.extra ?? {}) } }); throw e; };
|
|
405
542
|
|
|
406
|
-
async function launch({ spec, cpus, mem_gb, limit = null }) {
|
|
543
|
+
async function launch({ spec, cpus, mem_gb, limit = null, max_lanes = null }) {
|
|
407
544
|
if (typeof spec?.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(spec.id) || !Array.isArray(spec.command) || !spec.command.length) throw Object.assign(new Error("spec.id ([A-Za-z0-9._-], max 128) and spec.command are required"), { status: 400 });
|
|
408
545
|
let existing = own(spec.id);
|
|
409
546
|
if (existing?.drained && existing.state === "exited") { await destroy(existing.id, "drained: relaunch"); existing = null; } // #5856: the router/dispatcher rescheduled a drained lane under the same id
|
|
@@ -417,6 +554,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
417
554
|
const c = capacity();
|
|
418
555
|
const h = live(cfg);
|
|
419
556
|
const adm = admit({ prio, cpus, mem_gb, reservation, h });
|
|
557
|
+
if (c.draining && !c.paused) return { status: 503, body: { error: `draining: ${c.draining_reason}`, code: "pool.draining", capacity: c }, retryAfter: 60 }; // #6061: finish running lanes, accept none
|
|
558
|
+
if (laneTargetOn() && !c.paused && c.active >= laneNow()) return { status: 503, body: { error: `lane target ${laneNow()} reached (${c.active} running)`, code: "pool.lane_target", lane_target: laneNow(), capacity: c }, retryAfter: 60 };
|
|
420
559
|
if (c.paused || adm.refuse) {
|
|
421
560
|
const f = adm.refuse ?? {};
|
|
422
561
|
if (f.status === 400) return { status: 400, body: { error: f.error } };
|
|
@@ -425,10 +564,11 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
425
564
|
// Burst model: reservations are small, so also refuse when the VM is genuinely short of memory or overloaded right now.
|
|
426
565
|
// A reserved launch skips the load gate: it must never be refused because lanes are busy (they are throttled/drained below).
|
|
427
566
|
if (prio !== "reserved") { // #5858: ramp-aware: the admitted lanes' projected peaks plus this one must fit, however low the load is right now
|
|
428
|
-
const e = effectiveCapacity(), pu = projectedUse(), est = estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
|
|
567
|
+
const e = effectiveCapacity(), pu = projectedUse(), est = elastic() ? { cpus, mem: mem_gb } : estimateFor(slugOf(spec), { cpus, mem: mem_gb }), nm = Math.max(mem_gb, est.mem), nc = Math.max(cpus, est.cpus);
|
|
429
568
|
const availMem = e.mem - coTenant.mem_gb, availCpus = e.cpus - coTenant.cpus;
|
|
430
569
|
if (pu.mem + nm > availMem + 1e-9 || pu.cpus + nc > availCpus + 1e-9) return { status: 503, body: { error: `projected peak ${r1(pu.mem + nm)} GB / ${r1(pu.cpus + nc)} cpus exceeds capacity ${r1(availMem)} GB / ${r1(availCpus)} cpus`, code: "pool.projected_peak", capacity: c }, retryAfter: 60 };
|
|
431
570
|
}
|
|
571
|
+
if (elastic() && prio !== "reserved" && !Number.isInteger(max_lanes) && activeRecs().length >= derivedCeiling()) return { status: 503, body: { error: `derived lane ceiling ${derivedCeiling()} reached`, code: "pool.host_lane_ceiling", capacity: c }, retryAfter: 60 };
|
|
432
572
|
if (!h.ok && prio !== "reserved") return { status: 503, body: { error: `host busy: ${h.reason}`, code: "pool.host_load", live: h }, retryAfter: 60 };
|
|
433
573
|
const gate = hostDiskView(c.active, spec.repo?.slug ?? null);
|
|
434
574
|
if (gate.host_disk_low) { // #5733: before any mkdir or docker run; the lane defers on the 503 (SANDBOX_CAPACITY)
|
|
@@ -448,6 +588,14 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
448
588
|
if (st.building) return { status: 503, body: { error: `lane image ${st.tag} building`, code: "lane_tools.building" }, retryAfter: LANE_BUILD_RETRY_AFTER_S };
|
|
449
589
|
if (st.failed) return { status: 422, body: { error: st.failed, code: "lane_tools.build_failed" } };
|
|
450
590
|
}
|
|
591
|
+
// #6038: the project-deps layer builds in the background; a launch never waits for it and runs the lane image meanwhile.
|
|
592
|
+
let projectImage = null;
|
|
593
|
+
if (spec.project_deps?.hash) {
|
|
594
|
+
try {
|
|
595
|
+
const st = await projectLayerImageNow({ deps: spec.project_deps, baseImage: laneBaseOf(spec), docker });
|
|
596
|
+
if (st.image && st.image !== laneBaseOf(spec)) projectImage = st.image;
|
|
597
|
+
} catch (e) { log.warn?.(`project layer: ${String(e.message).slice(0, 200)}`); }
|
|
598
|
+
}
|
|
451
599
|
// Last refusal point passed: only now stop borrowed lanes (#5897), a launch refused above must not have drained any.
|
|
452
600
|
if (prio === "reserved") {
|
|
453
601
|
for (const r of tiers().act.filter((s) => prioOf(s) === "borrow")) await throttle(r, SHARES().throttled); // throttle every borrower first,
|
|
@@ -461,7 +609,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
461
609
|
const envFile = join(dir, "env");
|
|
462
610
|
const credToken = randomBytes(24).toString("hex");
|
|
463
611
|
const withDocker = Boolean(spec.docker);
|
|
464
|
-
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
612
|
+
const env = { ...(spec.env ?? {}), ...(withDocker ? { DOCKER_HOST: "tcp://127.0.0.1:2375" } : {}), ...(elastic() ? { CS_HEAVY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/heavy` } : {}), CS_CRED_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/creds`, CS_RELAY_BASE: `http://host.docker.internal:${cfg.listen.port}/sandboxes/${encodeURIComponent(spec.id)}/relay`, CS_CRED_TOKEN: credToken, CS_SANDBOX_ID: spec.id, ...cpuQuotaEnv(limit?.lane_cpus ?? cpus), CS_REPO_SLUG: spec.repo?.slug ?? "", CS_REPO_URL: spec.repo?.url ?? "", CS_REPO_REF: spec.repo?.ref ?? "", CS_RESULT_FILE: spec.result_file ?? "", CS_WORK_DIR: workDirOf(name),
|
|
465
613
|
...(spec.env_snapshots?.enabled ? { FORGE_ENV_IMAGE: envImageOf(spec) } : {}) }; // the image is part of the snapshot key
|
|
466
614
|
writeFileSync(envFile, Object.entries(env).map(([k, v]) => envLine(k, v)).join("\n") + "\n", { mode: 0o600 });
|
|
467
615
|
const rec = { id: spec.id, name, dir, issue: spec.issue ?? null, slug: spec.repo?.slug ?? null, repo: slugOf(spec), batch: spec.batch ?? null, cpus, mem_gb, result_file: spec.result_file ?? null, state: "starting", startedAt: now(), finishedAt: null, lease: now(), credToken, docker: withDocker, ...(weighted() || spec.priority ? { priority: prio, ...(reservation ? { reservation } : {}) } : {}) };
|
|
@@ -478,7 +626,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
478
626
|
const cacheMount = ["-v", `${rec.cacheVolume}:/cache`];
|
|
479
627
|
try {
|
|
480
628
|
// #5650: a repo's lane_tools select a derived image (built once per tool list); none keeps spec.image ?? image.
|
|
481
|
-
const
|
|
629
|
+
const toolsImage = spec.lane_tools?.length ? await resolveLaneImage({ tools: spec.lane_tools, baseImage: spec.image ?? image, docker }) : (spec.image ?? image);
|
|
630
|
+
const laneImage = projectImage ?? toolsImage; // #6038: the project layer sits on the tools image, or is skipped (base) while building
|
|
482
631
|
if (withDocker) {
|
|
483
632
|
// Private Docker daemon per sandbox (never the host socket). The lane joins its network namespace, so ports the
|
|
484
633
|
// project's compose stack publishes are on the lane's localhost, and the API listens on loopback only. Both share
|
|
@@ -506,6 +655,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
506
655
|
// Hard burst cap per container; the (smaller) reservation is only what placement counts.
|
|
507
656
|
// --memory-swap above --memory lets a rare spike page out instead of being OOM-killed (swap deal).
|
|
508
657
|
"--cpus", String(laneCpus), ...sharesArgs(prio), "--memory", mb(laneMem), "--memory-swap", mb(laneMem + swapFor(limit?.lane_swap_gb)), "--pids-limit", "4096",
|
|
658
|
+
"--init", // lane-compute audit 2026-11-26: PID 1 never reaped children (72–1408 zombies/lane in 17 min; the worst lane would reach the 4096 pid limit in ~50 min)
|
|
509
659
|
"--env-file", envFile, ...laneNet, ...work,
|
|
510
660
|
...(spec.claim_dir ? ["-v", `${join(dir, "claim")}:/claim`] : []), // #4912: warm sandboxes receive their lane here
|
|
511
661
|
...(withDocker ? [] : cacheMount), "-v", `${join(dir, "result")}:/result`, "-v", `${join(dir, "out")}:/csout`,
|
|
@@ -525,9 +675,8 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
525
675
|
return { status: 201, body: view(rec) };
|
|
526
676
|
}
|
|
527
677
|
|
|
528
|
-
const view = (r) => ({ id: r.id, state: r.state, issue: r.issue, cpus: r.cpus, mem_gb: r.mem_gb, started_at: new Date(r.startedAt).toISOString(), ...(r.error ? { error: r.error } : {}), ...(r.diskPaused ? { status_detail: "paused (disk)" } : {}), ...(r.memPaused ? { status_detail: "paused (host memory)" } : {}), ...(r.diskPressure ? { code: "sandbox.disk_pressure", status_detail: "stopped (disk pressure): worktree kept for resume" } : {}) });
|
|
529
678
|
|
|
530
|
-
|
|
679
|
+
warm = makeWarm({ store, sb, own, now, launch, destroy: (id, why) => destroy(id, why), view, log });
|
|
531
680
|
|
|
532
681
|
async function refresh(r) {
|
|
533
682
|
if (r.state === "exited") return r;
|
|
@@ -556,9 +705,54 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
556
705
|
try { return JSON.parse(readFileSync(join(r.dir, "result", basename(r.result_file)), "utf8")); } catch { return null; }
|
|
557
706
|
}
|
|
558
707
|
|
|
708
|
+
/** #6117: the lane's own run log (jsonl text, newest RUNLOG_MAX bytes), copied out of the container (running or exited); "" when unavailable. */
|
|
709
|
+
async function readRunLog(r) {
|
|
710
|
+
if (typeof docker.copyOut !== "function") return "";
|
|
711
|
+
let tmp = null;
|
|
712
|
+
try {
|
|
713
|
+
tmp = mkdtempSync(join(stateDir, "runlog-"));
|
|
714
|
+
await docker.copyOut(r.name, RUNS_IN_SANDBOX, tmp);
|
|
715
|
+
const want = new RegExp(`(^|__)${String(r.issue ?? "").replace(/[^\w.-]/g, "")}\\.jsonl$`);
|
|
716
|
+
const files = readdirSync(tmp).filter((f) => want.test(f) && (() => { try { return lstatSync(join(tmp, f)).isFile(); } catch { return false; } })());
|
|
717
|
+
if (!files.length) return "";
|
|
718
|
+
const text = readLaneFile(join(tmp, files.sort((a, b) => lstatSync(join(tmp, b)).size - lstatSync(join(tmp, a)).size)[0]));
|
|
719
|
+
if (text.length <= RUNLOG_MAX) return text;
|
|
720
|
+
const cut = text.slice(-RUNLOG_MAX); return cut.slice(cut.indexOf("\n") + 1); // whole lines only
|
|
721
|
+
} catch { return ""; } finally { if (tmp) rmSync(tmp, { recursive: true, force: true }); }
|
|
722
|
+
}
|
|
723
|
+
/** The last TAIL_LINES lines of the sandbox's lane log (its engine stderr/stdout). */
|
|
724
|
+
function logTail(r) {
|
|
725
|
+
const t = readLaneFile(join(r.dir, "out", "lane.log")); return t ? t.split("\n").slice(-(TAIL_LINES + 1)).join("\n") : "";
|
|
726
|
+
}
|
|
727
|
+
const grave = (id) => { const g = typeof id === "string" ? graveyard.get(id) : null; if (g && g.until <= now()) { graveyard.delete(id); return null; } return g ?? null; };
|
|
728
|
+
/** #6117: `{run_log, tail}` of a live sandbox, or of a destroyed one inside its grace period; null when unknown. */
|
|
729
|
+
async function evidence(id) {
|
|
730
|
+
const r = own(id);
|
|
731
|
+
if (r) return { run_log: await readRunLog(r), tail: logTail(r) };
|
|
732
|
+
const g = grave(id);
|
|
733
|
+
return g ? { run_log: g.runLog, tail: g.tail } : null;
|
|
734
|
+
}
|
|
735
|
+
/** Keeps what a late fetch needs once the container and its dir are gone. */
|
|
736
|
+
const GRAVE_MAX = 64; // destroyed sandboxes whose evidence is kept at once; the oldest goes first
|
|
737
|
+
async function bury(r) {
|
|
738
|
+
while (graveyard.size >= GRAVE_MAX) graveyard.delete(graveyard.keys().next().value);
|
|
739
|
+
try {
|
|
740
|
+
let text = "", size = 0;
|
|
741
|
+
const fd = openLaneFile(join(r.dir, "out", "lane.log")); // no symlink, no FIFO: a lane can plant either (#6145 delta review)
|
|
742
|
+
if (fd !== null) { try { size = fstatSync(fd).size; const len = Math.min(size, GRAVE_LOG_MAX); const buf = Buffer.alloc(len); readSync(fd, buf, 0, len, size - len); text = buf.toString("utf8"); } catch { /* no log */ } finally { closeSync(fd); } }
|
|
743
|
+
graveyard.set(r.id, { until: now() + keepLogMs, log: { from: size - Buffer.byteLength(text), size, text }, tail: logTail(r), runLog: await readRunLog(r), result: readResult(r) });
|
|
744
|
+
} catch { /* best effort: the destroy goes on */ }
|
|
745
|
+
}
|
|
746
|
+
function graveLog(g, cursor) {
|
|
747
|
+
const c = Math.max(Number(cursor) || 0, g.log.from);
|
|
748
|
+
if (c >= g.log.size) return { text: "", cursor: g.log.size };
|
|
749
|
+
return { text: Buffer.from(g.log.text).subarray(c - g.log.from).toString("utf8"), cursor: g.log.size };
|
|
750
|
+
}
|
|
751
|
+
|
|
559
752
|
async function destroy(id, why, { keepWork = false } = {}) {
|
|
560
753
|
const r = own(id);
|
|
561
754
|
if (!r) return false;
|
|
755
|
+
if (keepLogMs > 0) await Promise.race([bury(r), new Promise((res) => { const t = setTimeout(res, BURY_TIMEOUT_MS); t.unref?.(); })]); // #6117: before the container and its dir go; bounded so a hung copy never blocks the destroy
|
|
562
756
|
if (r.slug && r.diskPeakMb) { const h = (hist()[r.slug] ??= []); h.push(r.diskPeakMb); if (h.length > 50) h.shift(); }
|
|
563
757
|
const history = r.usage?.samples ? JSON.stringify({ at: new Date(now()).toISOString(), id: r.id, issue: r.issue, repo: r.repo ?? null, docker: Boolean(r.docker), minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10, ...usageView(r) }) : null;
|
|
564
758
|
await docker.remove(r.name);
|
|
@@ -593,7 +787,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
593
787
|
const keepN = Math.max(1, Number(cfg.keep_lane_images ?? 2) || 2);
|
|
594
788
|
const keep = [...bases.slice(0, keepN), laneImageTag(running.version), image, ...alsoKeep];
|
|
595
789
|
for (const t of tags) {
|
|
596
|
-
if (keep.some((b) => isLaneToolsTagOf(t, b)) || inUse.has(t)) continue;
|
|
790
|
+
if (keep.some((b) => isLaneToolsTagOf(t, b) || isProjectLayerTagOf(t, b)) || inUse.has(t)) continue;
|
|
597
791
|
try { await docker.removeImage(t); log.info?.(`removed superseded lane image ${t}`); } catch (e) { log.warn?.(`rmi ${t}: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
598
792
|
}
|
|
599
793
|
} catch (e) { log.warn?.(`lane image prune: ${String(e.stderr || e.message).slice(0, 200)}`); }
|
|
@@ -748,8 +942,28 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
748
942
|
if (!r.ok) log.warn?.(`fstrim: ${r.error}`);
|
|
749
943
|
}
|
|
750
944
|
|
|
945
|
+
// #6061: per-worker lane target, evaluated once per reap. Active only with an integer cfg.max_lanes (the ceiling) unless cfg.lane_autoscale is false.
|
|
946
|
+
// Draining refuses new launches only; running lanes are never stopped here (drainOne stays for idle_only borrowed lanes).
|
|
947
|
+
function laneDrain() {
|
|
948
|
+
const paused = Boolean(cfg.paused || ownerPaused || policyPaused);
|
|
949
|
+
return drainState({ paused, ownerPaused, policyPaused, busyForMs: laneS.busySince === null ? 0 : now() - laneS.busySince, drainAfterMs: (cfg.drain_busy_s ?? 300) * 1000 });
|
|
950
|
+
}
|
|
951
|
+
function laneTargetView() {
|
|
952
|
+
const d = laneDrain();
|
|
953
|
+
return { draining: d.draining, ...(d.reason ? { draining_reason: d.reason } : {}), accepting: !d.draining, ...(laneTargetOn() ? { lane_target: laneNow(), lane_ceiling: cfg.max_lanes } : {}) };
|
|
954
|
+
}
|
|
955
|
+
function laneTick() {
|
|
956
|
+
const h = live(cfg), t = now();
|
|
957
|
+
laneS.busySince = pressured(h) ? (laneS.busySince ?? t) : null;
|
|
958
|
+
if (!laneTargetOn()) { laneS.target = null; return; }
|
|
959
|
+
const r = laneStep({ target: laneNow(), ceiling: cfg.max_lanes, live: h, now: t, greenSince: laneS.greenSince, holdMs: (cfg.lane_hold_s ?? 60) * 1000 });
|
|
960
|
+
laneS.target = r.target; laneS.greenSince = r.greenSince;
|
|
961
|
+
if (r.change) log.info?.(`lane target ${r.change} to ${r.target}/${cfg.max_lanes}`);
|
|
962
|
+
}
|
|
963
|
+
|
|
751
964
|
async function reap() {
|
|
752
965
|
const t = now();
|
|
966
|
+
for (const id of [...graveyard.keys()]) grave(id); // #6117: expired grace entries go
|
|
753
967
|
for (const r of Object.values(sb())) {
|
|
754
968
|
try { await refresh(r); } catch { /* docker hiccup: judge by lease only */ }
|
|
755
969
|
const why = t - r.lease > leaseTtlMs && !r.diskPaused && !r.memPaused ? "lease expired" : t - r.startedAt > maxLifeMs ? "max lifetime" : r.state === "exited" && r.finishedAt && t - r.finishedAt > (r.diskPressure ? keepPressureMs : keepExitedMs) ? "exited retention" : null;
|
|
@@ -759,8 +973,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
759
973
|
await hostMemPressure(t); // #5967
|
|
760
974
|
const known = new Set(Object.values(sb()).flatMap((r) => [r.name, dindName(r.name)]));
|
|
761
975
|
for (const name of await docker.listLabelled(OWN)) if (!known.has(name)) { await docker.remove(name); log.info?.(`removed orphan container ${name}`); }
|
|
976
|
+
await sweepRunners().catch((e) => log.warn?.(`runner sweep: ${e.message}`));
|
|
762
977
|
await sampleUsage();
|
|
763
978
|
await reclaimIdle();
|
|
979
|
+
laneTick(); // #6061
|
|
764
980
|
await warm.maintain(maxLifeMs);
|
|
765
981
|
if (pendingResize && capacity().active === 0) {
|
|
766
982
|
const r = await resize(pendingResize);
|
|
@@ -844,7 +1060,10 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
844
1060
|
if (want.image !== running.image || want.version !== running.version) {
|
|
845
1061
|
const nextImage = cfg.image && cfg.image !== "computeshare-lane:1" ? cfg.image : laneImageTag(want.version);
|
|
846
1062
|
log.info?.(`rebuilding ${nextImage} (${running.version}/${running.image} -> ${want.version}/${want.image})`);
|
|
847
|
-
|
|
1063
|
+
// 2026-11-26: a host pre-seeded with the image (docker load from another host) skips the build: on a slow or memory-tight
|
|
1064
|
+
// host the build itself is the risk (an upgrade build coincided with a host crash)
|
|
1065
|
+
if (await docker.hasImage?.(nextImage)) log.info?.(`${nextImage} already present; no build`);
|
|
1066
|
+
else await buildWithRetry(() => docker.build(join(next, "pool", "image"), nextImage, laneBuildArgs(want.version)), { log }); // #5919
|
|
848
1067
|
}
|
|
849
1068
|
await pruneLaneImages([laneImageTag(want.version)]);
|
|
850
1069
|
await prepullImages();
|
|
@@ -889,11 +1108,6 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
889
1108
|
}
|
|
890
1109
|
store.save();
|
|
891
1110
|
}
|
|
892
|
-
const usageView = (r) => {
|
|
893
|
-
const u = r.usage; const f = (x) => Math.round(x * 100) / 100;
|
|
894
|
-
return u?.samples ? { reserved: { cpus: r.cpus, mem_gb: r.mem_gb }, cpu_avg: f(u.cpu_sum / u.samples), cpu_peak: f(u.cpu_peak), mem_avg_gb: f(u.mem_sum / u.samples), mem_peak_gb: f(u.mem_peak), samples: u.samples } : null;
|
|
895
|
-
};
|
|
896
|
-
let pendingResize = null;
|
|
897
1111
|
async function resize(body) {
|
|
898
1112
|
const int = (v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi ? v : null);
|
|
899
1113
|
const cpus = int(body.cpus, 1, 256), mem = int(body.mem_gb, 1, 1024), vmCpus = int(body.vm_cpus ?? body.cpus, 1, 256), vmMem = int(body.vm_mem_gb ?? (body.mem_gb + 2), 2, 1024);
|
|
@@ -948,16 +1162,19 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
948
1162
|
|
|
949
1163
|
const routes = [
|
|
950
1164
|
[route("GET", "/health"), async () => ({ status: 200, body: { ok: true, ...capacity() } })],
|
|
951
|
-
[route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload") }).catch(seedFail) })], // #5949
|
|
1165
|
+
[route("GET", "/mirrors"), async (_p, _b, url) => ({ status: 200, body: await mirrors.tips({ slug: url.searchParams.get("slug"), cache_key: url.searchParams.get("cache_key"), upload: url.searchParams.get("upload"), uploader: url.searchParams.get("uploader") }).catch(seedFail) })], // #5949
|
|
952
1166
|
[route("POST", "/mirrors/seed"), async (_p, body) => { try { return { status: 200, body: body?.finish ? await mirrors.finish(body) : mirrors.chunk(body) }; } catch (e) { return { status: e.status ?? 500, body: { error: e.message, ...(e.extra ?? {}) } }; } }],
|
|
953
1167
|
[route("GET", "/capacity"), async () => ({ status: 200, body: capacity() })],
|
|
954
1168
|
[route("POST", "/sandboxes"), async (_p, body) => { const r = await launch(body ?? {}); if (Number.isInteger(body?.spec?.warm)) warm.replenish().catch((e) => log.warn?.(`warm replenish: ${e.message}`)); return r; }],
|
|
1169
|
+
[route("POST", "/runners"), async (_p, body) => startRunner(body ?? {})], // #5695
|
|
1170
|
+
[route("DELETE", "/runners/:name"), async ({ name }) => ((await stopRunner(name)) ? { status: 200, body: { ok: true } } : { status: 404, body: { state: "gone" } })],
|
|
955
1171
|
[route("GET", "/warm"), async () => ({ status: 200, body: { warm: warm.list() } })],
|
|
956
1172
|
[route("POST", "/warm"), async (_p, body) => { const r = warm.configure({ ...(body ?? {}), n: body?.n }); await warm.replenish(); return { status: 200, body: { ...r, warm: warm.list() } }; }],
|
|
957
1173
|
[route("POST", "/warm/claim"), async (_p, body) => warm.claim(body ?? {})],
|
|
958
1174
|
[route("GET", "/sandboxes/:id"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; await refresh(r); store.save(); return { status: 200, body: view(r) }; }],
|
|
959
|
-
[route("GET", "/sandboxes/:id/logs"), async ({ id }, _b, url) => { const r = own(id); return r ? { status: 200, body: readLog(r, url.searchParams.get("cursor")) } : { status: 404, body: { text: "", cursor: 0 } }; }],
|
|
960
|
-
[route("GET", "/sandboxes/:id/
|
|
1175
|
+
[route("GET", "/sandboxes/:id/logs"), async ({ id }, _b, url) => { const r = own(id), g = !r && grave(id); return r ? { status: 200, body: readLog(r, url.searchParams.get("cursor")) } : g ? { status: 200, body: graveLog(g, url.searchParams.get("cursor")) } : { status: 404, body: { text: "", cursor: 0 } }; }],
|
|
1176
|
+
[route("GET", "/sandboxes/:id/runlog"), async ({ id }) => { const e = await evidence(id); return e ? { status: 200, body: e } : { status: 404, body: { error: "no run log" } }; }], // #6117
|
|
1177
|
+
[route("GET", "/sandboxes/:id/result"), async ({ id }) => { const r = own(id); const x = r ? readResult(r) : grave(id)?.result; if (!x && r?.drained) return { status: 200, body: { drained: true, reason: r.drained } }; if (!x && r?.diskPressure) return { status: 200, body: { disk_pressure: true, code: "sandbox.disk_pressure", reason: "host drive below the hard floor" } }; /* #5891 */ return x ? { status: 200, body: x } : { status: 404, body: { error: "no result" } }; }], // #5856: a drained lane without its own result is reported so the dispatcher reschedules it
|
|
961
1178
|
[route("GET", "/sandboxes/:id/usage"), async ({ id }) => { const r = own(id); return r ? { status: 200, body: { minutes: Math.round((((r.finishedAt ?? now()) - r.startedAt) / 60000) * 10) / 10 } } : { status: 404, body: {} }; }],
|
|
962
1179
|
[route("POST", "/sandboxes/:id/lease"), async ({ id }) => { const r = own(id); if (!r) return { status: 404, body: { state: "gone" } }; r.lease = now(); store.save(); return { status: 200, body: { ok: true } }; }],
|
|
963
1180
|
// #5274: SIGTERM the lane (PID 1) so its teardown checkpoints and reports deferred run.interrupted; the sandbox is kept, never destroyed.
|
|
@@ -989,6 +1206,13 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
989
1206
|
if (cred) { const r = await sandboxCred(decodeURIComponent(cred[1]), cred[2], req); return send(res, r.status, r.body, r.retryAfter ? { "retry-after": String(r.retryAfter) } : {}); }
|
|
990
1207
|
const limited = req.method === "POST" && /^\/sandboxes\/([^/]+)\/creds\/claude\/limited$/.exec(url.pathname); // #5205
|
|
991
1208
|
if (limited) { const r = await sandboxCredLimited(decodeURIComponent(limited[1]), req, await readJson(req)); return send(res, r.status, r.body); }
|
|
1209
|
+
const heavy = req.method === "POST" && /^\/sandboxes\/([^/]+)\/heavy\/(acquire|release|renew)$/.exec(url.pathname); // #6047
|
|
1210
|
+
if (heavy) {
|
|
1211
|
+
const id = decodeURIComponent(heavy[1]);
|
|
1212
|
+
if (!sandboxAuthed(id, req)) return send(res, SANDBOX_UNAUTHORIZED.status, SANDBOX_UNAUTHORIZED.body);
|
|
1213
|
+
const body = await readJson(req, 4096), r0 = own(id), r = heavy[2] === "acquire" ? heavyAcquire(r0) : heavyTouch(r0, heavy[2], body?.token);
|
|
1214
|
+
return send(res, r.status, r.body);
|
|
1215
|
+
}
|
|
992
1216
|
const relay = (req.method === "POST" && /^\/sandboxes\/([^/]+)\/relay$/.exec(url.pathname)) || (req.method === "GET" && /^\/sandboxes\/([^/]+)\/relay\/([^/]+)$/.exec(url.pathname));
|
|
993
1217
|
if (relay) { const r = await sandboxRelay(decodeURIComponent(relay[1]), relay[2] ? decodeURIComponent(relay[2]) : null, req); return send(res, r.status, r.body ?? {}); }
|
|
994
1218
|
if (url.pathname !== "/health" && !bearerOk(req, cfg.token)) return send(res, 401, { error: "unauthorized", hop: "agent", reason: "agent auth: router token rejected by agent" });
|
|
@@ -1014,7 +1238,7 @@ export function createAgent(cfg, { docker, now = () => Date.now(), log = console
|
|
|
1014
1238
|
await pruneLaneImages();
|
|
1015
1239
|
}
|
|
1016
1240
|
|
|
1017
|
-
return { handle, launch, warm, reap, destroy, capacity, refresh, store, prepullImages, ensureImage };
|
|
1241
|
+
return { handle, launch, warm, reap, destroy, capacity, refresh, store, prepullImages, ensureImage, evidence, graveLog: (id, cursor) => { const g = grave(id); return g ? graveLog(g, cursor) : null; } };
|
|
1018
1242
|
}
|
|
1019
1243
|
|
|
1020
1244
|
/**
|