diff --git a/apps/server/src/usage/AccountLimitsService.ts b/apps/server/src/usage/AccountLimitsService.ts index 7061fe487b..36ebbf0eb0 100644 --- a/apps/server/src/usage/AccountLimitsService.ts +++ b/apps/server/src/usage/AccountLimitsService.ts @@ -28,6 +28,7 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { writeFileStringAtomically } from "../atomicWrite.ts"; import { ServerConfig } from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; @@ -114,10 +115,17 @@ export const make = Effect.gen(function* () { }), ); - // A cache we cannot write is a colder next start, not a failure. + // 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. const persist = Effect.fn("AccountLimitsService.persist")(function* () { yield* encodeLimitsCache([...snapshots.values()]).pipe( - Effect.flatMap((serialized) => fileSystem.writeFileString(cachePath, serialized)), + Effect.flatMap((serialized) => + writeFileStringAtomically({ filePath: cachePath, contents: serialized }), + ), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), Effect.catchCause(() => Effect.void), ); }); diff --git a/apps/server/src/usage/accountLimitsTranscripts.ts b/apps/server/src/usage/accountLimitsTranscripts.ts index 05c4e10a5f..07683fa6f1 100644 --- a/apps/server/src/usage/accountLimitsTranscripts.ts +++ b/apps/server/src/usage/accountLimitsTranscripts.ts @@ -25,10 +25,12 @@ import { listTranscriptFiles } from "./usageTranscriptReader.ts"; const TAIL_BYTES = 256 * 1024; const SCAN_WINDOW_DAYS = 14; /** - * Newest-first cutoff. The newest file almost always hits; the rest cover a - * newest file that happens to be a side-meter-only session (Spark). + * Newest-first cutoff bounding the scan on the RPC path. The newest file + * almost always hits; the margin covers runs of files without a main-meter + * snapshot (Spark-only sessions, sessions abandoned before any token count). + * If this many consecutive files lack one, the data is genuinely absent. */ -const MAX_FILES = 8; +const MAX_FILES = 32; export interface CodexTranscriptRateLimits { readonly snapshot: CodexRateLimitsSnapshot;