Skip to content

fix(usage): serialize addSession to prevent lost updates on concurrent writes - #1201

Open
aakashsharma7 wants to merge 1 commit into
Nano-Collective:mainfrom
aakashsharma7:fix/usage-add-session-concurrency
Open

fix(usage): serialize addSession to prevent lost updates on concurrent writes#1201
aakashsharma7 wants to merge 1 commit into
Nano-Collective:mainfrom
aakashsharma7:fix/usage-add-session-concurrency

Conversation

@aakashsharma7

Copy link
Copy Markdown

Summary of changes

addSession() had a race when multiple sessions finished at the same time (for example parallel subagents). Each caller did a non-atomic read-modify-write on usage.json, so a later write could replace an earlier one using a stale baseline and drop usage data.

Changes

Atomic writes — write to ${filePath}.${uuid}.tmp, then fs.renameSync so concurrent readers never see empty or truncated JSON.
In-process lock— serialize read-modify-write with a Promise-chain lock (withUsageLock), same pattern as session-manager.ts.
addSession is async — now returns Promise<void> and runs inside withUsageLock.
Changeset + test — patch changeset, plus a concurrency regression test that fires several sessions with Promise.all.

Testing

  • pnpm run test:ava source/usage/storage.spec.ts — 35 tests passed
  • pnpm run test:types — 0 errors
  • pnpm run test:knip— no unused exports
  • pnpm run test:lint— Biome clean

…t writes

Serialize read-modify-write calls to usage.json using an in-process Promise-chain lock and write to a temporary file before atomically renaming into place. This prevents concurrent session completions (such as simultaneous subagent runs) from overwriting each other's session usage data and lifetime totals.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant