mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix(quickdesk): stop counting a session's estimate after its metrics arrive
Quick Desktop sources are merged durably, so a sessions.db estimate cached before the session's metrics landed was never removed and the session counted twice from then on. The sessions.db source is now marked as a snapshot of the store, replaced on each re-parse; a locked store defers the parse (cached rows kept, retried next refresh) instead of reading as empty. Parse version bumped so cached double counts re-parse.
This commit is contained in:
parent
9e5f729d8b
commit
99eafef13a
5 changed files with 56 additions and 7 deletions
|
|
@ -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]))
|
||||
|
|
|
|||
|
|
@ -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<SessionSource[]> {
|
|||
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()
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -611,7 +611,9 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// 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[<id>].parentAgentId === 'main'`
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue