diff --git a/src/main/claude-usage/scanner-scan.test.ts b/src/main/claude-usage/scanner-scan.test.ts index eb657636c..83fd6356d 100644 --- a/src/main/claude-usage/scanner-scan.test.ts +++ b/src/main/claude-usage/scanner-scan.test.ts @@ -165,6 +165,319 @@ describe('scanClaudeUsageFiles', () => { expect(second.dailyAggregates[0]?.inputTokens).toBe(999) }) + it('dedupes fork copies when only message.id is present (no requestId)', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = (sessionId: string, messageId: string, inputTokens: number): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 100), turn('session-2', 'msg_2', 50)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(150) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg:msg_1']) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg:msg_2']) + }) + + it('dedupes fork copies via uuid when message ids are absent', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = (sessionId: string, uuid: string, inputTokens: number): string => + JSON.stringify({ + type: 'assistant', + sessionId, + uuid, + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo-a', + message: { + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'uuid-1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'uuid-1', 100), turn('session-2', 'uuid-2', 40)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(140) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['uuid:uuid-1']) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['uuid:uuid-2']) + }) + + it('counts turns copied into forked session files exactly once', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile( + originalFile, + [turn('session-1', 'msg_1', 'req_1', 100), turn('session-1', 'msg_2', 'req_2', 200)].join( + '\n' + ) + ) + // Fork copies the original history with preserved message/request IDs but a + // rewritten sessionId, then appends its own new turn. + await writeFile( + forkFile, + [ + turn('session-2', 'msg_1', 'req_1', 100), + turn('session-2', 'msg_2', 'req_2', 200), + turn('session-2', 'msg_3', 'req_3', 400) + ].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const result = await scanClaudeUsageFiles([]) + const totalInput = result.dailyAggregates.reduce( + (sum, aggregate) => sum + aggregate.inputTokens, + 0 + ) + + expect(totalInput).toBe(700) + expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1', 'msg_2:req_2']) + expect(result.processedFiles[0]?.hasDeferredClaims).toBe(false) + expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg_3:req_3']) + expect(result.processedFiles[1]?.hasDeferredClaims).toBe(true) + }) + + it('keeps fork dedupe stable when the original file projection is reused from cache', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'zzzz-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + expect(first.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1']) + + // A fork appears later while the original stays unchanged (cache reuse). + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + const totalInput = second.dailyAggregates.reduce( + (sum, aggregate) => sum + aggregate.inputTokens, + 0 + ) + + expect(totalInput).toBe(150) + expect(second.processedFiles.map((file) => file.ownedDedupeKeys)).toEqual([ + ['msg_1:req_1'], + ['msg_9:req_9'] + ]) + + // Rescanning with the full cache stays stable. + const third = await scanClaudeUsageFiles([], second.processedFiles) + expect(third.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + }) + + it('reclaims fork-copied turns when the owning original file is deleted', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + expect(first.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + expect(first.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1']) + expect(first.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg_9:req_9']) + + // Deleting the owner must reparse deferred forks so they can re-claim the + // copied turn instead of permanently under-counting. + await rm(originalFile) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + expect(second.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 150 + ) + expect(second.processedFiles).toHaveLength(1) + expect(second.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg_1:req_1', 'msg_9:req_9']) + }) + + it('keeps unrelated cached transcripts when a different owner file is deleted', async () => { + const root = await makeClaudeProjectsRoot() + const projectDir = join(root, '.claude', 'projects', 'project-a') + const originalFile = join(projectDir, 'aaaa-original.jsonl') + const forkFile = join(projectDir, 'bbbb-fork.jsonl') + const unrelatedFile = join(projectDir, 'cccc-unrelated.jsonl') + + const turn = ( + sessionId: string, + messageId: string, + requestId: string, + inputTokens: number + ): string => + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: '2026-04-09T10:00:00.000Z', + requestId, + cwd: '/workspace/repo-a', + message: { + id: messageId, + model: 'claude-sonnet-4-6', + usage: { input_tokens: inputTokens, output_tokens: 10 } + } + }) + + await writeFile(originalFile, turn('session-1', 'msg_1', 'req_1', 100)) + await writeFile( + forkFile, + [turn('session-2', 'msg_1', 'req_1', 100), turn('session-2', 'msg_9', 'req_9', 50)].join('\n') + ) + await writeFile(unrelatedFile, turn('session-3', 'msg_u', 'req_u', 25)) + + vi.resetModules() + vi.doMock('os', async () => ({ + ...(await vi.importActual('os')), + homedir: () => root + })) + const { scanClaudeUsageFiles } = await import('./scanner') + + const first = await scanClaudeUsageFiles([]) + const unrelatedBefore = first.processedFiles.find((file) => file.path === unrelatedFile) + expect(unrelatedBefore?.hasDeferredClaims).toBe(false) + expect(unrelatedBefore?.ownedDedupeKeys).toEqual(['msg_u:req_u']) + + await rm(originalFile) + + const second = await scanClaudeUsageFiles([], first.processedFiles) + const unrelatedAfter = second.processedFiles.find((file) => file.path === unrelatedFile) + // Unrelated files must keep their cached projection identity (stat-only path). + expect(unrelatedAfter).toBe(unrelatedBefore) + expect(second.dailyAggregates.reduce((sum, aggregate) => sum + aggregate.inputTokens, 0)).toBe( + 175 + ) + }) + it('canonicalizes repeated cwd paths once per scan file', async () => { const root = await makeClaudeProjectsRoot() const projectDir = join(root, '.claude', 'projects', 'project-a') diff --git a/src/main/claude-usage/scanner.ts b/src/main/claude-usage/scanner.ts index bac5d5cac..db1c1f21f 100644 --- a/src/main/claude-usage/scanner.ts +++ b/src/main/claude-usage/scanner.ts @@ -29,6 +29,8 @@ type ClaudeUsageSourceRecord = { cwd?: string gitBranch?: string requestId?: string + /** Stable row id when present; preserved across fork-copied history. */ + uuid?: string isSidechain?: boolean agentId?: string message?: { @@ -209,9 +211,11 @@ function stripClaudeSourceMetadata(turn: ClaudeUsageParsedSourceTurn): ClaudeUsa } } -function dedupeClaudeUsageTurns(turns: ClaudeUsageParsedSourceTurn[]): ClaudeUsageParsedTurn[] { +function dedupeClaudeUsageTurns( + turns: ClaudeUsageParsedSourceTurn[] +): ClaudeUsageParsedSourceTurn[] { const dedupeIndexByKey = new Map() - const deduped: ClaudeUsageParsedTurn[] = [] + const deduped: ClaudeUsageParsedSourceTurn[] = [] for (const turn of turns) { if (turn.dedupeKey) { @@ -228,8 +232,7 @@ function dedupeClaudeUsageTurns(turns: ClaudeUsageParsedSourceTurn[]): ClaudeUsa } } - const stripped = stripClaudeSourceMetadata(turn) - deduped.push(stripped) + deduped.push({ ...turn }) if (turn.dedupeKey) { dedupeIndexByKey.set(turn.dedupeKey, deduped.length - 1) } @@ -273,8 +276,10 @@ function parseClaudeUsageSourceRecord( model: parsed.message?.model ?? null, cwd: parsed.cwd ?? null, gitBranch: parsed.gitBranch ?? null, - dedupeKey: - parsed.message?.id && parsed.requestId ? `${parsed.message.id}:${parsed.requestId}` : null, + // Why: forks rewrite sessionId but keep message/request ids (and usually + // uuid). Prefer the strongest stable identity available so ownership still + // works when requestId is missing on older or partial rows. + dedupeKey: buildClaudeUsageDedupeKey(parsed), inputTokens, outputTokens, cacheReadTokens, @@ -282,6 +287,22 @@ function parseClaudeUsageSourceRecord( } } +function buildClaudeUsageDedupeKey(parsed: ClaudeUsageSourceRecord): string | null { + const messageId = parsed.message?.id?.trim() + const requestId = parsed.requestId?.trim() + if (messageId && requestId) { + return `${messageId}:${requestId}` + } + if (messageId) { + return `msg:${messageId}` + } + const uuid = parsed.uuid?.trim() + if (uuid) { + return `uuid:${uuid}` + } + return null +} + export function parseClaudeUsageRecord(line: string): ClaudeUsageParsedTurn | null { const parsed = parseClaudeUsageSourceRecord(line) return parsed ? stripClaudeSourceMetadata(parsed) : null @@ -302,12 +323,12 @@ export async function parseClaudeUsageFile(filePath: string): Promise { const fileStat = await stat(filePath) let lineCount = 0 @@ -597,18 +618,6 @@ export function aggregateClaudeUsage(turns: ClaudeUsageAttributedTurn[]): { } } -async function parseClaudeUsagePersistedFile( - filePath: string, - worktreeLookup: Map -): Promise { - const { processedFile, turns } = await readClaudeUsageScanFile(filePath) - const attributed = await attributeClaudeUsageTurns(turns, worktreeLookup) - return { - ...processedFile, - ...aggregateClaudeUsage(attributed) - } -} - export async function scanClaudeUsageFiles( worktrees: ClaudeUsageWorktreeRef[], previousProcessedFiles: ClaudeUsagePersistedFile[] = [] @@ -619,41 +628,122 @@ export async function scanClaudeUsageFiles( }> { const files = await listClaudeTranscriptFiles() const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file])) - const processedFiles: ClaudeUsagePersistedFile[] = [] const worktreeLookup = await buildWorktreeLookup(worktrees) - const sessionsById = new Map() - const dailyByKey = new Map() + const currentPaths = new Set(files) + // Why: when a file that owned dedupe keys is deleted, remaining forks still + // contain those turns but their caches record them as unowned. Only files + // that previously deferred claims can reclaim, so invalidate those — not the + // entire transcript corpus (histories can be gigabytes). + const lostOwnerPath = previousProcessedFiles.some( + (file) => + !currentPaths.has(file.path) && + Array.isArray(file.ownedDedupeKeys) && + file.ownedDedupeKeys.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] for (let index = 0; index < files.length; index += FILE_SCAN_BATCH_SIZE) { const batch = files.slice(index, index + FILE_SCAN_BATCH_SIZE) - const results = await Promise.all( + const reusable = await Promise.all( batch.map(async (filePath) => { const fileInfo = await getProcessedFileStat(filePath) const previous = previousByPath.get(filePath) // Why: Claude histories can be gigabytes. Unchanged files should pay // only stat cost on refresh while preserving exactly the old projection. + // When an owner disappears, only deferred-claim files need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = + !mustReclaimDeferred && previous && previous.mtimeMs === fileInfo.mtimeMs && previous.size === fileInfo.size && Array.isArray(previous.sessions) && - Array.isArray(previous.dailyAggregates) - - return canReuse ? previous : parseClaudeUsagePersistedFile(filePath, worktreeLookup) + Array.isArray(previous.dailyAggregates) && + Array.isArray(previous.ownedDedupeKeys) && + typeof previous.hasDeferredClaims === 'boolean' + return canReuse ? previous : null }) ) - for (const processed of results) { - processedFiles.push(processed) - mergeClaudeSessions(sessionsById, processed.sessions) - mergeClaudeDailyAggregates(dailyByKey, processed.dailyAggregates) + for (const [batchIndex, previous] of reusable.entries()) { + if (previous) { + reusedByPath.set(batch[batchIndex], previous) + } else { + pathsToParse.push(batch[batchIndex]) + } } - // Why: transcript scans run in Electron's main process. Small parallel - // batches cut independent file I/O without letting Settings stay blocked. if (index + batch.length < files.length) { await yieldToEventLoop() } } + // Why: resuming or forking a Claude session copies earlier turns — with their + // original message/request IDs — into a new transcript file under a new + // session id. Per-file dedupe cannot see those copies, so long-lived sessions + // get re-counted on every fork (issue #8006). Cross-file ownership counts each + // turn for exactly one file; cached files keep the claims they persisted. + const turnOwnerByDedupeKey = new Map() + for (const [filePath, previous] of reusedByPath) { + for (const dedupeKey of previous.ownedDedupeKeys) { + // First cached claim wins so conflicting projections stay deterministic. + if (!turnOwnerByDedupeKey.has(dedupeKey)) { + turnOwnerByDedupeKey.set(dedupeKey, filePath) + } + } + } + + const parsedByPath = new Map() + for (let index = 0; index < pathsToParse.length; index += FILE_SCAN_BATCH_SIZE) { + const batch = pathsToParse.slice(index, index + FILE_SCAN_BATCH_SIZE) + // Why: transcript scans run in Electron's main process. Small parallel + // batches cut independent file I/O without letting Settings stay blocked. + const reads = await Promise.all(batch.map((filePath) => readClaudeUsageScanFile(filePath))) + for (const [batchIndex, filePath] of batch.entries()) { + const { processedFile, turns } = reads[batchIndex] + // Why: ownership claims must be sequential in sorted-path order so + // rescans assign duplicated turns to the same file deterministically. + const ownedTurns: ClaudeUsageParsedTurn[] = [] + const ownedDedupeKeys: string[] = [] + let hasDeferredClaims = false + for (const turn of turns) { + if (turn.dedupeKey) { + const owner = turnOwnerByDedupeKey.get(turn.dedupeKey) + if (owner !== undefined && owner !== filePath) { + hasDeferredClaims = true + continue + } + turnOwnerByDedupeKey.set(turn.dedupeKey, filePath) + ownedDedupeKeys.push(turn.dedupeKey) + } + ownedTurns.push(stripClaudeSourceMetadata(turn)) + } + const attributed = await attributeClaudeUsageTurns(ownedTurns, worktreeLookup) + parsedByPath.set(filePath, { + ...processedFile, + ...aggregateClaudeUsage(attributed), + ownedDedupeKeys, + hasDeferredClaims + }) + } + if (index + batch.length < pathsToParse.length) { + await yieldToEventLoop() + } + } + + const processedFiles: ClaudeUsagePersistedFile[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const filePath of files) { + const processed = reusedByPath.get(filePath) ?? parsedByPath.get(filePath) + if (!processed) { + continue + } + processedFiles.push(processed) + mergeClaudeSessions(sessionsById, processed.sessions) + mergeClaudeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedFiles, sessions: finalizeClaudeSessions(sessionsById), diff --git a/src/main/claude-usage/store.ts b/src/main/claude-usage/store.ts index 092ee6aa2..a020186ee 100644 --- a/src/main/claude-usage/store.ts +++ b/src/main/claude-usage/store.ts @@ -19,7 +19,10 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { ClaudeUsagePersistedState } from './types' import { createWorktreeRefs, getSessionProjectLabel, scanClaudeUsageFiles } from './scanner' -const SCHEMA_VERSION = 3 +// Why: v5 widens Claude ownership keys (message-id / uuid fallbacks). Older +// caches either lack ownership or used narrower keys and can under/over-count +// after fork reclaim (#8006). +const SCHEMA_VERSION = 5 const STALE_MS = 5 * 60_000 const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/claude-usage/types.ts b/src/main/claude-usage/types.ts index 8760621d7..ec497e5e0 100644 --- a/src/main/claude-usage/types.ts +++ b/src/main/claude-usage/types.ts @@ -66,6 +66,14 @@ export type ClaudeUsagePersistedState = { export type ClaudeUsagePersistedFile = ClaudeUsageProcessedFile & { sessions: ClaudeUsageSession[] dailyAggregates: ClaudeUsageDailyAggregate[] + /** Dedupe keys (message.id:requestId) this file counted. Forked/resumed + * sessions copy earlier turns into new files; ownership keeps each turn + * counted by exactly one cached file across incremental scans. */ + ownedDedupeKeys: string[] + /** True when this file saw turns already claimed by another file. When that + * owner disappears, only deferred files need reparse to reclaim — not the + * entire transcript corpus. */ + hasDeferredClaims: boolean } export type ClaudeUsageParsedTurn = { diff --git a/src/main/codex-usage/scanner-paths.test.ts b/src/main/codex-usage/scanner-paths.test.ts index 46c10be0c..ecdc03e13 100644 --- a/src/main/codex-usage/scanner-paths.test.ts +++ b/src/main/codex-usage/scanner-paths.test.ts @@ -1,5 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { linkSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + rmSync, + unlinkSync, + writeFileSync +} from 'node:fs' import { tmpdir } from 'node:os' import type * as NodeOs from 'node:os' import { join } from 'node:path' @@ -300,6 +308,216 @@ describe('listCodexSessionFiles', () => { ).toBe(3) }) + it('counts token events copied into forked rollout files exactly once', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const result = await scanCodexUsageFiles([], []) + + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.eventCount, 0) + ).toBe(3) + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]?.totalTokens).toBe(22) + }) + + it('dedupes fork copies even when session_meta id is rewritten', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const originalPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-original', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + // Same token_count records, different session_meta id (real resume/fork shape). + const forkBody = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-fork', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15), + usageRecord('2026-05-26T12:02:00.000Z', 7, 22) + ].join('') + writeFileSync(originalPath, originalPrefix, 'utf-8') + writeFileSync(forkPath, forkBody) + + const result = await scanCodexUsageFiles([], []) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(result.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + expect(result.processedFiles[1]?.ownedEventKeys).toHaveLength(1) + expect(result.processedFiles[1]?.hasDeferredClaims).toBe(true) + }) + + it('does not re-count the cumulative session for copied total-only records', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + totalOnlyUsageRecord('2026-05-26T12:00:00.000Z', 10), + totalOnlyUsageRecord('2026-05-26T12:01:00.000Z', 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + // Without cross-file ownership the fork's first copied total-only record + // re-counts the entire cumulative session (10) as a fresh delta. + writeFileSync( + forkPath, + `${copiedPrefix}${totalOnlyUsageRecord('2026-05-26T12:02:00.000Z', 22)}` + ) + + const result = await scanCodexUsageFiles([], []) + + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.eventCount, 0) + ).toBe(3) + }) + + it('keeps fork dedupe stable when the original file is reused from cache', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'zzzz-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + + const first = await scanCodexUsageFiles([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(15) + expect(first.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + + // A fork appears later while the original stays unchanged (cache reuse). + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const second = await scanCodexUsageFiles([], first.processedFiles) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(second.processedFiles.map((file) => file.ownedEventKeys.length)).toEqual([2, 1]) + + // Rescanning with the full cache stays stable. + const third = await scanCodexUsageFiles([], second.processedFiles) + expect( + third.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + }) + + it('reclaims copied token events when the owning original file is deleted', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + + const first = await scanCodexUsageFiles([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(first.processedFiles[0]?.ownedEventKeys).toHaveLength(2) + expect(first.processedFiles[0]?.hasDeferredClaims).toBe(false) + expect(first.processedFiles[1]?.ownedEventKeys).toHaveLength(1) + expect(first.processedFiles[1]?.hasDeferredClaims).toBe(true) + + // Deleting the owner must reparse deferred forks so they can re-claim the + // copied prefix instead of permanently under-counting. + unlinkSync(originalPath) + + const second = await scanCodexUsageFiles([], first.processedFiles) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(22) + expect(second.processedFiles).toHaveLength(1) + expect(second.processedFiles[0]?.ownedEventKeys).toHaveLength(3) + }) + + it('keeps unrelated cached rollouts when a different owner file is deleted', async () => { + const sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') + mkdirSync(sessionsDir, { recursive: true }) + const originalPath = join(sessionsDir, 'aaaa-original.jsonl') + const forkPath = join(sessionsDir, 'bbbb-fork.jsonl') + const unrelatedPath = join(sessionsDir, 'cccc-unrelated.jsonl') + const copiedPrefix = [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T12:00:00.000Z', 10), + usageRecord('2026-05-26T12:01:00.000Z', 5, 15) + ].join('') + writeFileSync(originalPath, copiedPrefix, 'utf-8') + writeFileSync(forkPath, `${copiedPrefix}${usageRecord('2026-05-26T12:02:00.000Z', 7, 22)}`) + writeFileSync( + unrelatedPath, + [ + `${JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-9', cwd: join(fakeHomeDir, 'repo') } + })}\n`, + usageRecord('2026-05-26T13:00:00.000Z', 3) + ].join('') + ) + + const first = await scanCodexUsageFiles([], []) + const unrelatedBefore = first.processedFiles.find((file) => file.path === unrelatedPath) + expect(unrelatedBefore?.hasDeferredClaims).toBe(false) + expect(unrelatedBefore?.ownedEventKeys).toHaveLength(1) + + unlinkSync(originalPath) + + const second = await scanCodexUsageFiles([], first.processedFiles) + const unrelatedAfter = second.processedFiles.find((file) => file.path === unrelatedPath) + expect(unrelatedAfter).toBe(unrelatedBefore) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) + ).toBe(25) + }) + it('treats a leading total-only source suffix record as baseline', async () => { const runtimeSessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') const runtimeBridgeMarkerDir = join( diff --git a/src/main/codex-usage/scanner.test.ts b/src/main/codex-usage/scanner.test.ts index 62777257b..642622246 100644 --- a/src/main/codex-usage/scanner.test.ts +++ b/src/main/codex-usage/scanner.test.ts @@ -99,6 +99,7 @@ describe('parseCodexUsageRecord', () => { expect(first).toEqual({ sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: expect.any(String), cwd: '/workspace/repo/packages/app', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -196,6 +197,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/app2/subdir', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -233,6 +235,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/..fixtures/session', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -263,6 +266,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: '/workspace/repo/../other/session', model: 'gpt-5.2-codex', hasInferredPricing: false, @@ -292,6 +296,7 @@ describe('attributeCodexUsageEvent', () => { { sessionId: 'session-1', timestamp: '2026-04-09T10:00:00.000Z', + eventKey: 'event-1', cwd: 'D:\\other\\repo', model: 'gpt-5.2-codex', hasInferredPricing: false, diff --git a/src/main/codex-usage/scanner.ts b/src/main/codex-usage/scanner.ts index a9764b53b..97e8f6f7b 100644 --- a/src/main/codex-usage/scanner.ts +++ b/src/main/codex-usage/scanner.ts @@ -388,6 +388,28 @@ function resolveCodexUsageDelta( return null } +function buildCodexUsageEventKey( + timestamp: string, + totalUsage: CodexUsageRawUsage | null, + lastUsage: CodexUsageRawUsage | null +): string { + // Why: fork/resume copies token_count records byte-for-byte into a new + // rollout file, but session_meta.id is often rewritten to the new session. + // Key only on the raw record fields (timestamp + usage tuples) so the copy + // matches the original regardless of surrounding parse context / session id. + const tupleOf = (usage: CodexUsageRawUsage | null): string => + usage + ? [ + usage.inputTokens, + usage.cachedInputTokens, + usage.outputTokens, + usage.reasoningOutputTokens, + usage.totalTokens + ].join(',') + : '' + return [timestamp, tupleOf(totalUsage), tupleOf(lastUsage)].join('|') +} + function extractString(value: unknown): string | null { if (typeof value !== 'string') { return null @@ -956,6 +978,7 @@ export function parseCodexUsageRecord( return { sessionId: context.sessionId, timestamp: parsed.timestamp, + eventKey: buildCodexUsageEventKey(parsed.timestamp, totalUsage, lastUsage), cwd: context.currentCwd ?? context.sessionCwd, model: resolvedModel, hasInferredPricing, @@ -970,7 +993,7 @@ export function parseCodexUsageRecord( export async function parseCodexUsageFile( filePath: string, worktrees: (CodexUsageWorktreeRef & { canonicalPath: string })[], - options: { skipInitialBytes?: number } = {} + options: { skipInitialBytes?: number; claimEventKey?: (eventKey: string) => boolean } = {} ): Promise { const processedFile = await getProcessedFileInfo(filePath) const lines = createInterface({ @@ -992,11 +1015,21 @@ export async function parseCodexUsageFile( totalOnlyBaselinePending: (options.skipInitialBytes ?? 0) > 0 } + const ownedEventKeys = new Set() + let hasDeferredClaims = false for await (const line of lines) { const parsed = parseCodexUsageRecord(line, context) if (!parsed) { continue } + // Why: fork/resume rollouts start with a copied prefix of the parent file. + // Events another file already owns are dropped here, but the record still + // advanced context.previousTotals above, so later deltas stay correct. + if (options.claimEventKey && !options.claimEventKey(parsed.eventKey)) { + hasDeferredClaims = true + continue + } + ownedEventKeys.add(parsed.eventKey) const attributed = await attributeCodexUsageEvent(parsed, worktrees) if (attributed) { events.push(attributed) @@ -1005,7 +1038,9 @@ export async function parseCodexUsageFile( return { ...processedFile, - ...aggregateCodexUsage(events) + ...aggregateCodexUsage(events), + ownedEventKeys: [...ownedEventKeys], + hasDeferredClaims } } @@ -1019,31 +1054,77 @@ export async function scanCodexUsageFiles( }> { const files = await listCodexSessionFiles() const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file])) - const processedFiles: CodexUsagePersistedFile[] = [] const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees) const legacySourceSkipBytesByPath = getLegacySourceSkipBytesByPath(files) - const sessionsById = new Map() - const dailyByKey = new Map() + const currentPaths = new Set(files) + // Why: when a rollout that owned event keys is deleted, remaining forks still + // contain those records but their caches record them as unowned. Only files + // that previously deferred claims can reclaim, so invalidate those — not the + // entire rollout corpus. + const lostOwnerPath = previousProcessedFiles.some( + (file) => + !currentPaths.has(file.path) && + Array.isArray(file.ownedEventKeys) && + file.ownedEventKeys.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] for (const [index, filePath] of files.entries()) { const legacySourceSkipBytes = legacySourceSkipBytesByPath.get(filePath) ?? 0 const fileInfo = await getProcessedFileInfo(filePath) const previous = previousByPath.get(filePath) + // When an owner disappears, only deferred-claim files need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = + !mustReclaimDeferred && legacySourceSkipBytes === 0 && previous && previous.mtimeMs === fileInfo.mtimeMs && - previous.size === fileInfo.size + previous.size === fileInfo.size && + Array.isArray(previous.ownedEventKeys) && + typeof previous.hasDeferredClaims === 'boolean' + if (canReuse) { + reusedByPath.set(filePath, previous) + } else { + pathsToParse.push(filePath) + } + if ((index + 1) % YIELD_EVERY_FILES === 0) { + await yieldToEventLoop() + } + } - const processed = canReuse - ? previous - : await parseCodexUsageFile(filePath, worktreesWithCanonicalPaths, { - skipInitialBytes: legacySourceSkipBytes - }) + // Why: resuming or forking a Codex session copies the parent rollout's + // token_count records into a new file, so per-file parsing re-counts the + // whole copied history once per descendant (#8006). Cross-file ownership + // counts each record for exactly one file; cached files keep the claims + // they persisted, and new files claim in sorted-path order so rescans stay + // deterministic. + const eventOwnerByKey = new Map() + for (const [filePath, previous] of reusedByPath) { + for (const eventKey of previous.ownedEventKeys) { + // First cached claim wins so conflicting projections stay deterministic. + if (!eventOwnerByKey.has(eventKey)) { + eventOwnerByKey.set(eventKey, filePath) + } + } + } - processedFiles.push(processed) - mergeSessions(sessionsById, processed.sessions) - mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + const parsedByPath = new Map() + for (const [index, filePath] of pathsToParse.entries()) { + const processed = await parseCodexUsageFile(filePath, worktreesWithCanonicalPaths, { + skipInitialBytes: legacySourceSkipBytesByPath.get(filePath) ?? 0, + claimEventKey: (eventKey) => { + const owner = eventOwnerByKey.get(eventKey) + if (owner !== undefined && owner !== filePath) { + return false + } + eventOwnerByKey.set(eventKey, filePath) + return true + } + }) + parsedByPath.set(filePath, processed) // Why: Codex session history can grow large, and scans run on the Electron // main process. Yield regularly so opening Settings does not stall while @@ -1053,6 +1134,19 @@ export async function scanCodexUsageFiles( } } + const processedFiles: CodexUsagePersistedFile[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const filePath of files) { + const processed = reusedByPath.get(filePath) ?? parsedByPath.get(filePath) + if (!processed) { + continue + } + processedFiles.push(processed) + mergeSessions(sessionsById, processed.sessions) + mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedFiles, sessions: finalizeSessions(sessionsById), diff --git a/src/main/codex-usage/store.test.ts b/src/main/codex-usage/store.test.ts index 1bb373237..055af8f3a 100644 --- a/src/main/codex-usage/store.test.ts +++ b/src/main/codex-usage/store.test.ts @@ -111,7 +111,7 @@ describe('CodexUsageStore', () => { it('persists a successful refresh with one compact disk write', async () => { const store = createStoreWithState({ - schemaVersion: 3, + schemaVersion: 5, scanState: { enabled: true, lastScanStartedAt: null, @@ -138,7 +138,7 @@ describe('CodexUsageStore', () => { const pendingScan = createDeferred() vi.mocked(scanCodexUsageFiles).mockReturnValueOnce(pendingScan.promise) const store = createStoreWithState({ - schemaVersion: 3, + schemaVersion: 5, scanState: { enabled: true, lastScanStartedAt: null, @@ -768,7 +768,7 @@ describe('CodexUsageStore', () => { } as unknown as CodexUsagePersistedState) expect(normalized).toEqual({ - schemaVersion: 3, + schemaVersion: 5, worktreeFingerprint: null, processedFiles: [], sessions: [], diff --git a/src/main/codex-usage/store.ts b/src/main/codex-usage/store.ts index e2963245c..ca42ba340 100644 --- a/src/main/codex-usage/store.ts +++ b/src/main/codex-usage/store.ts @@ -19,7 +19,10 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { CodexUsagePersistedState } from './types' import { createWorktreeRefs, scanCodexUsageFiles } from './scanner' -const SCHEMA_VERSION = 3 +// Why: v5 keys Codex ownership on raw token_count identity without session id +// so forks that rewrite session_meta still match. Older caches used session- +// scoped keys and can double-count after fork/resume (#8006). +const SCHEMA_VERSION = 5 const STALE_MS = 5 * 60_000 const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/codex-usage/types.ts b/src/main/codex-usage/types.ts index 4b54c6f6c..d7e6f058b 100644 --- a/src/main/codex-usage/types.ts +++ b/src/main/codex-usage/types.ts @@ -86,6 +86,14 @@ export type CodexUsageDailyAggregate = { export type CodexUsagePersistedFile = CodexUsageProcessedFile & { sessions: CodexUsageSession[] dailyAggregates: CodexUsageDailyAggregate[] + /** Event keys this file counted. Resumed/forked rollouts copy earlier + * token_count records into new files; ownership keeps each record counted + * by exactly one cached file across incremental scans. */ + ownedEventKeys: string[] + /** True when this file saw events already claimed by another file. When that + * owner disappears, only deferred files need reparse to reclaim — not the + * entire rollout corpus. */ + hasDeferredClaims: boolean } export type CodexUsagePersistedState = { @@ -105,6 +113,10 @@ export type CodexUsagePersistedState = { export type CodexUsageParsedEvent = { sessionId: string timestamp: string + /** Raw-record identity (timestamp + token tuples) used to dedupe the same + * token_count record copied across fork/resume rollout files. Session id is + * omitted because forks rewrite session_meta while copying the record. */ + eventKey: string model: string | null cwd: string | null hasInferredPricing: boolean diff --git a/src/main/opencode-usage/scanner.test.ts b/src/main/opencode-usage/scanner.test.ts index c4bd46aae..fbdc56bb5 100644 --- a/src/main/opencode-usage/scanner.test.ts +++ b/src/main/opencode-usage/scanner.test.ts @@ -1,12 +1,13 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, unlinkSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import Database from '../sqlite/sync-database' import { attributeOpenCodeUsageEvent, parseOpenCodeUsageDatabase, - parseOpenCodeUsageRow + parseOpenCodeUsageRow, + scanOpenCodeUsageDatabases } from './scanner' const WORKTREE = '/workspace/repo' @@ -32,6 +33,50 @@ function worktrees() { ] } +function createSessionTotalsSchema(db: Database.Database): void { + db.exec(` + CREATE TABLE session ( + id TEXT PRIMARY KEY, + directory TEXT, + title TEXT, + model TEXT, + cost REAL, + tokens_input INTEGER, + tokens_output INTEGER, + tokens_reasoning INTEGER, + tokens_cache_read INTEGER, + time_created INTEGER, + time_updated INTEGER + ); + `) +} + +function insertSessionTotalsRow( + db: Database.Database, + sessionId: string, + inputTokens: number +): void { + db.prepare( + `INSERT INTO session ( + id, directory, title, model, cost, + tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, + time_created, time_updated + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ).run( + sessionId, + `${WORKTREE}/packages/app`, + 'Session', + JSON.stringify({ providerID: 'anthropic', id: 'claude-sonnet-4-5' }), + 0.01, + inputTokens, + 100, + 0, + 0, + 1_777_777_700_000, + 1_777_777_800_000 + ) +} + function usageEvent(cwd: string) { return { sessionId: 'session-1', @@ -259,6 +304,17 @@ describe('parseOpenCodeUsageDatabase', () => { }) }) + it('reports the session ids the database counted', async () => { + const { db, path } = createTempDb() + createSessionTotalsSchema(db) + insertSessionTotalsRow(db, 'session-1', 1000) + db.close() + + const parsed = await parseOpenCodeUsageDatabase(path, worktrees()) + + expect(parsed.ownedSessionIds).toEqual(['session-1']) + }) + it('prefers session_message rows over legacy message rows to avoid double counting', async () => { const { db, path } = createTempDb() db.exec(` @@ -324,3 +380,154 @@ describe('parseOpenCodeUsageDatabase', () => { expect(parsed.sessions[0]?.eventCount).toBe(1) }) }) + +describe('scanOpenCodeUsageDatabases', () => { + let dataRoot: string + let openCodeDir: string + let previousXdgDataHome: string | undefined + let previousOpenCodeDb: string | undefined + + beforeEach(() => { + dataRoot = mkdtempSync(join(tmpdir(), 'orca-opencode-usage-scan-')) + openCodeDir = join(dataRoot, 'opencode') + mkdirSync(openCodeDir, { recursive: true }) + previousXdgDataHome = process.env.XDG_DATA_HOME + previousOpenCodeDb = process.env.OPENCODE_DB + process.env.XDG_DATA_HOME = dataRoot + delete process.env.OPENCODE_DB + }) + + afterEach(() => { + if (previousXdgDataHome === undefined) { + delete process.env.XDG_DATA_HOME + } else { + process.env.XDG_DATA_HOME = previousXdgDataHome + } + if (previousOpenCodeDb === undefined) { + delete process.env.OPENCODE_DB + } else { + process.env.OPENCODE_DB = previousOpenCodeDb + } + rmSync(dataRoot, { recursive: true, force: true }) + }) + + function writeSessionTotalsDb(fileName: string, rows: [string, number][]): string { + const path = join(openCodeDir, fileName) + const db = new Database(path) + createSessionTotalsSchema(db) + for (const [sessionId, inputTokens] of rows) { + insertSessionTotalsRow(db, sessionId, inputTokens) + } + db.close() + return path + } + + it('counts a session duplicated into a stale backup database exactly once', async () => { + // The backup holds a stale snapshot of session-1; the canonical db has + // grown since. The canonical totals must win and be counted once. + writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 300] + ]) + writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) + + const result = await scanOpenCodeUsageDatabases([], []) + + expect(result.sessions).toHaveLength(2) + const sessionOne = result.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + expect( + result.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1300) + }) + + it('still counts backup-only sessions and stays stable across cached rescans', async () => { + const canonicalPath = writeSessionTotalsDb('opencode.db', [['session-1', 1000]]) + // The backup duplicates session-1 (stale) and preserves session-9, which + // no longer exists in the canonical database. + writeSessionTotalsDb('opencode-backup.db', [ + ['session-1', 400], + ['session-9', 50] + ]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1050) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1050) + + // The canonical db keeps growing while the backup stays cached; session-1 + // must stay owned by the canonical db. + const db = new Database(canonicalPath) + insertSessionTotalsRow(db, 'session-2', 200) + db.close() + + const third = await scanOpenCodeUsageDatabases([], second.processedDatabases) + expect( + third.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1250) + const sessionOne = third.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + }) + + it('lets the live database reclaim sessions after a sticky backup-only claim', async () => { + // First scan only has the backup (e.g. live db temporarily missing), so it + // owns session-1 at the stale snapshot. When opencode.db reappears with + // higher totals it must reclaim the session instead of staying frozen. + writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(400) + expect(first.processedDatabases[0]?.ownedSessionIds).toEqual(['session-1']) + + writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 200] + ]) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1200) + const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(1000) + expect(sessionOne?.eventCount).toBe(1) + }) + + it('reclaims sessions when the owning live database is deleted', async () => { + const canonicalPath = writeSessionTotalsDb('opencode.db', [ + ['session-1', 1000], + ['session-2', 200] + ]) + writeSessionTotalsDb('opencode-backup.db', [ + ['session-1', 400], + ['session-9', 50] + ]) + + const first = await scanOpenCodeUsageDatabases([], []) + expect( + first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(1250) + + unlinkSync(canonicalPath) + + const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) + expect( + second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) + ).toBe(450) + expect(second.sessions.map((session) => session.sessionId).sort()).toEqual([ + 'session-1', + 'session-9' + ]) + const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') + expect(sessionOne?.totalInputTokens).toBe(400) + }) +}) diff --git a/src/main/opencode-usage/scanner.ts b/src/main/opencode-usage/scanner.ts index 8a6188688..4e2a39635 100644 --- a/src/main/opencode-usage/scanner.ts +++ b/src/main/opencode-usage/scanner.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { readdir, realpath, stat } from 'node:fs/promises' import { homedir } from 'node:os' -import { isAbsolute, join, posix, win32 } from 'node:path' +import { basename, isAbsolute, join, posix, win32 } from 'node:path' import type { Repo } from '../../shared/types' import { areWorktreePathsEqual } from '../ipc/worktree-logic' import Database from '../sqlite/sync-database' @@ -121,6 +121,18 @@ export async function listOpenCodeDatabases(): Promise { } } +function compareOpenCodeClaimPriority(left: string, right: string): number { + // Why: the canonical opencode.db is the live database; it must claim + // duplicated sessions ahead of stale sibling copies. Remaining ties use + // path order so ownership is deterministic across rescans. + const leftRank = basename(left).toLowerCase() === 'opencode.db' ? 0 : 1 + const rightRank = basename(right).toLowerCase() === 'opencode.db' ? 0 : 1 + if (leftRank !== rightRank) { + return leftRank - rightRank + } + return left < right ? -1 : left > right ? 1 : 0 +} + export async function getProcessedDatabaseInfo( dbPath: string ): Promise { @@ -831,18 +843,32 @@ function mergeDailyAggregates( export async function parseOpenCodeUsageDatabase( dbPath: string, - worktrees: (OpenCodeUsageWorktreeRef & { canonicalPath: string })[] + worktrees: (OpenCodeUsageWorktreeRef & { canonicalPath: string })[], + options: { claimSession?: (sessionId: string) => boolean } = {} ): Promise { const processedDatabase = await getProcessedDatabaseInfo(dbPath) const db = new Database(dbPath, { readonly: true, fileMustExist: true }) try { db.pragma('query_only = ON') const events: OpenCodeUsageAttributedEvent[] = [] + const claimedBySessionId = new Map() + let hasDeferredClaims = false for (const row of selectUsageRows(db)) { const parsed = parseOpenCodeUsageRow(row) if (!parsed) { continue } + // Why: a stale sibling copy of opencode.db carries the same sessions, so + // each session must be counted from exactly one database (#8006). + let owned = claimedBySessionId.get(parsed.sessionId) + if (owned === undefined) { + owned = options.claimSession ? options.claimSession(parsed.sessionId) : true + claimedBySessionId.set(parsed.sessionId, owned) + } + if (!owned) { + hasDeferredClaims = true + continue + } const attributed = await attributeOpenCodeUsageEvent(parsed, worktrees) if (attributed) { events.push(attributed) @@ -850,7 +876,11 @@ export async function parseOpenCodeUsageDatabase( } return { ...processedDatabase, - ...aggregateOpenCodeUsage(events) + ...aggregateOpenCodeUsage(events), + ownedSessionIds: [...claimedBySessionId.entries()] + .filter(([, owned]) => owned) + .map(([sessionId]) => sessionId), + hasDeferredClaims } } finally { db.close() @@ -869,29 +899,107 @@ export async function scanOpenCodeUsageDatabases( const previousByPath = new Map( previousProcessedDatabases.map((database) => [database.path, database]) ) - const processedDatabases: OpenCodeUsagePersistedDatabase[] = [] const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees) - const sessionsById = new Map() - const dailyByKey = new Map() - for (const [index, dbPath] of dbPaths.entries()) { + const currentPaths = new Set(dbPaths) + // Why: when a database that owned sessions is deleted, remaining siblings + // still contain those sessions but their caches record them as unowned. + // Only databases that previously deferred claims can reclaim. + const lostOwnerPath = previousProcessedDatabases.some( + (database) => + !currentPaths.has(database.path) && + Array.isArray(database.ownedSessionIds) && + database.ownedSessionIds.length > 0 + ) + + const reusedByPath = new Map() + const pathsToParse: string[] = [] + for (const dbPath of dbPaths) { const databaseInfo = await getProcessedDatabaseInfo(dbPath) const previous = previousByPath.get(dbPath) + // When an owner disappears, only deferred-claim databases need reparse. + const mustReclaimDeferred = lostOwnerPath && previous?.hasDeferredClaims !== false const canReuse = - previous && previous.mtimeMs === databaseInfo.mtimeMs && previous.size === databaseInfo.size - const processed = canReuse - ? previous - : await parseOpenCodeUsageDatabase(dbPath, worktreesWithCanonicalPaths) + !mustReclaimDeferred && + previous && + previous.mtimeMs === databaseInfo.mtimeMs && + previous.size === databaseInfo.size && + Array.isArray(previous.ownedSessionIds) && + typeof previous.hasDeferredClaims === 'boolean' + if (canReuse) { + reusedByPath.set(dbPath, previous) + } else { + pathsToParse.push(dbPath) + } + } - processedDatabases.push(processed) - mergeSessions(sessionsById, processed.sessions) - mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + // Why: a sticky backup claim from a scan where opencode.db was missing would + // otherwise freeze a still-growing session at the backup snapshot when the + // live db reappears. Reparse lower-priority siblings whenever a higher- + // priority path is being re-evaluated so the live db can reclaim sessions + // without double-counting cached backup aggregates. + const demotedReusePaths: string[] = [] + for (const dbPath of reusedByPath.keys()) { + const higherPriorityParsing = pathsToParse.some( + (candidate) => compareOpenCodeClaimPriority(candidate, dbPath) < 0 + ) + if (higherPriorityParsing) { + demotedReusePaths.push(dbPath) + } + } + for (const dbPath of demotedReusePaths) { + reusedByPath.delete(dbPath) + pathsToParse.push(dbPath) + } + + // Why: `opencode-*.db` siblings are typically stale copies of `opencode.db` + // (backups), so mergeSessions would double every duplicated session (#8006). + // Each session is counted from exactly one database. The canonical live db + // claims first so a stale backup cannot freeze a still-growing session at + // its snapshot totals; cached databases keep the claims they persisted. + const sessionOwnerById = new Map() + for (const dbPath of [...reusedByPath.keys()].sort(compareOpenCodeClaimPriority)) { + const previous = reusedByPath.get(dbPath) + for (const sessionId of previous?.ownedSessionIds ?? []) { + if (!sessionOwnerById.has(sessionId)) { + sessionOwnerById.set(sessionId, dbPath) + } + } + } + + const parsedByPath = new Map() + const orderedPathsToParse = [...pathsToParse].sort(compareOpenCodeClaimPriority) + for (const [index, dbPath] of orderedPathsToParse.entries()) { + const processed = await parseOpenCodeUsageDatabase(dbPath, worktreesWithCanonicalPaths, { + claimSession: (sessionId) => { + const owner = sessionOwnerById.get(sessionId) + if (owner !== undefined && owner !== dbPath) { + return false + } + sessionOwnerById.set(sessionId, dbPath) + return true + } + }) + parsedByPath.set(dbPath, processed) if ((index + 1) % YIELD_EVERY_DATABASES === 0) { await yieldToEventLoop() } } + const processedDatabases: OpenCodeUsagePersistedDatabase[] = [] + const sessionsById = new Map() + const dailyByKey = new Map() + for (const dbPath of dbPaths) { + const processed = reusedByPath.get(dbPath) ?? parsedByPath.get(dbPath) + if (!processed) { + continue + } + processedDatabases.push(processed) + mergeSessions(sessionsById, processed.sessions) + mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + } + return { processedDatabases, sessions: finalizeSessions(sessionsById), diff --git a/src/main/opencode-usage/store.test.ts b/src/main/opencode-usage/store.test.ts index bca001390..aea35628f 100644 --- a/src/main/opencode-usage/store.test.ts +++ b/src/main/opencode-usage/store.test.ts @@ -19,7 +19,7 @@ import { OpenCodeUsageStore, normalizePersistedState } from './store' function getDefaultState(): OpenCodeUsagePersistedState { return { - schemaVersion: 1, + schemaVersion: 2, worktreeFingerprint: null, processedDatabases: [], sessions: [], @@ -283,7 +283,9 @@ describe('OpenCodeUsageStore', () => { mtimeMs: 1, size: 2, sessions: [makeSession()], - dailyAggregates: [makeDaily()] + dailyAggregates: [makeDaily()], + ownedSessionIds: ['session-1'], + hasDeferredClaims: false } ], sessions: [makeSession()], @@ -300,7 +302,9 @@ describe('OpenCodeUsageStore', () => { mtimeMs: 1, size: 2, sessions: [], - dailyAggregates: [] + dailyAggregates: [], + ownedSessionIds: [], + hasDeferredClaims: false } ] }).processedDatabases diff --git a/src/main/opencode-usage/store.ts b/src/main/opencode-usage/store.ts index abfe2ca74..b926f3265 100644 --- a/src/main/opencode-usage/store.ts +++ b/src/main/opencode-usage/store.ts @@ -18,7 +18,9 @@ import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-w import type { OpenCodeUsageDailyAggregate, OpenCodeUsagePersistedState } from './types' import { createWorktreeRefs, scanOpenCodeUsageDatabases } from './scanner' -const SCHEMA_VERSION = 1 +// Why: v2 adds per-database session ownership (stale sibling-copy dedupe). +// Older caches were built without it and can carry doubled sessions (#8006). +const SCHEMA_VERSION = 2 const STALE_MS = 5 * 60_000 let _openCodeUsageFile: string | null = null diff --git a/src/main/opencode-usage/types.ts b/src/main/opencode-usage/types.ts index ed7f3d214..cf8d2c6a8 100644 --- a/src/main/opencode-usage/types.ts +++ b/src/main/opencode-usage/types.ts @@ -86,6 +86,13 @@ export type OpenCodeUsageDailyAggregate = { export type OpenCodeUsagePersistedDatabase = OpenCodeUsageProcessedDatabase & { sessions: OpenCodeUsageSession[] dailyAggregates: OpenCodeUsageDailyAggregate[] + /** Session ids this database counted. Sibling copies (opencode-backup.db) + * duplicate sessions; ownership keeps each session counted by exactly one + * cached database across incremental scans. */ + ownedSessionIds: string[] + /** True when this database saw sessions already claimed by another database. + * When that owner disappears, only deferred databases need reparse. */ + hasDeferredClaims: boolean } export type OpenCodeUsagePersistedState = {