fix: dedupe fork-copied usage history across Claude, Codex, and OpenCode scanners (#8023)

* fix: dedupe fork-copied usage history across Claude, Codex, and OpenCode scanners

Coding-agent CLIs copy transcript/rollout history into new files on
resume/fork, and the usage scanners deduped per-file only (or not at
all), so copied history was re-counted once per descendant file
(issue #8006: 38.6B tokens / $72,981 reported vs ~2.3B real).

- claude-usage: cross-file turn ownership keyed on message.id:requestId;
  per-file ownedDedupeKeys persisted; deterministic sorted-path claim
  order; schema v3 -> v4 so inflated caches rebuild.
- codex-usage: cross-file token_count event ownership keyed on the raw
  record identity (sessionId + timestamp + token tuples); fixes both the
  copied-prefix re-count and the total-only branch that re-counted the
  entire cumulative session per descendant rollout; legacy
  .orca-session-copies skip-bytes bridge unchanged; schema v3 -> v4.
- opencode-usage: each sessionId is counted from exactly one database;
  the canonical opencode.db claims ahead of stale sibling copies
  (opencode-backup.db etc.) so backups no longer double totals, while
  backup-only sessions are still counted; schema v1 -> v2.

Regression tests cover fork-copied files counted once (including the
Codex total-only variant), duplicated OpenCode databases, and dedupe
stability across cached incremental rescans.

Co-authored-by: Orca <help@stably.ai>

* Fix cross-tool usage double-counting for fork/resume-copied history

- Widen Claude dedupe keys with message-id and uuid fallbacks so forks
  missing requestId still dedupe correctly, and drop Codex's sessionId
  from event keys since fork/resume rewrites session_meta.id while
  copying identical token_count records.
- Track hasDeferredClaims per cached file/database across Claude, Codex,
  and OpenCode scanners so that when an owning file is deleted, only
  files that deferred a claim need reparsing to reclaim those turns
  instead of rescanning the entire corpus.
- Let OpenCode's live opencode.db reclaim sessions from a stale backup
  claim once it reappears, avoiding a frozen stale snapshot.
- Bump schema versions to invalidate caches built with the old,
  narrower ownership keys (#8006, #8013 follow-up).

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinjing
2026-07-09 22:36:53 -07:00
committed by GitHub
co-authored by Orca
parent f495b39a6a
commit 4908a03671
15 changed files with 1148 additions and 74 deletions
+210 -3
View File
@@ -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)
})
})
+122 -14
View File
@@ -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<string[]> {
}
}
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<OpenCodeUsageProcessedDatabase> {
@@ -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<OpenCodeUsagePersistedDatabase> {
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<string, boolean>()
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<string, OpenCodeUsageSession>()
const dailyByKey = new Map<string, OpenCodeUsageDailyAggregate>()
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<string, OpenCodeUsagePersistedDatabase>()
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<string, string>()
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<string, OpenCodeUsagePersistedDatabase>()
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<string, OpenCodeUsageSession>()
const dailyByKey = new Map<string, OpenCodeUsageDailyAggregate>()
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),
+7 -3
View File
@@ -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
+3 -1
View File
@@ -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
+7
View File
@@ -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 = {