Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Honor config lock acquisition deadlines (#5260)
Nick Gomez663908831b41
diff --git a/.changeset/config-lock-deadlines.md b/.changeset/config-lock-deadlines.mdnew file mode 100644index 000000000..a112483c7--- /dev/null+++ b/.changeset/config-lock-deadlines.md@@ -0,0 +1,5 @@+---+'@inkeep/open-knowledge': patch+---++Config writes now stop waiting when their lock acquisition deadline expires.diff --git a/packages/cli/tests/integration/mcp-host-config-race.test.ts b/packages/cli/tests/integration/mcp-host-config-race.test.tsindex a1f574a06..b06ac3366 100644--- a/packages/cli/tests/integration/mcp-host-config-race.test.ts+++ b/packages/cli/tests/integration/mcp-host-config-race.test.ts@@ -2,7 +2,15 @@ import { spawn as nativeSpawn } from 'node:child_process';import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { arrangeExpiredFileLock } from '../../../core/src/util/file-lock-deadline.test-helper.ts';+import { EDITOR_TARGETS } from '../../src/commands/editors.ts';+import { writeEditorMcpConfig } from '../../src/commands/init.ts';++vi.mock('node:fs', async (importOriginal) => {+ const fs = await importOriginal<typeof import('node:fs')>();+ return { ...fs, openSync: vi.fn(fs.openSync) };+});const WORKER_PATH = resolve(__dirname, '_helpers', 'config-race-worker.ts');const WORKER_TIMEOUT_MS = 30_000;@@ -69,9 +77,33 @@ describe('mcp host config — concurrent-write race', () => {});afterEach(() => {+ vi.restoreAllMocks();+ vi.resetAllMocks();rmSync(testRoot, { recursive: true, force: true });});+ it.each(['stable', 'disappearing'] as const)(+ 'reports the acquisition deadline without changing config for a %s lock',+ async (schedule) => {+ const original = readFileSync(configPath, 'utf-8');+ await arrangeExpiredFileLock(`${configPath}.lock`, schedule, 5_000);+ const target = {+ ...EDITOR_TARGETS.cursor,+ configPath: () => configPath,+ serverName: () => 'deadline-writer',+ };++ const result = writeEditorMcpConfig(target, '', {+ mode: 'published',+ skipAvailabilityCheck: true,+ });++ expect(result.action).toBe('failed');+ expect(result.error).toBe(`Could not acquire file lock at ${configPath}.lock within 5000ms`);+ expect(readFileSync(configPath, 'utf-8')).toBe(original);+ },+ );+it('N=20 concurrent writers all add their entries; no lost updates, no corruption, no destruction of pre-existing servers', async () => {const N = 20;const expectedKeys = Array.from({ length: N }, (_, i) => `ok-writer-${i}`);diff --git a/packages/core/src/util/file-lock-deadline.test-helper.ts b/packages/core/src/util/file-lock-deadline.test-helper.tsnew file mode 100644index 000000000..cb8150135--- /dev/null+++ b/packages/core/src/util/file-lock-deadline.test-helper.ts@@ -0,0 +1,34 @@+import { openSync } from 'node:fs';+import { vi } from 'vitest';++export async function arrangeExpiredFileLock(+ lockPath: string,+ schedule: 'stable' | 'disappearing' | 'stale',+ timeoutMs: number,+): Promise<void> {+ const fs = await vi.importActual<typeof import('node:fs')>('node:fs');+ const startedAt = Date.now();+ let expiredAt: number | undefined;+ vi.spyOn(Date, 'now').mockImplementation(() =>+ expiredAt === undefined ? startedAt : expiredAt++,+ );+ let attempts = 0;++ vi.mocked(openSync).mockImplementation((path, flags, mode) => {+ if (path !== lockPath) return fs.openSync(path, flags, mode);+ if (attempts++ < 2) {+ fs.writeFileSync(lockPath, '');+ if (schedule === 'stale') {+ const modifiedAt = new Date(startedAt - timeoutMs * 3);+ fs.utimesSync(lockPath, modifiedAt, modifiedAt);+ }+ }+ try {+ return fs.openSync(path, flags, mode);+ } catch (error) {+ expiredAt ??= startedAt + timeoutMs + 1;+ if (schedule === 'disappearing') fs.unlinkSync(lockPath);+ throw error;+ }+ });+}diff --git a/packages/core/src/util/file-lock-deadline.test.ts b/packages/core/src/util/file-lock-deadline.test.tsnew file mode 100644index 000000000..146f9662e--- /dev/null+++ b/packages/core/src/util/file-lock-deadline.test.ts@@ -0,0 +1,61 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { withFileLock, withFileLockSync } from './file-lock.ts';+import { arrangeExpiredFileLock } from './file-lock-deadline.test-helper.ts';++vi.mock('node:fs', async (importOriginal) => {+ const fs = await importOriginal<typeof import('node:fs')>();+ return { ...fs, openSync: vi.fn(fs.openSync) };+});++let directory: string;++beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), 'ok-file-lock-deadline-'));+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.resetAllMocks();+ rmSync(directory, { recursive: true, force: true });+});++describe.each(['sync', 'async'] as const)('%s acquisition deadline', (variant) => {+ test.each(['stable', 'disappearing', 'stale'] as const)(+ 'keeps the protected file unchanged when a %s lock exhausts acquisition',+ async (schedule) => {+ const targetPath = join(directory, 'target.json');+ const lockPath = `${targetPath}.lock`;+ const timeoutMs = 5_000;+ writeFileSync(targetPath, 'original');+ await arrangeExpiredFileLock(lockPath, schedule, timeoutMs);++ const write = () => writeFileSync(targetPath, 'unexpected');+ const attempt = Promise.resolve().then(() =>+ variant === 'sync'+ ? withFileLockSync(lockPath, write, { timeoutMs })+ : withFileLock(lockPath, async () => write(), { timeoutMs }),+ );++ await expect(attempt).rejects.toMatchObject({+ name: 'FileLockTimeoutError',+ code: 'LOCK_TIMEOUT',+ lockPath,+ timeoutMs,+ });+ expect(readFileSync(targetPath, 'utf-8')).toBe('original');+ },+ );++ test('permits an immediately available lock without a retry budget', async () => {+ const lockPath = join(directory, 'available.lock');+ const result =+ variant === 'sync'+ ? withFileLockSync(lockPath, () => 'written', { timeoutMs: 0 })+ : await withFileLock(lockPath, async () => 'written', { timeoutMs: 0 });++ expect(result).toBe('written');+ });+});diff --git a/packages/core/src/util/file-lock.ts b/packages/core/src/util/file-lock.tsindex 37f5ef500..9a87aee52 100644--- a/packages/core/src/util/file-lock.ts+++ b/packages/core/src/util/file-lock.ts@@ -28,8 +28,13 @@ export async function withFileLock<T>(const retryIntervalMs = opts.retryIntervalMs ?? 25;const staleThresholdMs = timeoutMs * 2;const deadline = Date.now() + timeoutMs;+ let firstAttempt = true;while (true) {+ if (!firstAttempt && Date.now() >= deadline) {+ throw new FileLockTimeoutError(lockPath, timeoutMs);+ }+ firstAttempt = false;let fd: number;try {fd = openSync(lockPath, 'wx', 0o600);@@ -93,8 +98,13 @@ export function withFileLockSync<T>(const retryIntervalMs = opts.retryIntervalMs ?? 25;const staleThresholdMs = timeoutMs * 2;const deadline = Date.now() + timeoutMs;+ let firstAttempt = true;while (true) {+ if (!firstAttempt && Date.now() >= deadline) {+ throw new FileLockTimeoutError(lockPath, timeoutMs);+ }+ firstAttempt = false;let fd: number;try {fd = openSync(lockPath, 'wx', 0o600);