Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(catalog): write the models cache and route registry atomically

Jack Rudenkod27b930cbdda
diff --git a/packages/cli/src/fs-atomic.test.ts b/packages/cli/src/fs-atomic.test.ts
new file mode 100644
index 00000000..b85e5b77
--- /dev/null
+++ b/packages/cli/src/fs-atomic.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { writeFileAtomic } from "./fs-atomic.js";
+
+let root: string;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "claudish-fs-atomic-"));
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe("writeFileAtomic", () => {
+ test("writes exact UTF-8 content and leaves no temp file", () => {
+ const path = join(root, "cache.json");
+ const content = '{"value":"hello 🌍"}\n';
+ writeFileAtomic(path, content);
+ expect(readFileSync(path, "utf8")).toBe(content);
+ expect(readdirSync(root)).toEqual(["cache.json"]);
+ expect(existsSync(`${path}.tmp.${process.pid}`)).toBe(false);
+ });
+
+ test("creates parent directories and replaces previous content completely", () => {
+ const path = join(root, "nested", "cache.json");
+ writeFileAtomic(path, "a longer previous value");
+ writeFileAtomic(path, "");
+ expect(readFileSync(path, "utf8")).toBe("");
+ expect(readdirSync(join(root, "nested"))).toEqual(["cache.json"]);
+ });
+
+ test("a failing rename rethrows the filesystem error and removes the temp file", () => {
+ const path = join(root, "target-directory");
+ mkdirSync(path);
+ let error: NodeJS.ErrnoException | undefined;
+ try {
+ writeFileAtomic(path, "cannot replace a directory");
+ } catch (caught) {
+ error = caught as NodeJS.ErrnoException;
+ }
+ expect(error).toBeInstanceOf(Error);
+ expect(error?.syscall).toBe("rename");
+ expect(error?.code).toBe("EISDIR");
+ expect(error?.path).toBe(`${path}.tmp.${process.pid}`);
+ expect(existsSync(`${path}.tmp.${process.pid}`)).toBe(false);
+ expect(readdirSync(root)).toEqual(["target-directory"]);
+ expect(readdirSync(path)).toEqual([]);
+ });
+});
diff --git a/packages/cli/src/fs-atomic.ts b/packages/cli/src/fs-atomic.ts
new file mode 100644
index 00000000..838ced44
--- /dev/null
+++ b/packages/cli/src/fs-atomic.ts
@@ -0,0 +1,24 @@
+import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { dirname } from "node:path";
+
+/**
+ * Write `text` to `path` through a temp file and a rename, so another claudish
+ * process never reads a half-written file. An in-place write truncates first, and
+ * a reader in that window parses broken JSON, which every catalog reader takes for
+ * "no cache": several MCP servers starting together hit it.
+ */
+export function writeFileAtomic(path: string, text: string): void {
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.tmp.${process.pid}`;
+ try {
+ writeFileSync(tmp, text, "utf-8");
+ renameSync(tmp, path);
+ } catch (error) {
+ try {
+ unlinkSync(tmp);
+ } catch {
+ // Nothing was left behind.
+ }
+ throw error;
+ }
+}
diff --git a/packages/cli/src/providers/all-models-cache.ts b/packages/cli/src/providers/all-models-cache.ts
index 8abc3455..ec9841d8 100644
--- a/packages/cli/src/providers/all-models-cache.ts
+++ b/packages/cli/src/providers/all-models-cache.ts
@@ -1,6 +1,8 @@
-import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { dirname, join } from "node:path";
+import { join } from "node:path";
+import { writeFileAtomic } from "../fs-atomic.js";
+import { log } from "../logger.js";
import type { AggregatorEntry } from "../model-loader.js";
import {
type CachedRouteRegistry,
@@ -262,7 +264,12 @@ function readSidecarRegistry(path: string): CachedRouteRegistry | null {
return typeof raw.generationId === "string" && isRouteRegistry(raw.registry)
? (raw as unknown as CachedRouteRegistry)
: null;
- } catch {
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") {
+ log(
+ `[catalog] unreadable route registry for ${path}: ${err instanceof Error ? err.message : String(err)}`
+ );
+ }
return null;
}
}
@@ -297,7 +304,9 @@ export function readAllModelsCache(path: string = ALL_MODELS_CACHE_PATH): DiskCa
let cache: DiskCacheV3 | null;
try {
cache = parseAllModelsCache(JSON.parse(readFileSync(path, "utf-8")));
- } catch {
+ } catch (err) {
+ // Memoized under this mtime and size, so logged once per version of the file.
+ log(`[catalog] unreadable ${path}: ${err instanceof Error ? err.message : String(err)}`);
cache = null;
}
if (cache && !cache.routeRegistry && side) {
@@ -320,16 +329,14 @@ export function writeRouteRegistry(
routeRegistry: CachedRouteRegistry,
path: string = ALL_MODELS_CACHE_PATH
): void {
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(routeRegistryPathFor(path), JSON.stringify(routeRegistry), "utf-8");
+ writeFileAtomic(routeRegistryPathFor(path), JSON.stringify(routeRegistry));
_readMemo.delete(path);
}
export function writeAllModelsCache(data: DiskCacheV3, path: string = ALL_MODELS_CACHE_PATH): void {
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, JSON.stringify(data), "utf-8");
+ writeFileAtomic(path, JSON.stringify(data));
if (data.routeRegistry) {
- writeFileSync(routeRegistryPathFor(path), JSON.stringify(data.routeRegistry), "utf-8");
+ writeFileAtomic(routeRegistryPathFor(path), JSON.stringify(data.routeRegistry));
}
_readMemo.delete(path);
}