Skip to content
TypeScript

fix(server): caches and ids are written atomically (#16242)

Julius Marmingeeef36a67c37f
diff --git a/apps/server/src/atomicWrite.test.ts b/apps/server/src/atomicWrite.test.ts
index 172c9703a30..28cc1e3ca8c 100644
--- a/apps/server/src/atomicWrite.test.ts
+++ b/apps/server/src/atomicWrite.test.ts
@@ -137,3 +137,49 @@ it.effect("surfaces an unreadable link instead of writing over it", () =>
),
),
);
+
+it.effect("succeeds when the write lands but its temp directory cannot be removed", () =>
+ Effect.gen(function* () {
+ const renamed: Array<string> = [];
+ const removed: Array<string> = [];
+ const fileSystem = FileSystem.layerNoop({
+ // The target does not exist yet, so it is written in place.
+ readLink: (path) =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "NotFound",
+ module: "FileSystem",
+ method: "readLink",
+ pathOrDescriptor: path,
+ }),
+ ),
+ makeDirectory: () => Effect.void,
+ makeTempDirectory: () => Effect.succeed("/home/settings.json.abc123"),
+ writeFileString: () => Effect.void,
+ rename: (_from, to) => Effect.sync(() => void renamed.push(to)),
+ remove: (path) =>
+ Effect.sync(() => void removed.push(path)).pipe(
+ Effect.andThen(
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "PermissionDenied",
+ module: "FileSystem",
+ method: "remove",
+ pathOrDescriptor: path,
+ }),
+ ),
+ ),
+ ),
+ });
+
+ const result = yield* Effect.exit(
+ writeFileStringAtomically({ filePath: "/home/settings.json", contents: "after" }).pipe(
+ Effect.provide(Layer.mergeAll(Path.layer, fileSystem)),
+ ),
+ );
+
+ assert.deepStrictEqual(result, Exit.void);
+ assert.deepStrictEqual(renamed, ["/home/settings.json"]);
+ assert.deepStrictEqual(removed, ["/home/settings.json.abc123"]);
+ }),
+);
diff --git a/apps/server/src/atomicWrite.ts b/apps/server/src/atomicWrite.ts
index 8a7fb20f2ae..bdceff501d6 100644
--- a/apps/server/src/atomicWrite.ts
+++ b/apps/server/src/atomicWrite.ts
@@ -20,10 +20,16 @@ export const writeFileStringAtomically = (input: {
const targetDirectory = path.dirname(targetPath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
- const tempDirectory = yield* fs.makeTempDirectoryScoped({
- directory: targetDirectory,
- prefix: `${path.basename(targetPath)}.`,
- });
+ // The temp directory is cleanup, not part of the write: failing to remove
+ // it (a virus scanner holding it on Windows) must not fail a write that
+ // already landed.
+ const tempDirectory = yield* Effect.acquireRelease(
+ fs.makeTempDirectory({
+ directory: targetDirectory,
+ prefix: `${path.basename(targetPath)}.`,
+ }),
+ (directory) => fs.remove(directory, { recursive: true }).pipe(Effect.ignore({ log: true })),
+ );
const tempPath = path.join(tempDirectory, "contents.tmp");
yield* fs.writeFileString(tempPath, input.contents);
diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts
index 261ae79a680..2e3cb3d0f71 100644
--- a/apps/server/src/device/LocalDeviceHost.ts
+++ b/apps/server/src/device/LocalDeviceHost.ts
@@ -47,6 +47,7 @@ import { HttpClient } from "effect/http";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as DeviceHost from "./DeviceHost.ts";
@@ -354,7 +355,11 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
port: Number(new URL(hub.origin).port),
entryPath: hubTool.entryPath,
}).pipe(
- Effect.flatMap((json) => fs.writeFileString(hubStatePath(), json)),
+ Effect.flatMap((contents) =>
+ writeFileStringAtomically({ filePath: hubStatePath(), contents }),
+ ),
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
Effect.ignore,
);
diff --git a/apps/server/src/provider/ModelManifest.ts b/apps/server/src/provider/ModelManifest.ts
index 2b518b58491..fd0fa1042a2 100644
--- a/apps/server/src/provider/ModelManifest.ts
+++ b/apps/server/src/provider/ModelManifest.ts
@@ -30,6 +30,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientResponse } from "effect/http";
+import { writeFileStringAtomically } from "../atomicWrite.ts";
import { ServerConfig } from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts";
@@ -411,7 +412,9 @@ export const make = Effect.gen(function* () {
manifest = fetched;
fetchedAtMs = now;
yield* encodeManifestCache({ fetchedAtMs: now, manifest: fetched }).pipe(
- Effect.flatMap((serialized) => fileSystem.writeFileString(cachePath, serialized)),
+ Effect.flatMap((contents) => writeFileStringAtomically({ filePath: cachePath, contents })),
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(Path.Path, path),
Effect.ignoreCause,
);
return manifest;
diff --git a/apps/server/src/provider/OpenCodeServerLedger.ts b/apps/server/src/provider/OpenCodeServerLedger.ts
index ef833571862..c6b74aeb88f 100644
--- a/apps/server/src/provider/OpenCodeServerLedger.ts
+++ b/apps/server/src/provider/OpenCodeServerLedger.ts
@@ -8,6 +8,7 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
+import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ServerConfig from "../config.ts";
import { signalProcessGroup } from "../process/processGroup.ts";
@@ -245,8 +246,13 @@ export const make = Effect.fn("OpenCodeServerLedger.make")(function* (input: {
stateDir: input.stateDir,
owner,
};
- yield* fs.makeDirectory(directory, { recursive: true });
- yield* fs.writeFileString(entryPath, yield* encodeEntry(entry));
+ yield* writeFileStringAtomically({
+ filePath: entryPath,
+ contents: yield* encodeEntry(entry),
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ );
return fs
.remove(entryPath, { force: true })
.pipe(
diff --git a/apps/server/src/telemetry/Identify.test.ts b/apps/server/src/telemetry/Identify.test.ts
index c4240be1834..6885946a631 100644
--- a/apps/server/src/telemetry/Identify.test.ts
+++ b/apps/server/src/telemetry/Identify.test.ts
@@ -6,6 +6,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
+import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as ServerConfig from "../config.ts";
@@ -57,6 +58,45 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => {
),
);
+ it.effect("leaves no torn anonymous id behind when its write fails midway", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const tornWrites = FileSystem.FileSystem.of({
+ ...fileSystem,
+ writeFileString: (filePath, data, options) =>
+ fileSystem
+ .writeFileString(filePath, data.slice(0, Math.floor(data.length / 2)), options)
+ .pipe(
+ Effect.andThen(
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "WriteZero",
+ module: "FileSystem",
+ method: "writeFileString",
+ pathOrDescriptor: filePath,
+ }),
+ ),
+ ),
+ ),
+ });
+
+ const identifier = yield* Identify.getTelemetryIdentifierForHome(
+ path.join(config.baseDir, "home"),
+ ).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites));
+
+ assert.isNull(identifier);
+ assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath));
+ }).pipe(
+ Effect.provide(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-telemetry-identify-torn-",
+ }),
+ ),
+ ),
+ );
+
it.effect.each([
{
login: "an API key",
diff --git a/apps/server/src/telemetry/Identify.ts b/apps/server/src/telemetry/Identify.ts
index 13aec2968fe..dcb59d8bb3f 100644
--- a/apps/server/src/telemetry/Identify.ts
+++ b/apps/server/src/telemetry/Identify.ts
@@ -8,6 +8,7 @@ import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
+import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ServerConfig from "../config.ts";
/**
@@ -240,7 +241,7 @@ const upsertAnonymousId = Effect.gen(function* () {
}),
),
);
- yield* fileSystem.writeFileString(anonymousIdPath, anonymousId).pipe(
+ yield* writeFileStringAtomically({ filePath: anonymousIdPath, contents: anonymousId }).pipe(
Effect.mapError(
(cause) =>
new TelemetryAnonymousIdPersistenceError({
diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts
index 6a3c75f79e4..c2206a53d33 100644
--- a/apps/server/src/usage/UsageService.ts
+++ b/apps/server/src/usage/UsageService.ts
@@ -44,6 +44,7 @@ import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { HttpClient, HttpClientResponse } from "effect/http";
+import { writeFileStringAtomically } from "../atomicWrite.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import * as ServerSettings from "../serverSettings.ts";
@@ -204,6 +205,11 @@ export const make = Effect.gen(function* () {
const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");
const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME);
const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME);
+ const writeCacheFile = (filePath: string, contents: string) =>
+ writeFileStringAtomically({ filePath, contents }).pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ Effect.provideService(Path.Path, path),
+ );
let rates: RateTable = new Map();
let ratesFetchedAtMs: number | null = null;
let ratesStatus: UsagePricing["status"] = "unavailable";
@@ -267,7 +273,7 @@ export const make = Effect.gen(function* () {
ratesStatus = "fresh";
yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(
- Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),
+ Effect.flatMap((contents) => writeCacheFile(ratesCachePath, contents)),
Effect.ignoreCause,
);
});
@@ -419,8 +425,8 @@ export const make = Effect.gen(function* () {
);
const writeScanCache = makeScanCacheWriter();
- // Scans with different windows can finish together; two writes interleaved
- // in one file would corrupt it.
+ // Scans with different windows can finish together; serializing the writes
+ // keeps an older snapshot from landing after a newer one.
const persistLock = yield* Semaphore.make(1);
const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {
@@ -432,7 +438,7 @@ export const make = Effect.gen(function* () {
yield* Effect.sync(() =>
writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }),
).pipe(
- Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),
+ Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)),
// A cache we cannot write is a slower next start, not a failed read.
Effect.catchCause(() =>
Effect.sync(() => {