From 48bb9625156a20e804e2667760933903e5d4c6d3 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 8 Aug 2026 15:11:58 -0700 Subject: [PATCH] fix(server): serialize account-limits persists Atomic rename prevented torn JSON but not ordering: a slow earlier persist could land after a newer one and drop a provider snapshot from the file. The encode now runs inside a one-permit semaphore, so the last writer always persists the latest map. Co-Authored-By: Claude Fable 5 --- apps/server/src/usage/AccountLimitsService.ts | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/apps/server/src/usage/AccountLimitsService.ts b/apps/server/src/usage/AccountLimitsService.ts index 36ebbf0eb0..774c535ff2 100644 --- a/apps/server/src/usage/AccountLimitsService.ts +++ b/apps/server/src/usage/AccountLimitsService.ts @@ -27,6 +27,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import { writeFileStringAtomically } from "../atomicWrite.ts"; import { ServerConfig } from "../config.ts"; @@ -115,19 +116,28 @@ export const make = Effect.gen(function* () { }), ); - // A cache we cannot write is a colder next start, not a failure. Written - // atomically: the ingestion worker and the RPC-path transcript seed can - // persist concurrently, and an interleaved plain write would corrupt the - // file - which on restart silently drops the Claude snapshot. + // A cache we cannot write is a colder next start, not a failure. The + // ingestion worker and the RPC-path transcript seed can persist + // concurrently, so writes are atomic (no torn JSON) and serialized: the + // snapshot map is read inside the permit, so a slow earlier write can + // never land after - and clobber - a newer one. + const persistLock = yield* Semaphore.make(1); const persist = Effect.fn("AccountLimitsService.persist")(function* () { - yield* encodeLimitsCache([...snapshots.values()]).pipe( - Effect.flatMap((serialized) => - writeFileStringAtomically({ filePath: cachePath, contents: serialized }), - ), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.catchCause(() => Effect.void), - ); + yield* persistLock + .withPermits(1)( + Effect.suspend(() => + encodeLimitsCache([...snapshots.values()]).pipe( + Effect.flatMap((serialized) => + writeFileStringAtomically({ filePath: cachePath, contents: serialized }), + ), + ), + ), + ) + .pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catchCause(() => Effect.void), + ); }); const store = Effect.fn("AccountLimitsService.store")(function* (