From 635321dd9a6f322af7466957a6df75c8a60eb035 Mon Sep 17 00:00:00 2001 From: 777genius Date: Sat, 30 May 2026 13:55:43 +0300 Subject: [PATCH] perf: drop per-acquire existsSync stat from file lock fast path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tryAcquire() ran fs.existsSync(dir) on every lock acquisition to lazily create the lock directory. The dir almost always already exists (team dirs are created up front), so that stat was wasted on every acquire — and the file-lock path churns heavily during a launch (inbox writes, journals, task mutations all lock per write, showing up as unlink/open/stat syscall load in the launch profile). Attempt the openSync('wx') directly; only on ENOENT create the directory and retry the acquire in the same call. Same locking semantics, same files, same first-acquire latency for a missing dir — just one fewer stat per acquire in the common case. --- src/main/services/team/fileLock.ts | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/main/services/team/fileLock.ts b/src/main/services/team/fileLock.ts index 9152bbda..56a1c7de 100644 --- a/src/main/services/team/fileLock.ts +++ b/src/main/services/team/fileLock.ts @@ -69,18 +69,34 @@ function removeLockPath(lockPath: string): void { } } +function writeLockFile(lockPath: string): void { + const fd = fs.openSync(lockPath, 'wx'); + fs.writeSync(fd, `${process.pid}\n${Date.now()}\n`); + fs.closeSync(fd); +} + function tryAcquire(lockPath: string, options: Required): boolean { try { - const dir = path.dirname(lockPath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - const fd = fs.openSync(lockPath, 'wx'); - fs.writeSync(fd, `${process.pid}\n${Date.now()}\n`); - fs.closeSync(fd); + // Fast path: assume the lock directory already exists (the common case once a + // team dir is created). This drops an existsSync(dir) stat from EVERY acquire, + // which adds up across the many lock cycles during a team launch. + writeLockFile(lockPath); return true; } catch (err) { const code = (err as NodeJS.ErrnoException).code; + if (code === 'ENOENT') { + // Lock directory missing — create it lazily and acquire in the same call, so + // first-acquire latency in a fresh dir is unchanged. + try { + fs.mkdirSync(path.dirname(lockPath), { recursive: true }); + writeLockFile(lockPath); + return true; + } catch { + // Lost a race (another process created the dir/lock) or still failing — + // fall through to a normal retry on the next loop iteration. + return false; + } + } if (code === 'EEXIST' || code === 'EISDIR') { if (shouldBreakExistingLock(lockPath, options.staleTimeoutMs)) { removeLockPath(lockPath);