Skip to content

fix: use a unique key for the new-session RPC lock (#227)#228

Open
shani-singh1 wants to merge 1 commit into
agegr:mainfrom
shani-singh1:fix/227-unique-new-session-key
Open

fix: use a unique key for the new-session RPC lock (#227)#228
shani-singh1 wants to merge 1 commit into
agegr:mainfrom
shani-singh1:fix/227-unique-new-session-key

Conversation

@shani-singh1

Copy link
Copy Markdown

Summary

Fixes #227.

POST /api/agent/new derived its de-duplication lock key from Date.now(), which is not unique under concurrency. Two new-session requests that arrive in the same millisecond receive the same AgentSessionWrapper and sessionId, silently merging two independent chats into one pi session.

Root cause

app/api/agent/new/route.ts:

const tempKey = `__new__${Date.now()}`;
const { session, realSessionId } = await startRpcSession(tempKey, "", cwd, toolNames);

startRpcSession coalesces concurrent callers that share a key via an in-flight lock (lib/rpc-manager.ts):

const inflight = locks.get(sessionId);
if (inflight) return inflight;   // returns the SAME session promise

Session creation takes tens–hundreds of ms, so the lock stays in-flight far longer than 1 ms. Any second request that computes the same millisecond-resolution tempKey gets the first request's in-flight promise — and therefore the same real session. The existing comment already calls this a "one-time key"; Date.now() just doesn't guarantee that.

Fix

Use randomUUID() (already imported and used throughout lib/rpc-manager.ts) so each request gets a genuinely unique key. The lock then only ever coalesces retries of the same logical request, never two different new-session requests.

const tempKey = `__new__${randomUUID()}`;

One line of behavior change; no API or type changes.

Testing

  • tsc --noEmit passes
  • eslint passes
  • Two near-simultaneous POST /api/agent/new calls for the same cwd now always return distinct sessionIds (before, same-millisecond calls returned an identical sessionId).

startRpcSession coalesces concurrent callers that pass the same key onto
one shared session (in-flight lock in lib/rpc-manager.ts). The new-session
route derived that key from Date.now(), which has millisecond resolution,
so two POST /api/agent/new requests in the same millisecond received the
same AgentSessionWrapper and sessionId. Two independent chats were then
merged into a single pi session.

Use randomUUID() so the key is unique per request; the lock now only
coalesces retries of the same logical request, never two distinct ones.

Fixes agegr#227
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.

Bug: concurrent "New Session" requests in the same millisecond collide onto one shared agent session

1 participant