Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(local-installation): end the services a failed install attempt leaves behind

Dongdong Chend6b0e7797ecd
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 03e51376..1935e102 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -137,7 +137,15 @@ program fails the start after 15 seconds instead of at the deadline.
On POSIX, a start that finds the recorded supervisor gone but processes
still carrying its lease (the app was killed with it) ends them as a stop
does and starts the service again. A live recorded PID or process group
-without the lease proves nothing and is refused, never signalled.
+without the lease proves nothing and is refused, never signalled. A start
+that fails before its record is kept ends what it launched: by the lease,
+or, when the lease cannot be proved, by the group of the supervisor it has
+not reaped yet, whose PID cannot belong to another program. Before the
+services start, `reclaimNativeOrphans` also ends, on POSIX, a supervisor
+whose command line names a job file in this instance's process directory
+under a lease no record holds, once its environment proves that lease; an
+attempt that failed or was killed before keeping a record would otherwise
+leave PostgreSQL holding `postmaster.pid` against every retry.
Move a freshly downloaded or unpacked file or folder into place with
`renameRetrying` from `fs-retry.ts`: on Windows antivirus and indexing hold
diff --git a/packages/local-installation/src/native-process-unverified.test.ts b/packages/local-installation/src/native-process-unverified.test.ts
new file mode 100644
index 00000000..a5da2d35
--- /dev/null
+++ b/packages/local-installation/src/native-process-unverified.test.ts
@@ -0,0 +1,71 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { expect, onTestFinished, test, vi } from "vitest";
+
+// Every identity check fails, as a localized `ps` once made them on macOS:
+// neither the supervisor nor what it started can be proved by its lease.
+vi.mock("./native-process-identity.js", async (original) => ({
+ ...(await original<typeof import("./native-process-identity.js")>()),
+ nativeProcessIdentity: async () => undefined,
+ nativeLeaseProcesses: async () => [],
+}));
+const { startNativeProcess } = await import("./native-process.js");
+
+vi.setConfig({ testTimeout: 30_000, expect: { poll: { timeout: 15_000 } } });
+
+function alive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ if (process.platform === "linux")
+ return !execFileSync("cat", [`/proc/${pid}/stat`], { encoding: "utf8" })
+ .replace(/^.*\) /s, "")
+ .startsWith("Z");
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+(process.platform === "win32" ? test.skip : test)(
+ "ends the launched supervisor and its service when their identity cannot be verified",
+ async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "native-unverified-"));
+ onTestFinished(async () => {
+ try {
+ execFileSync("pkill", ["-KILL", "-f", root]);
+ } catch {
+ // pkill exits 1 when nothing matched.
+ }
+ await rm(root, { recursive: true, force: true });
+ });
+ await expect(
+ startNativeProcess({
+ root,
+ name: "postgres",
+ executable: process.execPath,
+ args: [
+ "-e",
+ "require('node:fs').writeFileSync('service.pid',String(process.pid));setInterval(()=>{},1000)",
+ // Names the root on its command line, so the check below finds it.
+ root,
+ ],
+ cwd: root,
+ env: process.env,
+ }),
+ ).rejects.toThrow("Native postgres identity could not be verified.");
+ const service = Number(
+ await readFile(path.join(root, "service.pid"), "utf8").catch(() => "0"),
+ );
+ // A service left running here held postmaster.pid against every retry.
+ if (service) await expect.poll(() => alive(service)).toBe(false);
+ await expect
+ .poll(() =>
+ execFileSync("ps", ["-axo", "stat=,command="], { encoding: "utf8" })
+ .split("\n")
+ .filter((line) => line.includes(root) && !/^\s*Z/.test(line)),
+ )
+ .toEqual([]);
+ },
+);
diff --git a/packages/local-installation/src/native-process.test.ts b/packages/local-installation/src/native-process.test.ts
index 6a46b42b..4f22b8e9 100644
--- a/packages/local-installation/src/native-process.test.ts
+++ b/packages/local-installation/src/native-process.test.ts
@@ -24,6 +24,7 @@ import {
nativeConfigurationChanged,
startNativeProcess,
inspectNativeProcess,
+ reclaimNativeOrphans,
stopNativeProcess,
} from "./native-process.js";
@@ -245,6 +246,39 @@ test("stops descendants that ignore SIGINT after the service leader exits", asyn
},
);
+(process.platform === "win32" ? test.skip : test)(
+ "reclaims a service an earlier attempt left under a lease no record holds",
+ async (context) => {
+ const { expect } = context;
+ const root = await fixture(context);
+ const service = (name: "web" | "teamhub") => ({
+ root,
+ name,
+ executable: process.execPath,
+ args: [
+ "-e",
+ `require('node:fs').writeFileSync('${name}.pid',String(process.pid));setInterval(()=>{},1000)`,
+ ],
+ cwd: root,
+ env: process.env,
+ });
+ const lost = await startNativeProcess(service("web"));
+ const kept = await startNativeProcess(service("teamhub"));
+ const pid = async (name: string) =>
+ Number(await readFile(path.join(root, `${name}.pid`), "utf8"));
+ await expect.poll(() => pid("web").catch(() => 0)).not.toBe(0);
+ await expect.poll(() => pid("teamhub").catch(() => 0)).not.toBe(0);
+ // The attempt that started it failed before its record was kept.
+ await rm(path.join(root, "native/processes/web.json"));
+ const ended = await reclaimNativeOrphans(root, { ports: [], paths: [] });
+ expect(ended).toContain(lost.pid);
+ await expect.poll(async () => exited(await pid("web"))).toBe(true);
+ expect(exited(lost.pid!)).toBe(true);
+ expect(exited(kept.pid!)).toBe(false);
+ expect(exited(await pid("teamhub"))).toBe(false);
+ },
+);
+
test("cleans the launched owned group when identity persistence fails", async (context) => {
const { expect } = context;
const root = await fixture(context);
diff --git a/packages/local-installation/src/native-process.ts b/packages/local-installation/src/native-process.ts
index 46e5ac23..489afffd 100644
--- a/packages/local-installation/src/native-process.ts
+++ b/packages/local-installation/src/native-process.ts
@@ -1,4 +1,4 @@
-import { spawn } from "node:child_process";
+import { spawn, type ChildProcess } from "node:child_process";
import { existsSync } from "node:fs";
import { readFile, rm } from "node:fs/promises";
import { createHash, randomBytes } from "node:crypto";
@@ -396,6 +396,11 @@ export async function startNativeProcess(options: {
{ cause: error },
);
}
+ // When the lease could not be proved, the supervisor this call spawned
+ // and has not reaped is still provably its own, and so is the group it
+ // leads: end them, or the service keeps its files (postmaster.pid) and
+ // ports against every retry.
+ await endUnreapedGroup(child);
if (child.connected) child.disconnect();
child.unref();
throw error;
@@ -404,6 +409,33 @@ export async function startNativeProcess(options: {
}
}
+/**
+ * Ends the process group a detached child leads while the child is not yet
+ * reaped: until then its PID, and so its group, cannot belong to another
+ * program.
+ */
+async function endUnreapedGroup(child: ChildProcess): Promise<void> {
+ if (child.pid === undefined) return;
+ const exited = new Promise<void>((resolve) => child.once("exit", resolve));
+ if (child.exitCode === null && child.signalCode === null) {
+ try {
+ process.kill(-child.pid, "SIGKILL");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
+ }
+ await Promise.race([exited, delay(5_000)]);
+ }
+ // The leader's exit does not wait for the rest of its group.
+ for (let count = 0; count < 50 && (await groupLive(child.pid)); count++) {
+ try {
+ process.kill(-child.pid, "SIGKILL");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;
+ }
+ await delay(100);
+ }
+}
+
/**
* Marks a stop refused because the recorded PID now belongs to another
* program: none of the service's own processes are left.
@@ -417,11 +449,20 @@ export async function stopNativeProcess(
): Promise<void> {
const record = await stored(root, name);
if (!record) return;
- if (process.platform === "win32") {
+ if (process.platform === "win32")
await stopWindowsTree(name, record.lease, record);
- await rm(paths(root, name).record, { force: true });
- return;
- }
+ else await stopLease(name, record, interruptMs);
+ await rm(paths(root, name).record, { force: true });
+}
+/**
+ * macOS and Linux: ends the supervisor holding the lease and everything
+ * under it, SIGINT first and SIGKILL for what outlives `interruptMs`.
+ */
+async function stopLease(
+ name: NativeService,
+ record: Pick<Lease, "pid" | "birth" | "lease">,
+ interruptMs: number,
+): Promise<void> {
const current = await observed(record.pid, record.lease);
let owned = await nativeLeaseProcesses(record.lease);
if (current !== record.birth && !owned.length) {
@@ -432,7 +473,6 @@ export async function stopNativeProcess(
),
{ code: NATIVE_PROCESS_REPLACED },
);
- await rm(paths(root, name).record, { force: true });
return;
}
const signalOwned = async (
@@ -496,7 +536,6 @@ export async function stopNativeProcess(
(await nativeLeaseProcesses(record.lease)).length
)
throw new Error(`Native ${name} did not stop; identity record retained.`);
- await rm(paths(root, name).record, { force: true });
}
function terminate(pid: number) {
@@ -664,14 +703,14 @@ export function windowsOrphans(
return order;
}
/**
- * Ends what `windowsOrphans` finds for this instance; nothing elsewhere.
+ * Ends what `windowsOrphans` finds for this instance on Windows, and what
+ * `reclaimUnrecordedLeases` finds on macOS and Linux; nothing elsewhere.
* Returns the PIDs it ended.
*/
export async function reclaimNativeOrphans(
root: string,
options: { ports: number[]; paths: string[] },
): Promise<number[]> {
- if (process.platform !== "win32") return [];
const records: Lease[] = [];
for (const name of services)
try {
@@ -680,6 +719,8 @@ export async function reclaimNativeOrphans(
} catch {
// A damaged record proves nothing; its supervisor counts as unrecorded.
}
+ if (process.platform !== "win32")
+ return reclaimUnrecordedLeases(root, records);
const ended: number[] = [];
const deadline = Date.now() + 12_000;
for (;;) {
@@ -709,3 +750,63 @@ export async function reclaimNativeOrphans(
await delay(100);
}
}
+
+/** Each process of this user with its command line (macOS and Linux). */
+async function ownCommands(): Promise<Array<{ pid: number; command: string }>> {
+ if (process.platform === "linux") {
+ const listed = await Promise.all(
+ (await linuxProcessStates(true)).map(async ({ pid, state }) => {
+ if (state === "Z") return undefined;
+ const command = await readFile(`/proc/${pid}/cmdline`, "utf8").catch(
+ () => "",
+ );
+ return { pid, command: command.split("\0").join(" ") };
+ }),
+ );
+ return listed.filter((entry) => entry !== undefined);
+ }
+ const result = await runProcess("/bin/ps", ["-axo", "pid=,uid=,command="], {
+ timeoutMs: 5_000,
+ });
+ if (result.code !== 0)
+ throw new Error("Native processes could not be enumerated.");
+ return result.stdout.split("\n").flatMap((line) => {
+ const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
+ return match && Number(match[2]) === process.getuid?.()
+ ? [{ pid: Number(match[1]), command: match[3]! }]
+ : [];
+ });
+}
+/**
+ * macOS and Linux: ends the services an earlier attempt started and kept no
+ * record of (it failed or was killed before writing one), which otherwise
+ * keep their files and ports, such as PostgreSQL's postmaster.pid, against
+ * every retry. A supervisor is this instance's own when its command line
+ * names a job file in this instance's process directory and its environment
+ * carries that job's unguessable lease. Returns the supervisors it ended.
+ */
+async function reclaimUnrecordedLeases(
+ root: string,
+ records: Array<Pick<Lease, "lease">>,
+): Promise<number[]> {
+ const recorded = new Set(records.map((record) => record.lease));
+ const jobs = path.join(root, "native", "processes") + path.sep;
+ const ended: number[] = [];
+ for (const { pid, command } of await ownCommands()) {
+ if (!command.includes(SUPERVISOR)) continue;
+ const at = command.indexOf(jobs);
+ const job =
+ at < 0
+ ? undefined
+ : /^([a-z-]+)\.([a-f0-9]{64})\.job(?:\s|$)/.exec(
+ command.slice(at + jobs.length),
+ );
+ if (!job || !services.has(job[1]!) || recorded.has(job[2]!)) continue;
+ const [, name, lease] = job as unknown as [string, NativeService, string];
+ const birth = await observed(pid, lease);
+ if (!birth) continue;
+ await stopLease(name, { pid, birth, lease }, 12_000);
+ ended.push(pid);
+ }
+ return ended;
+}
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index 885f727a..72f058db 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -1121,9 +1121,10 @@ async function runNativeSource(
}
}
/**
- * Windows: ends the processes of this instance an earlier run lost track of
- * (an earlier release's stop left them, or their supervisor died), so they
- * neither hold the ports nor answer health checks for the new services.
+ * Ends the processes of this instance an earlier run lost track of (an
+ * earlier release's stop left them, their supervisor died, or a failed
+ * attempt kept no record of them), so they neither hold the ports and data
+ * files nor answer health checks for the new services.
*/
async function reclaimEarlierProcesses(
instance: Instance,
diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts
index 0bf68db6..6f3f7081 100644
--- a/packages/local-installation/src/source-checkout.ts
+++ b/packages/local-installation/src/source-checkout.ts
@@ -228,7 +228,7 @@ export async function prepareSourceConfiguration(
(await portFree(port))
)
continue;
- // On Windows the program may be one an earlier run left behind.
+ // The program may be one an earlier run left behind.
await reclaimNativeOrphans(instance.root, {
ports: [port],
paths: [path.resolve(instance.root, "../.."), instance.root, repo],