From 6821b224455bef028647d29fff02e6f1348c18b5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 16:06:47 +0000 Subject: [PATCH 1/2] fix(devkitd): prevent dual live daemons during autostart (#495) Acquire a kernel flock on daemon.lock before SQLite init, bind the Unix socket before the warm-up sweep, and keep the client spawn lock until the spawned devkitd is serving or has exited. --- packages/daemon-client/src/autostart.ts | 74 ++++++++++++-- .../tests/autostart-spawn-lock.test.ts | 98 +++++++++++++++++++ rust/crates/devkitd/src/main.rs | 5 +- rust/crates/devkitd/src/server.rs | 60 +++++++++++- 4 files changed, 223 insertions(+), 14 deletions(-) create mode 100644 packages/daemon-client/tests/autostart-spawn-lock.test.ts diff --git a/packages/daemon-client/src/autostart.ts b/packages/daemon-client/src/autostart.ts index 3ee1c182..ac4848e5 100644 --- a/packages/daemon-client/src/autostart.ts +++ b/packages/daemon-client/src/autostart.ts @@ -75,11 +75,17 @@ export async function ensureDaemon( // arrives while devkitd is still binding its socket must see the lock and // wait — releasing early lets it spawn a twin that clobbers the socket path // and orphans the first daemon forever. + let spawnedPid: number | undefined; + let socketReady = false; try { - if (!spawnDaemon(bin.path, dir, debug)) return null; - return await waitForSocket(waitMs, debug); + const pid = spawnDaemon(bin.path, dir, debug); + if (pid === null) return null; + spawnedPid = pid; + const client = await waitForSocket(waitMs, debug); + socketReady = client !== null; + return client; } finally { - releaseSpawnLock(lockPath); + releaseSpawnLockAfterStart(lockPath, spawnedPid, socketReady, debug); } } @@ -164,6 +170,8 @@ async function replaceStaleDaemon( debug?.("another process is replacing devkitd; waiting for it"); return waitForLockRelease(lockPath, 2 * waitMs + 1000, debug); } + let spawnedPid: number | undefined; + let socketReady = false; try { const current = await DaemonClient.tryConnect(); if (current) { @@ -176,10 +184,14 @@ async function replaceStaleDaemon( } debug?.("stale devkitd stopped"); } - if (!spawnDaemon(bin.path, dir, debug)) return null; - return await waitForSocket(waitMs, debug); + const pid = spawnDaemon(bin.path, dir, debug); + if (pid === null) return null; + spawnedPid = pid; + const client = await waitForSocket(waitMs, debug); + socketReady = client !== null; + return client; } finally { - releaseSpawnLock(lockPath); + releaseSpawnLockAfterStart(lockPath, spawnedPid, socketReady, debug); } } @@ -193,7 +205,7 @@ function isNewerVersion(a: string, b: string): boolean { return false; } -function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): boolean { +function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): number | null { try { const logPath = path.join(dir, "daemon.log"); capDaemonLog(logPath); @@ -204,14 +216,60 @@ function spawnDaemon(bin: string, dir: string, debug?: (msg: string) => void): b }); child.unref(); fs.closeSync(logFd); + if (child.pid === undefined) { + debug?.("devkitd spawn failed (no pid)"); + return null; + } debug?.(`spawned devkitd (pid ${child.pid}) from ${bin}; waiting for socket`); - return true; + return child.pid; } catch { debug?.("devkitd spawn failed"); + return null; + } +} + +function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { return false; } } +/** + * Drop the spawn lock when startup finished or the child is gone. If the + * client timed out but devkitd is still booting, keep the lock and release + * it once the socket answers or the child exits — otherwise a second caller + * spawns a twin (#495). + */ +function releaseSpawnLockAfterStart( + lockPath: string, + spawnedPid: number | undefined, + socketReady: boolean, + debug?: (msg: string) => void, +): void { + if (socketReady || spawnedPid === undefined || !isProcessAlive(spawnedPid)) { + releaseSpawnLock(lockPath); + return; + } + void (async () => { + const deadline = Date.now() + 5 * 60_000; + while (Date.now() < deadline && isProcessAlive(spawnedPid)) { + const c = await DaemonClient.tryConnect(); + if (c) { + c.close(); + debug?.("released spawn lock after devkitd socket became ready"); + releaseSpawnLock(lockPath); + return; + } + await new Promise((r) => setTimeout(r, 50)); + } + if (!isProcessAlive(spawnedPid)) releaseSpawnLock(lockPath); + else debug?.("spawn lock held: devkitd still starting after extended wait"); + })(); +} + /** daemon.log is append-only per spawn — rotate to .1 past 1 MiB. */ const MAX_LOG_BYTES = 1 << 20; diff --git a/packages/daemon-client/tests/autostart-spawn-lock.test.ts b/packages/daemon-client/tests/autostart-spawn-lock.test.ts new file mode 100644 index 00000000..aff86d87 --- /dev/null +++ b/packages/daemon-client/tests/autostart-spawn-lock.test.ts @@ -0,0 +1,98 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { daemonSocketPath } from "../src/client.js"; +import { ensureDaemon } from "../src/autostart.js"; +import type { DaemonBinary } from "../src/binary.js"; + +/** Fake devkitd that sleeps before binding — reproduces client wait timeout (#495). */ +function makeSlowFakeBin(dir: string, delayMs: number): string { + const file = path.join(dir, "slow-devkitd"); + fs.writeFileSync( + file, + `#!/usr/bin/env node +const fs = require("node:fs"); +const net = require("node:net"); +const path = require("node:path"); +const os = require("node:os"); +const delay = ${delayMs}; +if (process.argv[2] === "version") { + console.log(JSON.stringify({ version: "0.1.0", buildVersion: "9.9.9" })); + process.exit(0); +} +const dir = path.join(os.homedir(), ".ai-devkit"); +const sock = path.join(dir, "daemon.sock"); +fs.mkdirSync(dir, { recursive: true }); +fs.appendFileSync(path.join(dir, "slow-pids"), process.pid + "\\n"); +setTimeout(() => { + const server = net.createServer((conn) => { + let buf = ""; + conn.on("data", (d) => { + buf += d; + let i; + while ((i = buf.indexOf("\\n")) >= 0) { + const req = JSON.parse(buf.slice(0, i)); + buf = buf.slice(i + 1); + conn.write(JSON.stringify({ id: req.id, result: { pong: true } }) + "\\n"); + } + }); + }); + server.listen(sock); +}, delay); +`, + ); + fs.chmodSync(file, 0o755); + return file; +} + +describe("ensureDaemon spawn lock while child is still starting", () => { + let home: string; + let binDir: string; + const saved: Record = {}; + + beforeEach(() => { + home = fs.mkdtempSync(path.join(os.tmpdir(), "aidk-spawnlock-home-")); + binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aidk-spawnlock-bin-")); + for (const k of ["HOME", "DEVKITD_BIN", "AI_DEVKIT_NO_DAEMON", "VITEST"]) + saved[k] = process.env[k]; + process.env.HOME = home; + delete process.env.AI_DEVKIT_NO_DAEMON; + delete process.env.VITEST; + }); + + afterEach(() => { + const pids = path.join(home, ".ai-devkit", "slow-pids"); + if (fs.existsSync(pids)) { + for (const pid of fs.readFileSync(pids, "utf8").split("\n").filter(Boolean)) { + try { + process.kill(Number(pid), "SIGKILL"); + } catch { + /* already gone */ + } + } + } + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + fs.rmSync(home, { recursive: true, force: true }); + fs.rmSync(binDir, { recursive: true, force: true }); + }); + + it("keeps spawn lock when wait times out but the child is still booting", async () => { + const bin = makeSlowFakeBin(binDir, 3500); + const lockPath = `${daemonSocketPath()}.spawn.lock`; + const resolveBinary = (): DaemonBinary => ({ path: bin, version: "9.9.9" }); + + const first = ensureDaemon({ resolveBinary, waitMs: 400 }); + const second = ensureDaemon({ resolveBinary, waitMs: 6000 }); + + await expect(first).resolves.toBeNull(); + expect(fs.existsSync(lockPath)).toBe(true); + + const client = await second; + expect(client).not.toBeNull(); + expect(fs.existsSync(lockPath)).toBe(false); + }); +}); diff --git a/rust/crates/devkitd/src/main.rs b/rust/crates/devkitd/src/main.rs index 16709025..2f3653b0 100644 --- a/rust/crates/devkitd/src/main.rs +++ b/rust/crates/devkitd/src/main.rs @@ -33,8 +33,9 @@ async fn main() -> Result<()> { let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into()); match cmd.as_str() { "serve" => { - let daemon = Arc::new(Daemon::new(&data_dir(), socket_path(), dirs_home())?); - daemon.apply_sweep(); // warm the cache before accepting clients + let dir = data_dir(); + let _instance = server::acquire_instance_lock(&dir)?; + let daemon = Arc::new(Daemon::new(&dir, socket_path(), dirs_home())?); server::serve(daemon).await } "install" => { diff --git a/rust/crates/devkitd/src/server.rs b/rust/crates/devkitd/src/server.rs index a0e2e275..c762e050 100644 --- a/rust/crates/devkitd/src/server.rs +++ b/rust/crates/devkitd/src/server.rs @@ -414,6 +414,33 @@ fn peer_is_same_user(_stream: &UnixStream) -> bool { /// apart (#376) — clients compare `buildVersion` to detect a stale daemon. pub const BUILD_VERSION: Option<&str> = option_env!("DEVKITD_BUILD_VERSION"); +/// Kernel-released singleton lock — held for the process lifetime so two +/// `devkitd serve` invocations cannot both sweep `daemon.db` or race on the +/// socket path. Must be taken before `Daemon::new()` / SQLite work. +pub fn acquire_instance_lock(data_dir: &std::path::Path) -> Result { + std::fs::create_dir_all(data_dir)?; + let path = data_dir.join("daemon.lock"); + let file = std::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(false) + .open(&path)?; + let fd = std::os::unix::io::AsRawFd::as_raw_fd(&file); + let rc = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) }; + if rc != 0 { + let err = std::io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::EWOULDBLOCK) { + anyhow::bail!("devkitd already running"); + } + return Err(err.into()); + } + Ok(InstanceLock { _file: file }) +} + +pub struct InstanceLock { + _file: std::fs::File, +} + /// Shared by `daemon.status` and `devkitd version` so a client can compare /// the running daemon against the binary it would spawn. pub fn identity() -> Value { @@ -428,15 +455,25 @@ pub async fn serve(daemon: Arc) -> Result<()> { // Refuse to displace a live daemon: unlinking the socket file leaves // the old process sweeping and writing daemon.db invisibly — two // daemons, one reachable. Only a dead owner's file is unlinked. - match std::os::unix::net::UnixStream::connect(&daemon.socket_path) { - Ok(_) => anyhow::bail!("devkitd already running"), - Err(_) => std::fs::remove_file(&daemon.socket_path)?, + if std::os::unix::net::UnixStream::connect(&daemon.socket_path).is_ok() { + anyhow::bail!("devkitd already running"); + } + // Re-probe before unlink — a peer may have bound between checks. + if std::os::unix::net::UnixStream::connect(&daemon.socket_path).is_ok() { + anyhow::bail!("devkitd already running"); + } + if daemon.socket_path.exists() { + std::fs::remove_file(&daemon.socket_path)?; } } let listener = UnixListener::bind(&daemon.socket_path)?; std::fs::set_permissions(&daemon.socket_path, std::fs::Permissions::from_mode(0o600))?; tracing::info!("listening on {}", daemon.socket_path.display()); + // Warm the cache after the socket is visible so clients don't time out + // while SQLite + the first sweep run (#495). + daemon.apply_sweep(); + // Discovery loop: one sweep per interval for all subscribers. { let d = daemon.clone(); @@ -610,7 +647,6 @@ mod tests { async fn test_daemon() -> (Arc, PathBuf) { let (d, sock) = unserved_daemon(); - d.apply_sweep(); // warm the cache like main() does before serving let d2 = d.clone(); tokio::spawn(async move { let _ = serve(d2).await; @@ -699,6 +735,22 @@ mod tests { assert_eq!(r["pid"], std::process::id()); } + #[test] + fn instance_lock_allows_one_holder() { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "aidk-instlock-{}-{}", + std::process::id(), + N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).unwrap(); + let _a = acquire_instance_lock(&dir).unwrap(); + match acquire_instance_lock(&dir) { + Err(e) => assert!(e.to_string().contains("already running")), + Ok(_) => panic!("expected lock contention"), + } + } + #[tokio::test] async fn serve_refuses_to_displace_a_live_daemon() { let (d, sock) = test_daemon().await; From 5faea2b9f109ee10b8d46c4074edd9a025b9faa8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 16:09:03 +0000 Subject: [PATCH 2/2] fix(#495): drop spawn-lock poll loop; pid-based reclaim Release the client spawn lock in finally (daemon.lock flock is the singleton guard). Record the spawned devkitd pid in the lock file for reclaim when the holder dies. Remove the duplicate socket connect probe. Co-authored-by: Hoang Nguyen --- packages/daemon-client/src/autostart.ts | 89 ++++++++----------- .../tests/autostart-spawn-lock.test.ts | 60 +++++++++++-- rust/crates/devkitd/src/server.rs | 4 - 3 files changed, 89 insertions(+), 64 deletions(-) diff --git a/packages/daemon-client/src/autostart.ts b/packages/daemon-client/src/autostart.ts index ac4848e5..9715592d 100644 --- a/packages/daemon-client/src/autostart.ts +++ b/packages/daemon-client/src/autostart.ts @@ -75,17 +75,13 @@ export async function ensureDaemon( // arrives while devkitd is still binding its socket must see the lock and // wait — releasing early lets it spawn a twin that clobbers the socket path // and orphans the first daemon forever. - let spawnedPid: number | undefined; - let socketReady = false; try { const pid = spawnDaemon(bin.path, dir, debug); if (pid === null) return null; - spawnedPid = pid; - const client = await waitForSocket(waitMs, debug); - socketReady = client !== null; - return client; + writeSpawnLockPid(lockPath, pid); + return await waitForSocket(waitMs, debug); } finally { - releaseSpawnLockAfterStart(lockPath, spawnedPid, socketReady, debug); + releaseSpawnLock(lockPath); } } @@ -170,8 +166,6 @@ async function replaceStaleDaemon( debug?.("another process is replacing devkitd; waiting for it"); return waitForLockRelease(lockPath, 2 * waitMs + 1000, debug); } - let spawnedPid: number | undefined; - let socketReady = false; try { const current = await DaemonClient.tryConnect(); if (current) { @@ -186,12 +180,10 @@ async function replaceStaleDaemon( } const pid = spawnDaemon(bin.path, dir, debug); if (pid === null) return null; - spawnedPid = pid; - const client = await waitForSocket(waitMs, debug); - socketReady = client !== null; - return client; + writeSpawnLockPid(lockPath, pid); + return await waitForSocket(waitMs, debug); } finally { - releaseSpawnLockAfterStart(lockPath, spawnedPid, socketReady, debug); + releaseSpawnLock(lockPath); } } @@ -237,37 +229,22 @@ function isProcessAlive(pid: number): boolean { } } -/** - * Drop the spawn lock when startup finished or the child is gone. If the - * client timed out but devkitd is still booting, keep the lock and release - * it once the socket answers or the child exits — otherwise a second caller - * spawns a twin (#495). - */ -function releaseSpawnLockAfterStart( - lockPath: string, - spawnedPid: number | undefined, - socketReady: boolean, - debug?: (msg: string) => void, -): void { - if (socketReady || spawnedPid === undefined || !isProcessAlive(spawnedPid)) { - releaseSpawnLock(lockPath); - return; +function writeSpawnLockPid(lockPath: string, pid: number): void { + try { + fs.writeFileSync(lockPath, String(pid)); + } catch { + /* best effort — mtime-based reclaim still applies */ + } +} + +function readSpawnLockPid(lockPath: string): number | undefined { + try { + const text = fs.readFileSync(lockPath, "utf8").trim(); + const pid = Number(text); + return Number.isInteger(pid) && pid > 0 ? pid : undefined; + } catch { + return undefined; } - void (async () => { - const deadline = Date.now() + 5 * 60_000; - while (Date.now() < deadline && isProcessAlive(spawnedPid)) { - const c = await DaemonClient.tryConnect(); - if (c) { - c.close(); - debug?.("released spawn lock after devkitd socket became ready"); - releaseSpawnLock(lockPath); - return; - } - await new Promise((r) => setTimeout(r, 50)); - } - if (!isProcessAlive(spawnedPid)) releaseSpawnLock(lockPath); - else debug?.("spawn lock held: devkitd still starting after extended wait"); - })(); } /** daemon.log is append-only per spawn — rotate to .1 past 1 MiB. */ @@ -291,23 +268,31 @@ function releaseSpawnLock(lockPath: string): void { } } +function spawnLockIsStale(lockPath: string, staleMs: number): boolean { + try { + const age = Date.now() - fs.statSync(lockPath).mtimeMs; + if (age > staleMs) return true; + const pid = readSpawnLockPid(lockPath); + return pid !== undefined && !isProcessAlive(pid); + } catch { + return false; + } +} + function acquireSpawnLock(lockPath: string, staleMs: number): boolean { try { fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); return true; } catch { - // Lock held — reclaim it only if the holder plausibly died. + if (!spawnLockIsStale(lockPath, staleMs)) return false; try { - const age = Date.now() - fs.statSync(lockPath).mtimeMs; - if (age > staleMs) { - fs.unlinkSync(lockPath); - fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); - return true; - } + fs.unlinkSync(lockPath); + fs.closeSync(fs.openSync(lockPath, "wx", 0o600)); + return true; } catch { /* races with the holder are fine — losing means we wait */ + return false; } - return false; } } diff --git a/packages/daemon-client/tests/autostart-spawn-lock.test.ts b/packages/daemon-client/tests/autostart-spawn-lock.test.ts index aff86d87..e9ebf75c 100644 --- a/packages/daemon-client/tests/autostart-spawn-lock.test.ts +++ b/packages/daemon-client/tests/autostart-spawn-lock.test.ts @@ -2,10 +2,14 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; +import { spawn } from "node:child_process"; +import { fileURLToPath } from "node:url"; import { daemonSocketPath } from "../src/client.js"; import { ensureDaemon } from "../src/autostart.js"; import type { DaemonBinary } from "../src/binary.js"; +const testDir = path.dirname(fileURLToPath(import.meta.url)); + /** Fake devkitd that sleeps before binding — reproduces client wait timeout (#495). */ function makeSlowFakeBin(dir: string, delayMs: number): string { const file = path.join(dir, "slow-devkitd"); @@ -46,7 +50,7 @@ setTimeout(() => { return file; } -describe("ensureDaemon spawn lock while child is still starting", () => { +describe("ensureDaemon spawn lock", () => { let home: string; let binDir: string; const saved: Record = {}; @@ -80,19 +84,59 @@ describe("ensureDaemon spawn lock while child is still starting", () => { fs.rmSync(binDir, { recursive: true, force: true }); }); - it("keeps spawn lock when wait times out but the child is still booting", async () => { - const bin = makeSlowFakeBin(binDir, 3500); + it("releases spawn lock when the socket wait times out", async () => { + const bin = makeSlowFakeBin(binDir, 5000); const lockPath = `${daemonSocketPath()}.spawn.lock`; const resolveBinary = (): DaemonBinary => ({ path: bin, version: "9.9.9" }); - const first = ensureDaemon({ resolveBinary, waitMs: 400 }); - const second = ensureDaemon({ resolveBinary, waitMs: 6000 }); + const client = await ensureDaemon({ resolveBinary, waitMs: 200 }); + expect(client).toBeNull(); + expect(fs.existsSync(lockPath)).toBe(false); + }); - await expect(first).resolves.toBeNull(); - expect(fs.existsSync(lockPath)).toBe(true); + it("reclaims spawn lock when the recorded devkitd pid has exited", async () => { + const lockPath = `${daemonSocketPath()}.spawn.lock`; + fs.mkdirSync(path.dirname(lockPath), { recursive: true }); + fs.writeFileSync(lockPath, "999999999"); - const client = await second; + const bin = makeSlowFakeBin(binDir, 50); + const resolveBinary = (): DaemonBinary => ({ path: bin, version: "9.9.9" }); + const client = await ensureDaemon({ resolveBinary, waitMs: 3000 }); expect(client).not.toBeNull(); + client?.close(); expect(fs.existsSync(lockPath)).toBe(false); }); + + it("short-lived caller subprocess exits promptly when devkitd binds slowly", async () => { + const bin = makeSlowFakeBin(binDir, 8000); + const runner = path.join(home, "run-ensure-once.mjs"); + const autostart = path.join(testDir, "../dist/autostart.js"); + fs.writeFileSync( + runner, + `import { ensureDaemon } from ${JSON.stringify(autostart)}; +await ensureDaemon({ + waitMs: 250, + resolveBinary: () => ({ path: process.env.BIN, version: "9.9.9" }), +}); +`, + ); + + const start = Date.now(); + await new Promise((resolve, reject) => { + const child = spawn(process.execPath, [runner], { + env: { ...process.env, HOME: home, BIN: bin, VITEST: undefined }, + stdio: "ignore", + }); + const killTimer = setTimeout(() => { + child.kill("SIGKILL"); + reject(new Error("subprocess hung (event loop kept alive)")); + }, 2500); + child.on("exit", (code) => { + clearTimeout(killTimer); + if (code === 0) resolve(); + else reject(new Error(`subprocess exited ${code}`)); + }); + }); + expect(Date.now() - start).toBeLessThan(2000); + }, 15000); }); diff --git a/rust/crates/devkitd/src/server.rs b/rust/crates/devkitd/src/server.rs index c762e050..3ba40467 100644 --- a/rust/crates/devkitd/src/server.rs +++ b/rust/crates/devkitd/src/server.rs @@ -458,10 +458,6 @@ pub async fn serve(daemon: Arc) -> Result<()> { if std::os::unix::net::UnixStream::connect(&daemon.socket_path).is_ok() { anyhow::bail!("devkitd already running"); } - // Re-probe before unlink — a peer may have bound between checks. - if std::os::unix::net::UnixStream::connect(&daemon.socket_path).is_ok() { - anyhow::bail!("devkitd already running"); - } if daemon.socket_path.exists() { std::fs::remove_file(&daemon.socket_path)?; }