forgedock 1.64.0 → 1.66.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.
@@ -0,0 +1,122 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) RapierCraft Studios
2
+ // SPDX-License-Identifier: AGPL-3.0-or-later
3
+ /**
4
+ * #5949: dispatcher-seeded repo mirrors. The agent receives a git bundle in checksummed chunks (resumable by offset) and applies
5
+ * it to the repo's bare mirror in the cache volume (`<cache>/git/<slug>.git`, the path entrypoint.sh and `env ensure` read):
6
+ * copy of the mirror (or a fresh bare repo) -> `git fetch <bundle>` -> `fsck --connectivity-only` -> rename into place, under a
7
+ * per-slug flock. Any failure removes the tmp copy and leaves the live mirror untouched. The git steps run in a helper container
8
+ * of the lane image that mounts the volume (`runner`); tests inject a runner that runs the same script on a local directory.
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ import { execFile } from "node:child_process";
12
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
13
+ import { join } from "node:path";
14
+
15
+ /** Per-chunk cap on the decoded payload; base64 of it stays under the 1 MB JSON body limit of the router and agent. */
16
+ export const SEED_CHUNK_MAX = 512 * 1024;
17
+ /** Abandoned uploads: a `.part` untouched this long is swept; one upload and all uploads together are capped (#5970). */
18
+ export const SEED_PART_TTL_MS = 60 * 60000;
19
+ export const SEED_UPLOAD_MAX = 2 * 1024 ** 3;
20
+ export const SEED_TOTAL_MAX = 4 * 1024 ** 3;
21
+ export const mirrorName = (slug) => String(slug).replace(/\//g, "_");
22
+ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9._-]+)?$/;
23
+ const SHA_RE = /^[a-f0-9]{64}$/;
24
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
25
+ const fail = (status, error, extra = {}) => Object.assign(new Error(error), { status, extra });
26
+
27
+ /** Lists the mirror's ref tips (`sha ref` lines), or prints ABSENT. Env: CACHE, NAME. */
28
+ export const TIPS_SCRIPT = 'm="$CACHE/git/$NAME.git"; if [ -d "$m" ]; then git -C "$m" for-each-ref --format="%(objectname) %(refname)" refs/heads refs/tags; else echo ABSENT; fi';
29
+ /** Applies $BUNDLE to the mirror atomically. Env: CACHE, NAME, BUNDLE. Exit non-zero leaves the live mirror as it was. */
30
+ export const APPLY_SCRIPT = `set -eu
31
+ m="$CACHE/git/$NAME.git"; t="$m.tmp"; old="$m.old"
32
+ mkdir -p "$CACHE/git"
33
+ exec 9>"$CACHE/git/$NAME.lock"
34
+ if command -v flock >/dev/null 2>&1; then flock 9; fi
35
+ cleanup() { rm -rf "$t"; }
36
+ trap cleanup EXIT
37
+ rm -rf "$t" "$old"
38
+ if [ -d "$m" ]; then cp -al "$m" "$t"; else git init --bare --quiet "$t"; fi
39
+ git -C "$t" bundle verify "$BUNDLE" >/dev/null
40
+ if git -C "$t" bundle list-heads "$BUNDLE" | grep -q ' refs/remotes/origin/'; then heads='+refs/remotes/origin/*:refs/heads/*'; else heads='+refs/heads/*:refs/heads/*'; fi
41
+ git -C "$t" fetch --quiet --no-tags "$BUNDLE" "$heads" '+refs/tags/*:refs/tags/*'
42
+ git -C "$t" fsck --connectivity-only --no-dangling >/dev/null
43
+ date +%s > "$t/cs-seeded"
44
+ if [ -d "$m" ]; then mv "$m" "$old"; fi
45
+ mv "$t" "$m"
46
+ rm -rf "$old"
47
+ trap - EXIT`;
48
+
49
+ /** Default runner: the script in a helper container of the lane image with the cache volume at /cache and the seed dir at /seed. */
50
+ export function dockerRunner({ volume, image, seedDir }) {
51
+ return (script, env) => new Promise((resolve, reject) => {
52
+ const e = { ...env, CACHE: "/cache", ...(env.BUNDLE ? { BUNDLE: `/seed/${env.BUNDLE}` } : {}) };
53
+ const args = ["run", "--rm", "--network", "none", "-v", `${volume}:/cache`, "-v", `${seedDir}:/seed:ro`, ...Object.entries(e).flatMap(([k, v]) => ["-e", `${k}=${v}`]), "--entrypoint", "bash", image, "-c", script];
54
+ execFile("docker", args, { timeout: 10 * 60000, maxBuffer: 1 << 24 }, (err, stdout, stderr) => (err ? reject(Object.assign(err, { stderr })) : resolve(String(stdout))));
55
+ });
56
+ }
57
+
58
+ /** Local runner (tests, and agents whose cache is a host directory): the same script on `root` as the cache dir. */
59
+ export function localRunner({ root, seedDir }) {
60
+ return (script, env) => new Promise((resolve, reject) => {
61
+ const e = { ...process.env, ...env, CACHE: root, ...(env.BUNDLE ? { BUNDLE: join(seedDir, env.BUNDLE) } : {}) };
62
+ execFile("bash", ["-c", script], { env: e, timeout: 10 * 60000, maxBuffer: 1 << 24 }, (err, stdout, stderr) => (err ? reject(Object.assign(err, { stderr })) : resolve(String(stdout))));
63
+ });
64
+ }
65
+
66
+ /** `runnerFor({slug, cache_key})` -> runner. Returns the agent's mirror seed handlers. */
67
+ export function makeMirrorSeed({ seedDir, runnerFor, partTtlMs = SEED_PART_TTL_MS, uploadMax = SEED_UPLOAD_MAX, totalMax = SEED_TOTAL_MAX }) {
68
+ mkdirSync(seedDir, { recursive: true });
69
+ const part = (up) => join(seedDir, `${up}.part`);
70
+ const size = (up) => { try { return statSync(part(up)).size; } catch { return 0; } };
71
+ /** Removes `.part` files idle past the TTL; returns the bytes the remaining ones hold. */
72
+ const sweep = () => {
73
+ let total = 0;
74
+ for (const n of readdirSync(seedDir)) {
75
+ if (!n.endsWith(".part")) continue;
76
+ try {
77
+ const st = statSync(join(seedDir, n));
78
+ if (Date.now() - st.mtimeMs > partTtlMs) rmSync(join(seedDir, n), { force: true }); else total += st.size;
79
+ } catch { /* removed concurrently */ }
80
+ }
81
+ return total;
82
+ };
83
+ sweep();
84
+ const check = (b) => {
85
+ if (typeof b?.slug !== "string" || !SLUG_RE.test(b.slug)) throw fail(400, "slug required");
86
+ if (typeof b.upload !== "string" || !SHA_RE.test(b.upload)) throw fail(400, "upload must be the bundle sha256");
87
+ };
88
+ return {
89
+ /** `GET /mirrors`: {mirrors: {slug: {ref: sha} | "absent"}, upload_offset?}. */
90
+ async tips({ slug, cache_key = null, upload = null }) {
91
+ if (typeof slug !== "string" || !SLUG_RE.test(slug)) throw fail(400, "slug required");
92
+ const out = String(await runnerFor({ slug, cache_key })(TIPS_SCRIPT, { NAME: mirrorName(slug) })).trim();
93
+ const mirror = out === "ABSENT" ? "absent" : Object.fromEntries(out.split("\n").filter(Boolean).map((l) => { const i = l.indexOf(" "); return [l.slice(i + 1), l.slice(0, i)]; }));
94
+ return { mirrors: { [slug]: mirror }, ...(upload && SHA_RE.test(upload) ? { upload_offset: size(upload) } : {}) };
95
+ },
96
+ /** One chunk: {slug, cache_key, upload, offset, data_b64, sha256}. A wrong offset is a 409 carrying the offset to resume from. */
97
+ chunk(b) {
98
+ check(b);
99
+ const buf = Buffer.from(String(b.data_b64 ?? ""), "base64");
100
+ if (!buf.length || buf.length > SEED_CHUNK_MAX) throw fail(413, `chunk must be 1..${SEED_CHUNK_MAX} bytes`);
101
+ if (sha256(buf) !== b.sha256) throw fail(422, "chunk checksum mismatch");
102
+ const have = size(b.upload);
103
+ if (b.offset !== have) throw fail(409, "offset mismatch", { offset: have });
104
+ if (have + buf.length > uploadMax) throw fail(413, `upload exceeds ${uploadMax} bytes`);
105
+ if (sweep() + buf.length > totalMax) throw fail(413, `seed dir exceeds ${totalMax} bytes`);
106
+ appendFileSync(part(b.upload), buf);
107
+ return { offset: have + buf.length };
108
+ },
109
+ /** Verifies the whole bundle against {size, sha256 = upload} and applies it. A corrupt upload is dropped; the mirror is never touched on failure. */
110
+ async finish(b) {
111
+ check(b);
112
+ const f = b.finish ?? {};
113
+ const have = size(b.upload);
114
+ if (!Number.isInteger(f.size) || have !== f.size) throw fail(409, "incomplete upload", { offset: have });
115
+ if (!existsSync(part(b.upload)) || sha256(readFileSync(part(b.upload))) !== b.upload) { rmSync(part(b.upload), { force: true }); throw fail(422, "bundle checksum mismatch"); }
116
+ try { await runnerFor(b)(APPLY_SCRIPT, { NAME: mirrorName(b.slug), BUNDLE: `${b.upload}.part` }); }
117
+ catch (e) { rmSync(part(b.upload), { force: true }); throw fail(422, `bundle apply failed: ${String(e.stderr || e.message).slice(-300)}`); }
118
+ rmSync(part(b.upload), { force: true });
119
+ return { ok: true, ...(await this.tips({ slug: b.slug, cache_key: b.cache_key })) };
120
+ },
121
+ };
122
+ }
@@ -242,6 +242,8 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
242
242
  }
243
243
  return out;
244
244
  }
245
+ /** #5967: host free memory and the other-VM (vmmem) working sets per agent. */
246
+ const memReport = (c) => Number.isFinite(c.host_mem_free_gb) ? { host_mem_free_gb: c.host_mem_free_gb, ...(Array.isArray(c.vmmem) && c.vmmem.length ? { vmmem: c.vmmem } : {}), ...(c.host_mem_low === true ? { host_mem_low: true } : {}) } : {};
245
247
  async function capacities() {
246
248
  const out = [];
247
249
  for (const [name, a] of Object.entries(agents())) {
@@ -256,7 +258,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
256
258
  /** Agent liveness for the scheduler (#4547): an agent is online when it answers and is not paused. */
257
259
  async function status() {
258
260
  const caps = await capacities();
259
- const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c) }));
261
+ const agentsView = caps.map((c) => ({ name: c.name, ok: c.ok, paused: Boolean(c.paused), transport: c.transport ?? "direct", ...diskReport(c), ...memReport(c) }));
260
262
  return { online: agentsView.filter((a) => a.ok && !a.paused).length, total: agentsView.length, agents: agentsView };
261
263
  }
262
264
 
@@ -329,6 +331,29 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
329
331
  return cpusFree >= size.cpus && memFree >= size.mem_gb;
330
332
  };
331
333
  const headroom = (c, spec) => (spec?.priority === "borrow" && Number.isFinite(c.cpus_free_unreserved) ? c.cpus_free_unreserved : 0);
334
+ // #5949: the dispatcher seeds a repo mirror before launch. The agent that will own the sandbox is picked here (the placing agent
335
+ // when it is known, else the best-fitting one) and remembered, so launch() prefers it and the seeded mirror is the one the lane uses.
336
+ const seedPick = new Map(); // sandbox id -> {agent, at}
337
+ const SEED_CHUNK_B64_MAX = 768 * 1024;
338
+ async function seedAgent(id) {
339
+ const known = own(sbx(), id);
340
+ if (known && own(agents(), known.agent)) return known.agent;
341
+ const hit = seedPick.get(id);
342
+ if (hit && own(agents(), hit.agent) && now() - hit.at < 30 * 60000) return hit.agent;
343
+ for (const [k, v] of seedPick) if (now() - v.at >= 30 * 60000) seedPick.delete(k);
344
+ const fits = (await capacities()).filter((c) => c.ok && !c.paused && c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
345
+ if (!fits.length) return null;
346
+ seedPick.set(id, { agent: fits[0].name, at: now() });
347
+ return fits[0].name;
348
+ }
349
+ async function seedForward(id, method, path, body) {
350
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(id)) return { status: 400, body: { error: "bad sandbox id" } };
351
+ if (typeof body?.data_b64 === "string" && body.data_b64.length > SEED_CHUNK_B64_MAX) return { status: 413, body: { error: "chunk too large" } };
352
+ const name = await seedAgent(id), a = name && own(agents(), name);
353
+ if (!a) return { status: 503, body: { error: "no agent available to seed" }, retryAfter: cfg.retry_after_s ?? 60 };
354
+ try { const r = await agentCall(a, method, path, body, 120000); return { status: r.status, body: agentBody(r, name) }; }
355
+ catch (e) { return { status: 502, body: { error: `agent ${name} unreachable: ${e.message}` } }; }
356
+ }
332
357
  /** #5886: a spec naming an account is placed only on that account's agents; without one, any enrolled agent (as before). */
333
358
  const inAccount = (c, spec) => typeof spec?.account !== "string" || own(agents(), c.name)?.account === spec.account;
334
359
  async function launch(spec) {
@@ -345,9 +370,12 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
345
370
  const sized = (await capacities()).filter((c) => c.ok && !c.paused && inAccount(c, spec) && fitsPriority(c, spec, size));
346
371
  const diskLow = sized.filter((c) => c.host_disk_low === true).map((c) => c.name); // #5733: never POST to a host whose drive is short
347
372
  const capped = sized.filter((c) => c.disk_capped === true && c.host_disk_low !== true).map((c) => c.name); // #5884: lane disk at its hard cap
348
- const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
373
+ const memLow = sized.filter((c) => c.host_mem_low === true && c.host_disk_low !== true && c.disk_capped !== true).map((c) => c.name); // #5967: host memory under the floor
374
+ const fits = sized.filter((c) => c.host_disk_low !== true && c.disk_capped !== true && c.host_mem_low !== true).sort((a, b) => headroom(b, spec) - headroom(a, spec) || b.cpus_free - a.cpus_free || b.mem_free_gb - a.mem_free_gb);
349
375
  const laneId = isLane(spec.id), laneCapped = []; // #5735: agents skipped because their lane ceiling is reached
350
376
  let busy = null; // the last agent 503 (e.g. lane_tools image building): its body and Retry-After are passed back
377
+ const seeded = seedPick.get(spec.id)?.agent; // #5949: the agent holding this lane's seeded mirror goes first
378
+ if (seeded) fits.sort((a, b) => (b.name === seeded) - (a.name === seeded));
351
379
  for (const c of fits) {
352
380
  if (laneId && atCeiling(c.name)) { laneCapped.push({ name: c.name, ...laneView(c.name) }); continue; }
353
381
  if (laneId) reserve(c.name, spec.id);
@@ -362,6 +390,7 @@ export function createRouter(cfg, { fetchFn = globalThis.fetch, now = () => Date
362
390
  if (busy) return { status: 503, body: { ...agentBody(busy.r, busy.name), agent: busy.name }, retryAfter: busy.r.retryAfter ?? cfg.retry_after_s ?? 60 };
363
391
  if (diskLow.length) return { status: 503, body: { error: "no host has free disk", code: "pool.disk_low", agents: diskLow }, retryAfter: cfg.disk_low_retry_after_s ?? 300 }; // a capacity deferral, not a failure
364
392
  if (capped.length) return { status: 503, body: { error: "no host has lane disk below its cap", code: "pool.disk_cap", agents: capped }, retryAfter: cfg.disk_low_retry_after_s ?? 300 };
393
+ if (memLow.length) return { status: 503, body: { error: "no host has free memory", code: "pool.host_mem", reason: "host_mem", agents: memLow }, retryAfter: cfg.host_mem_retry_after_s ?? 60 }; // a capacity deferral, not a failure
365
394
  return { status: 503, body: { error: "no host has a free reservation", lane: size }, retryAfter: cfg.retry_after_s ?? 60 };
366
395
  }
367
396
 
@@ -577,6 +606,8 @@ bash "$TMP/pool/install/install-agent-$OS.sh" "$@" --token "$CODE" --bundle "$TM
577
606
  [route("GET", "/health"), { fn: async () => ({ status: 200, body: { ok: true, agents: Object.keys(agents()).length, sandboxes: Object.keys(sbx()).length } }), auth: "none" }],
578
607
  [route("POST", "/sandboxes"), fd(async (_p, body) => launch(body))],
579
608
  [route("POST", "/sandboxes/claim"), fd(async (_p, body) => claim(body))],
609
+ [route("GET", "/sandboxes/:id/mirrors"), fd(async ({ id }, _b, url) => seedForward(id, "GET", `/mirrors?${new URLSearchParams([...url.searchParams].filter(([k]) => ["slug", "cache_key", "upload"].includes(k)))}`))], // #5949
610
+ [route("POST", "/sandboxes/:id/seed"), fd(async ({ id }, body) => seedForward(id, "POST", "/mirrors/seed", body))],
580
611
  [route("GET", "/sandboxes/:id"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}`))],
581
612
  [route("GET", "/sandboxes/:id/logs"), fd(async ({ id }, _b, url) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/logs?cursor=${encodeURIComponent(url.searchParams.get("cursor") ?? "0")}`))],
582
613
  [route("GET", "/sandboxes/:id/result"), fd(async ({ id }) => forward(id, "GET", `/sandboxes/${encodeURIComponent(id)}/result`))],
package/docs/CONFIG.md CHANGED
@@ -2950,6 +2950,7 @@ Keys of the pool agent's JSON config (`forgedock pool agent`), not of `forge.yam
2950
2950
  |---|---|---|---|
2951
2951
  | `cache_max_age_days` | number | `14` | uv/npm/pip/poetry cache files, depcache and env snapshot entries older than this are deleted by the agent sweep, with no launch needed. The pnpm store is pruned and the git mirror gets `git gc --auto`. |
2952
2952
  | `cache_max_gb` | number | unset (no cap) | Per-volume cap. A volume over it is shrunk oldest-first below the cap; work dirs of live sandboxes are never touched. |
2953
+ | `depcache_max_gb` | number | `40` | Per-repo cap on `forge-depcache/<repo>/` (#5901). Over it, the least recently used snapshots (by their `last-used` stamp) are deleted, never one held by a lane lock. `/capacity` `cache_volumes.<volume>.depcache_gb` and `forgedock pool status` show each repo's depcache size. Snapshots are also aged out per snapshot by `cache_max_age_days`. |
2953
2954
  | `cache_idle_days` | number | `30` | A volume with no launch for this long and no referencing sandbox is removed. Evicted only when its last use is known (`/cache/.last-used`, written by the lane entrypoint). |
2954
2955
  | `cache_never_evict` | list of volume names | `[]` | Volumes (e.g. `cs-cache-marcode`) that are never swept or evicted. |
2955
2956
  | `cache_sweep_interval_s` | number | `3600` | Gap between cache sweeps. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "forgedock",
3
- "version": "1.64.0",
3
+ "version": "1.66.0",
4
4
  "description": "An AI engineering team that ships to production",
5
5
  "bin": {
6
6
  "forgedock": "bin/forgedock.mjs"
@@ -17,7 +17,8 @@ date +%s > /cache/.last-used 2>/dev/null || true # #5757: the agent evicts cache
17
17
  exec > >(tee -a /csout/lane.log) 2>&1
18
18
 
19
19
  export HOME=/root
20
- export UV_CACHE_DIR=/cache/uv npm_config_cache=/cache/npm POETRY_CACHE_DIR=/cache/poetry PIP_CACHE_DIR=/cache/pip
20
+ # #5969: same layout as depcache.mjs env(); the legacy /cache/{uv,npm,pip,poetry} stay swept for old volumes.
21
+ export UV_CACHE_DIR=/cache/forge-depcache/stores/uv-cache npm_config_cache=/cache/forge-depcache/stores/npm-cache POETRY_CACHE_DIR=/cache/forge-depcache/stores/poetry-cache PIP_CACHE_DIR=/cache/forge-depcache/stores/pip-cache
21
22
  export TMPDIR=/tmp
22
23
  # ForgeDock's dependency cache (its pnpm store and snapshots) and pnpm's own store live in the persistent per-repo
23
24
  # cache volume, so a lane installs from a warm store instead of downloading every package (a cold monorepo install
@@ -45,6 +46,25 @@ checkout_repo() {
45
46
  if [ -n "${CS_REPO_URL:-}" ]; then
46
47
  # Shared bare mirror in the cache volume: later lanes fetch a delta instead of a full clone.
47
48
  mirror="/cache/git/$(echo "${CS_REPO_SLUG:-repo}" | tr '/' '_').git"
49
+ # #5949: a mirror seeded by the dispatcher (cs-seeded marker, written by the agent's atomic apply) is cloned from directly:
50
+ # no GitHub transfer is needed to start. Its fetch is best effort with retries, and skipped when it already has the lane ref.
51
+ if [ -f "$mirror/cs-seeded" ]; then
52
+ if [ -n "${CS_REPO_REF:-}" ] && git -C "$mirror" rev-parse --verify --quiet "refs/heads/$CS_REPO_REF" >/dev/null; then
53
+ echo "[computeshare] mirror seeded by the dispatcher; skipping the GitHub fetch"
54
+ else
55
+ for attempt in 1 2 3; do
56
+ timeout 90 git -C "$mirror" fetch --prune --quiet origin '+refs/heads/*:refs/heads/*' && break || { echo "[computeshare] GitHub fetch attempt $attempt failed (best effort)"; sleep $((attempt * 5)); }
57
+ done
58
+ fi
59
+ rm -rf /work/repo
60
+ if git clone --quiet --shared ${CS_REPO_REF:+--branch "$CS_REPO_REF"} "$mirror" /work/repo; then
61
+ git -C /work/repo remote set-url origin "$CS_REPO_URL" # pushes stay on GitHub
62
+ cd "$(readlink -f /work/repo)"
63
+ return 0
64
+ fi
65
+ echo "[computeshare] clone from the seeded mirror failed; falling back to GitHub"
66
+ rm -rf /work/repo
67
+ fi
48
68
  # #5947: mirror.sh validates (refs, no empty objects), quarantines a bad one, builds under a lock; `direct` = no --reference.
49
69
  use="$(/usr/local/bin/cs-mirror prepare "$CS_REPO_URL" "$mirror" 2>/dev/null || echo direct)"
50
70
  rm -rf /work/repo