diff --git a/src/memory/codex.ts b/src/memory/codex.ts index 8f1a9a36..b72c56d2 100644 --- a/src/memory/codex.ts +++ b/src/memory/codex.ts @@ -15,7 +15,7 @@ import { promises as fs } from 'fs'; import { resolve, basename, join } from 'path'; import { getDateLocale } from '../locale/index.js'; import { homedir } from 'os'; -import { createHash } from 'crypto'; +import { createHash, randomUUID } from 'crypto'; import { withFileLock } from '../support/fileLock.js'; import { atomicWriteFile } from '../support/atomicFile.js'; @@ -364,6 +364,15 @@ async function updateIndex(session: CodexSession, summaryPath: string): Promise< }); } +/** + * A session id that does not collide when two sessions start in the same + * millisecond (parallel workers). Keeps the `session-` prefix so ids still + * sort and read by start time; the random suffix makes them unique. + */ +export function newSessionId(now: number = Date.now()): string { + return `session-${now}-${randomUUID()}`; +} + /** * Session builder - incrementally construct a session */ @@ -373,7 +382,7 @@ export class SessionBuilder { constructor(title: string) { this.session = { - id: `session-${Date.now()}`, + id: newSessionId(), title, startedAt: Date.now(), tags: [], diff --git a/src/memory/sessionId.test.ts b/src/memory/sessionId.test.ts new file mode 100644 index 00000000..a32acb89 --- /dev/null +++ b/src/memory/sessionId.test.ts @@ -0,0 +1,35 @@ +// ============================================ +// OpenSwarm - codex session id uniqueness tests +// ============================================ +// +// Session ids used to be `session-${Date.now()}`, so two sessions started in +// the same millisecond (parallel workers) got the same id and their records +// mixed. The id keeps the `session-` prefix and adds a random suffix. + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { SessionBuilder, newSessionId, sessionFilenameSuffix } from './codex.js'; + +const AT = 1_785_050_644_884; + +describe('codex session id', () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it('gives two sessions started in the same millisecond different ids', () => { + vi.useFakeTimers(); + vi.setSystemTime(AT); + const a = new SessionBuilder('same title').getSession(); + const b = new SessionBuilder('same title').getSession(); + expect(a.startedAt).toBe(b.startedAt); + expect(a.id).not.toBe(b.id); + expect(sessionFilenameSuffix(a.id)).not.toBe(sessionFilenameSuffix(b.id)); + }); + + it('keeps the session- prefix so ids still read by start time', () => { + vi.useFakeTimers(); + vi.setSystemTime(AT); + expect(new SessionBuilder('t').getSession().id.startsWith(`session-${AT}-`)).toBe(true); + expect(newSessionId(AT)).toMatch(new RegExp(`^session-${AT}-[0-9a-f-]{36}$`)); + }); +});