fix: address review findings on the memory safeguards

- kill the whole process group on git/nixpacks timeout so a hung docker build
  cannot block the build queue
- mark interrupted cloning/building/starting installations as error on boot
- keep a running installation served while it rebuilds, including failed builds
- time out Docker image calls inside the build queue
- make session touch best-effort

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-19 05:31:08 +02:00
1 parent a999b8c694
commit 5fb1d6b0b4
12 files changed
+118 -23

No files matched your search

+3 -1
View File
@@ -2,13 +2,15 @@ import fs from "node:fs";
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import path from "node:path"; import path from "node:path";
import { config } from "../config/env.js"; import { config } from "../config/env.js";
import { killGroupAfter } from "../util/processTimeout.js";
// A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever. // A clone that never finishes (e.g. ssh waiting on a prompt) would otherwise hang forever.
const GIT_TIMEOUT_MS = 5 * 60 * 1000; const GIT_TIMEOUT_MS = 5 * 60 * 1000;
function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> { function run(cmd: string, args: string[], cwd?: string): Promise<{ code: number; output: string }> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const child = spawn(cmd, args, { cwd, timeout: GIT_TIMEOUT_MS }); const child = spawn(cmd, args, { cwd, detached: true });
killGroupAfter(child, GIT_TIMEOUT_MS);
let output = ""; let output = "";
child.stdout.on("data", (d) => (output += d.toString())); child.stdout.on("data", (d) => (output += d.toString()));
child.stderr.on("data", (d) => (output += d.toString())); child.stderr.on("data", (d) => (output += d.toString()));
+3 -1
View File
@@ -2,6 +2,7 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { config } from "../config/env.js"; import { config } from "../config/env.js";
import { killGroupAfter } from "../util/processTimeout.js";
export function buildLogPath(slug: string, buildId: string): string { export function buildLogPath(slug: string, buildId: string): string {
return path.join(config.logsDir, slug, `${buildId}.log`); return path.join(config.logsDir, slug, `${buildId}.log`);
@@ -86,7 +87,8 @@ export function runNixpacksBuild(
logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`); logStream.write(`[remote-mcp-manager] pinning NIXPACKS_NODE_VERSION=${nodeVersion}\n`);
} }
const child = spawn("nixpacks", args, { timeout: BUILD_TIMEOUT_MS }); const child = spawn("nixpacks", args, { detached: true });
killGroupAfter(child, BUILD_TIMEOUT_MS);
child.stdout.pipe(logStream, { end: false }); child.stdout.pipe(logStream, { end: false });
child.stderr.pipe(logStream, { end: false }); child.stderr.pipe(logStream, { end: false });
+17 -1
View File
@@ -10,7 +10,8 @@ process.env.DATA_DIR = tmpDir;
process.env.DB_PATH = path.join(tmpDir, "db.sqlite"); process.env.DB_PATH = path.join(tmpDir, "db.sqlite");
process.env.MASTER_KEY = "test-master-key-at-least-32-characters-long"; process.env.MASTER_KEY = "test-master-key-at-least-32-characters-long";
const { createInstallation, updateInstallation, getInstallationById, slugify } = await import("./installations.js"); const { createInstallation, updateInstallation, getInstallationById, slugify, reconcileInterruptedInstallations } =
await import("./installations.js");
describe("slugify", () => { describe("slugify", () => {
it("normalizes names into a URL/container-safe slug", () => { it("normalizes names into a URL/container-safe slug", () => {
@@ -59,3 +60,18 @@ describe("installations repository", () => {
expect(getInstallationById(installation.id)?.env).toEqual({ FOO: "bar", API_KEY: "shh" }); expect(getInstallationById(installation.id)?.env).toEqual({ FOO: "bar", API_KEY: "shh" });
}); });
}); });
describe("reconcileInterruptedInstallations", () => {
it("turns statuses that only a live process can advance into errors, and leaves the rest alone", () => {
const stuck = createInstallation({ name: "Stuck", slug: "stuck", repoUrl: "https://example.com/a.git" });
const fine = createInstallation({ name: "Fine", slug: "fine", repoUrl: "https://example.com/b.git" });
updateInstallation(stuck.id, { status: "starting" });
updateInstallation(fine.id, { status: "running" });
expect(reconcileInterruptedInstallations()).toBeGreaterThanOrEqual(1);
expect(getInstallationById(stuck.id)?.status).toBe("error");
expect(getInstallationById(stuck.id)?.statusDetail).toContain("interrupted");
expect(getInstallationById(fine.id)?.status).toBe("running");
});
});
+14
View File
@@ -229,6 +229,20 @@ export function updateInstallation(id: string, patch: InstallationUpdate): Insta
return getInstallationById(id)!; return getInstallationById(id)!;
} }
/**
* Statuses that only make sense while this process is working on the installation. After a
* restart (including the memory guard's deliberate one) nothing is working on them any more, so
* they would otherwise stay stuck forever, locking the UI buttons and gating the proxy.
*/
export function reconcileInterruptedInstallations(): number {
return db
.prepare(
`UPDATE installations SET status = 'error', status_detail = ?, updated_at = ?
WHERE status IN ('cloning', 'building', 'starting')`,
)
.run("interrupted by a manager restart — use Start or Redeploy to recover", new Date().toISOString()).changes;
}
export function deleteInstallation(id: string): void { export function deleteInstallation(id: string): void {
db.prepare("DELETE FROM installations WHERE id = ?").run(id); db.prepare("DELETE FROM installations WHERE id = ?").run(id);
} }
+2 -2
View File
@@ -82,7 +82,7 @@ export async function runInstallationContainer(installation: Installation): Prom
export async function getImageId(imageTag: string): Promise<string | undefined> { export async function getImageId(imageTag: string): Promise<string | undefined> {
try { try {
const info = await docker.getImage(imageTag).inspect(); const info = await withTimeout(docker.getImage(imageTag).inspect(), DOCKER_CALL_TIMEOUT_MS, `docker inspect ${imageTag}`);
return info.Id; return info.Id;
} catch { } catch {
return undefined; return undefined;
@@ -92,7 +92,7 @@ export async function getImageId(imageTag: string): Promise<string | undefined>
/** Best-effort removal: leaves the image alone if it's still referenced (e.g. by a running container). */ /** Best-effort removal: leaves the image alone if it's still referenced (e.g. by a running container). */
export async function removeImageIfUnused(imageId: string): Promise<void> { export async function removeImageIfUnused(imageId: string): Promise<void> {
try { try {
await docker.getImage(imageId).remove({ force: false }); await withTimeout(docker.getImage(imageId).remove({ force: false }), DOCKER_CALL_TIMEOUT_MS, "docker image rm");
} catch { } catch {
// still in use or already gone — nothing to do // still in use or already gone — nothing to do
} }
+4
View File
@@ -3,6 +3,7 @@ import express from "express";
import session from "express-session"; import session from "express-session";
import { config } from "./config/env.js"; import { config } from "./config/env.js";
import { db } from "./db/index.js"; import { db } from "./db/index.js";
import { reconcileInterruptedInstallations } from "./db/installations.js";
import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js"; import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js";
import { authRouter } from "./api/auth.js"; import { authRouter } from "./api/auth.js";
import { installationsRouter } from "./api/installations.js"; import { installationsRouter } from "./api/installations.js";
@@ -14,6 +15,9 @@ if (!config.sessionSecret) {
throw new Error("SESSION_SECRET env var must be set"); throw new Error("SESSION_SECRET env var must be set");
} }
const interrupted = reconcileInterruptedInstallations();
if (interrupted > 0) console.warn(`marked ${interrupted} interrupted installation(s) as error after restart`);
const app = express(); const app = express();
app.set("trust proxy", 1); app.set("trust proxy", 1);
app.use( app.use(
+27 -14
View File
@@ -72,15 +72,28 @@ export function configureInstallation(
return updateInstallation(id, patch); return updateInstallation(id, patch);
} }
export function buildInstallation(id: string): Promise<Installation> { interface BuildOutcome {
return enqueueBuild(() => runBuild(id)); installation: Installation;
ok: boolean;
} }
async function runBuild(id: string): Promise<Installation> { export async function buildInstallation(id: string): Promise<Installation> {
return (await enqueueBuild(() => runBuild(id))).installation;
}
async function runBuild(id: string): Promise<BuildOutcome> {
const installation = getInstallationById(id); const installation = getInstallationById(id);
if (!installation) throw new Error("installation not found"); if (!installation) throw new Error("installation not found");
updateInstallation(id, { status: "building", statusDetail: null }); // A build never touches the running container, so a running installation keeps its
// "running" status (and keeps being served by the proxy) throughout, whether the build
// succeeds or fails. Any other installation shows the build's progress/failure instead.
const wasRunning = installation.status === "running";
if (!wasRunning) updateInstallation(id, { status: "building", statusDetail: null });
const fail = (detail: string): BuildOutcome => ({
installation: updateInstallation(id, { status: wasRunning ? "running" : "error", statusDetail: detail }),
ok: false,
});
// The clone on disk is otherwise only ever made once, at draft creation — without this, // The clone on disk is otherwise only ever made once, at draft creation — without this,
// every "rebuild" silently reused that same stale checkout forever, never picking up new // every "rebuild" silently reused that same stale checkout forever, never picking up new
@@ -88,7 +101,7 @@ async function runBuild(id: string): Promise<Installation> {
try { try {
await cloneOrUpdateRepo(installation.slug, installation.repoUrl, installation.gitRef); await cloneOrUpdateRepo(installation.slug, installation.repoUrl, installation.gitRef);
} catch (err) { } catch (err) {
return updateInstallation(id, { status: "error", statusDetail: `git pull failed: ${(err as Error).message}` }); return fail(`git pull failed: ${(err as Error).message}`);
} }
const imageTag = `mcpmgr/${installation.slug}:latest`; const imageTag = `mcpmgr/${installation.slug}:latest`;
@@ -102,10 +115,7 @@ async function runBuild(id: string): Promise<Installation> {
); );
if (!result.success) { if (!result.success) {
return updateInstallation(id, { return fail(`build failed, see log at ${result.logPath}`);
status: "error",
statusDetail: `build failed, see log at ${result.logPath}`,
});
} }
// Nixpacks moves the tag to the new image, leaving the previous one dangling — clean it up // Nixpacks moves the tag to the new image, leaving the previous one dangling — clean it up
@@ -117,7 +127,10 @@ async function runBuild(id: string): Promise<Installation> {
} }
} }
return updateInstallation(id, { status: "built", statusDetail: null, imageTag }); return {
installation: updateInstallation(id, { status: wasRunning ? "running" : "built", statusDetail: null, imageTag }),
ok: true,
};
} }
export async function deployInstallation(id: string): Promise<Installation> { export async function deployInstallation(id: string): Promise<Installation> {
@@ -139,10 +152,10 @@ export async function deployInstallation(id: string): Promise<Installation> {
export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise<Installation> { export async function redeployInstallation(id: string, opts: { rebuild?: boolean } = {}): Promise<Installation> {
if (opts.rebuild) { if (opts.rebuild) {
// A failed build must stop here: deploying anyway would silently run the previous image // A failed build must stop here: deploying anyway would silently redeploy the previous image
// and flip the status back to "running", hiding the failure. // and report success, hiding the failure.
const built = await buildInstallation(id); const built = await enqueueBuild(() => runBuild(id));
if (built.status === "error") return built; if (!built.ok) return built.installation;
} }
return deployInstallation(id); return deployInstallation(id);
} }
+3 -2
View File
@@ -61,9 +61,10 @@ export class SqliteSessionStore extends session.Store {
touch(sid: string, sess: session.SessionData, cb?: () => void): void { touch(sid: string, sess: session.SessionData, cb?: () => void): void {
try { try {
this.db.prepare("UPDATE sessions SET expires = ? WHERE sid = ?").run(this.expiryOf(sess), sid); this.db.prepare("UPDATE sessions SET expires = ? WHERE sid = ?").run(this.expiryOf(sess), sid);
} finally { } catch {
cb?.(); // best effort: a failed touch only means the session expires on its original schedule
} }
cb?.();
} }
destroy(sid: string, cb?: (err?: unknown) => void): void { destroy(sid: string, cb?: (err?: unknown) => void): void {
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { spawn } from "node:child_process";
import { killGroupAfter } from "./processTimeout.js";
describe("killGroupAfter", () => {
it("kills a hung grandchild so the child's 'close' event still fires", async () => {
// The shell backgrounds `sleep` (a grandchild that inherits stdio) and waits on it.
const child = spawn("sh", ["-c", "sleep 30 & wait"], { detached: true });
killGroupAfter(child, 100);
const started = Date.now();
await new Promise((resolve) => child.on("close", resolve));
expect(Date.now() - started).toBeLessThan(5_000);
});
it("does nothing to a process that exits on its own", async () => {
const child = spawn("sh", ["-c", "exit 0"], { detached: true });
killGroupAfter(child, 60_000);
const code = await new Promise((resolve) => child.on("close", resolve));
expect(code).toBe(0);
});
});
+19
View File
@@ -0,0 +1,19 @@
import type { ChildProcess } from "node:child_process";
/**
* Kills the child's whole process group (SIGKILL) after `ms`. Spawn the child with `detached: true`
* so it leads its own group. Plain `spawn({ timeout })` only signals the direct child: a grandchild
* (e.g. the `docker build` nixpacks runs, or `ssh` under git) survives holding the stdio pipes, so
* the child's 'close' event never fires and whatever awaits it hangs forever.
*/
export function killGroupAfter(child: ChildProcess, ms: number): void {
const timer = setTimeout(() => {
try {
process.kill(-child.pid!, "SIGKILL");
} catch {
child.kill("SIGKILL");
}
}, ms);
timer.unref();
child.once("exit", () => clearTimeout(timer));
}
+3 -1
View File
@@ -41,7 +41,9 @@ Two families of actions, both in `apps/server/src/service/orchestrator.ts`:
reason). If the container no longer exists they fall back to Deploy when the installation reason). If the container no longer exists they fall back to Deploy when the installation
has a built image, and report an error otherwise. has a built image, and report an error otherwise.
The proxy only serves installations in status `running`, so a stopped or restarting A build never touches the running container, so an installation that is `running` stays
`running` (and served) during and after a build, even a failed one; the failure shows in the
status detail. The proxy only serves installations in status `running`, so a stopped or restarting
installation answers 404 until it is healthy again. The per-container IP cache is dropped on installation answers 404 until it is healthy again. The per-container IP cache is dropped on
every start/stop/restart because the IP can change. every start/stop/restart because the IP can change.
+2 -1
View File
@@ -15,7 +15,8 @@ limits exist:
| Session store | `session/sqliteStore.ts` | Sessions live in the SQLite DB and expired ones are purged every 10 min. Replaces `MemoryStore`, which never evicts and warned it leaks in production. | | Session store | `session/sqliteStore.ts` | Sessions live in the SQLite DB and expired ones are purged every 10 min. Replaces `MemoryStore`, which never evicts and warned it leaks in production. |
| Memory guard | `MANAGER_MEMORY_LIMIT_MB` (default 512, 0 = off) | Checked every 30 s on heap + external memory (not RSS, which hides swapped pages). When exceeded the process exits and `restart: unless-stopped` starts a fresh one. | | Memory guard | `MANAGER_MEMORY_LIMIT_MB` (default 512, 0 = off) | Checked every 30 s on heap + external memory (not RSS, which hides swapped pages). When exceeded the process exits and `restart: unless-stopped` starts a fresh one. |
| V8 heap ceiling | `NODE_OPTIONS=--max-old-space-size=768` in the `Dockerfile` | Hard backstop above the soft limit. | | V8 heap ceiling | `NODE_OPTIONS=--max-old-space-size=768` in the `Dockerfile` | Hard backstop above the soft limit. |
| Serialized builds | `service/orchestrator.ts` | One Nixpacks/Docker build at a time; git is killed after 5 min and a build after 30 min. | | Serialized builds | `service/orchestrator.ts` | One Nixpacks/Docker build at a time; git is killed after 5 min and a build after 30 min (the whole process group, so a hung `docker build` can't keep the queue blocked). |
| Restart reconciliation | `reconcileInterruptedInstallations` | On boot, `cloning`/`building`/`starting` installations are marked `error` (Start or Redeploy recovers them), since the process that was advancing them is gone. |
A container-level cgroup limit on the manager (`mem_limit` in compose) would be the strongest A container-level cgroup limit on the manager (`mem_limit` in compose) would be the strongest
guard, but it fails outright on hosts that do not delegate cgroup controllers (see guard, but it fails outright on hosts that do not delegate cgroup controllers (see