diff --git a/src/parser.ts b/src/parser.ts index 19462e5e..e1c42891 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -3982,7 +3982,7 @@ export async function parseProviderSources( // Durable providers (e.g. copilot OTel) never clear existing entries so // that pruned-away data is preserved for monotonic monthly totals. const priorEntry = section.files[source.path] - if (!provider.durableSources && !clearedPaths.has(source.path)) { + if ((!provider.durableSources || source.snapshot) && !clearedPaths.has(source.path)) { delete section.files[source.path] markCacheDirty(diskCache, providerName, source.path) clearedPaths.add(source.path) @@ -4056,7 +4056,7 @@ export async function parseProviderSources( // migrated cache with an anchor the virgin cache had - dropping the // post-compaction residual (#946 validation round 6, see (c6)). // Non-durable providers keep the original overwrite-or-append behaviour. - if (provider.durableSources) { + if (provider.durableSources && !source.snapshot) { const existingEntry = section.files[source.path] if (existingEntry) { const freshByKey = new Map(turns.flatMap(t => t.calls).map(c => [c.deduplicationKey, c])) diff --git a/src/providers/quickdesk.ts b/src/providers/quickdesk.ts index 76fa7b5f..96866f50 100644 --- a/src/providers/quickdesk.ts +++ b/src/providers/quickdesk.ts @@ -4,7 +4,7 @@ import { basename, isAbsolute, join, resolve } from 'node:path' import { calculateCost, ownValue } from '../models.js' import { estimateTokensFromChars } from '../token-estimate.js' -import { blobToText, isSqliteAvailable, openDatabase } from '../sqlite.js' +import { blobToText, isSqliteAvailable, isSqliteBusyError, openDatabase } from '../sqlite.js' import type { SqliteDatabase } from '../sqlite.js' import type { ParsedProviderCall, ProbeRoot, Provider, SessionParser, SessionSource } from './types.js' @@ -176,6 +176,7 @@ async function discoverSources(): Promise { provider: 'quickdesk', sourceId: 'sessions-db', sourcePath: base.path, + snapshot: true, }) } } @@ -238,7 +239,9 @@ function loadDatabaseSnapshot(basePath: string): DatabaseSnapshot { let db: SqliteDatabase try { db = openDatabase(join(basePath, 'sessions', 'sessions.db')) - } catch { + } catch (err) { + // A locked store must defer the parse, not read as a store with no sessions. + if (isSqliteBusyError(err)) throw err return empty } @@ -307,13 +310,15 @@ function loadDatabaseSnapshot(basePath: string): DatabaseSnapshot { } session.tools.push(...toolNames(row.tool_names)) } - } catch { + } catch (err) { + if (isSqliteBusyError(err)) throw err return { sessions, canEstimate: false } } for (const session of sessions.values()) session.tools = uniqueMappedTools(session.tools) return { sessions, canEstimate: true } - } catch { + } catch (err) { + if (isSqliteBusyError(err)) throw err return empty } finally { db.close() diff --git a/src/providers/types.ts b/src/providers/types.ts index 18b90932..2da9418d 100644 --- a/src/providers/types.ts +++ b/src/providers/types.ts @@ -23,6 +23,10 @@ export type SessionSource = { // #992 that exemption is redundant (only ORPHANS age out) — kept as the // explicit statement of intent, not as the thing enforcing it. retainWhilePresent?: boolean + // This source is a projection of a store's current state, not a record, so + // a re-parse replaces its cached calls even under a durableSources provider + // (Quick Desktop's sessions.db estimates, superseded once metrics land). + snapshot?: boolean } export type SessionParser = { diff --git a/src/session-cache.ts b/src/session-cache.ts index 0efb6abe..9fc3caaa 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -611,7 +611,9 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // rollup uses the bare model id, and `google-vertex`/`google-vertex-anthropic` // ride as the `vertex` route. Cached calls hold none of these. opencode: 'session-model-v1-archived-subtree-v1-billing-routes-v2-v2-legacy-union-v1-unknown-usage-v1-vertex-fallback-cost-v1', - quickdesk: 'emf-sqlite-v2-est-cost', + // snapshot-db-v1: sessions.db estimates are replaced on re-parse, so an + // estimate superseded by metrics no longer stays cached beside them. + quickdesk: 'emf-sqlite-v2-est-cost-snapshot-db-v1', // session-lineage-capture-v1: SessionLineage (CB-1, slice 1) is now carried // on the cached file for every kimicode wire. Child evidence is the // provider-recorded `state.json` `agents[].parentAgentId === 'main'` diff --git a/tests/providers/quickdesk.test.ts b/tests/providers/quickdesk.test.ts index f750c752..ddc6e921 100644 --- a/tests/providers/quickdesk.test.ts +++ b/tests/providers/quickdesk.test.ts @@ -443,3 +443,41 @@ skipUnlessSqlite('quickdesk provider', () => { expect(quickdesk.toolDisplayName('future_tool')).toBe('future_tool') }) }) + +describe.skipIf(!isSqliteAvailable())('quickdesk estimate superseded by metrics', () => { + it('drops a cached sessions.db estimate once the session has metered calls', async () => { + const originalCacheDir = process.env['CODEBURN_CACHE_DIR'] + process.env['CODEBURN_CACHE_DIR'] = join(quickworkHome, 'cb-cache') + try { + const dbPath = await createSessionsDb(quickworkHome) + withDb(dbPath, db => { + db.prepare('INSERT INTO sessions (id, title, created_at, updated_at, message_count, agent_mode, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?)') + .run('S', 'T', 1783900800, 1783900900, 2, 'agent', null) + const insertMessage = db.prepare('INSERT INTO session_messages (session_id, role, content, timestamp, tool_names) VALUES (?, ?, ?, ?, ?)') + insertMessage.run('S', 'user', 'x'.repeat(4000), 1783900801, null) + insertMessage.run('S', 'assistant', 'y'.repeat(4000), 1783900802, null) + }) + + const { clearSessionCache, parseAllSessions } = await import('../../src/parser.js') + const servedKeys = async () => (await parseAllSessions(undefined, 'quickdesk')) + .flatMap(p => p.sessions).flatMap(s => s.turns).flatMap(t => t.assistantCalls).map(c => c.deduplicationKey) + clearSessionCache() + expect(await servedKeys()).toEqual(['quickdesk-est:S']) + + await writeMetrics(quickworkHome, '2026-07-13', [ + { session_id: 'S', Model: 'claude-sonnet-4-5', InputTokens: 1000, OutputTokens: 1000, CostUSD: 0.018, _aws: { Timestamp: 1783900802000 } }, + ]) + withDb(dbPath, db => { + db.prepare('INSERT INTO session_messages (session_id, role, content, timestamp, tool_names) VALUES (?, ?, ?, ?, ?)') + .run('S', 'user', 'thanks', 1783900803, null) + }) + clearSessionCache() + const keys = await servedKeys() + expect(keys).toHaveLength(1) + expect(keys[0]).toMatch(/^quickdesk:S:/) + } finally { + if (originalCacheDir === undefined) delete process.env['CODEBURN_CACHE_DIR'] + else process.env['CODEBURN_CACHE_DIR'] = originalCacheDir + } + }) +})