mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix(warp): put a conversation's new spend on its new exchanges
Warp records cost and tokens per conversation, and each parse re-split the running total over every finished exchange, so a later exchange's spend moved onto earlier days. Exchanges already in the cache now keep their share and only the growth since the last parse is split over the new ones. No new state: the previous split is read from the cache entry being replaced.
This commit is contained in:
parent
68a2684b4f
commit
4f82716639
3 changed files with 78 additions and 0 deletions
|
|
@ -14,6 +14,7 @@ import { estimateTokensFromChars } from './token-estimate.js'
|
|||
import { discoverAllSessions, discoverAllSessionsWithFailures, getProvider } from './providers/index.js'
|
||||
import { evictCachedCodexResults, flushCodexCache, readCachedCodexResults, withCodexCacheDirectory, writeCachedCodexResults } from './codex-cache.js'
|
||||
import { antigravityCascadeIdFromPath, flushAntigravityCache, preloadAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js'
|
||||
import { keepCachedWarpShares } from './providers/warp.js'
|
||||
import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js'
|
||||
import { kimicodeLineageForSource } from './providers/kimicode.js'
|
||||
import { isSqliteBusyError } from './sqlite.js'
|
||||
|
|
@ -4024,6 +4025,7 @@ export async function parseProviderSources(
|
|||
for await (const call of parser.parse()) {
|
||||
providerCalls.push(call)
|
||||
}
|
||||
if (providerName === 'warp' && priorEntry) providerCalls = keepCachedWarpShares(priorEntry, providerCalls)
|
||||
}
|
||||
const canonicalCalls = await Promise.all(providerCalls.map(canonicalizeProviderCallProject))
|
||||
const turns = providerCallsToCachedTurns(canonicalCalls)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { calculateCost, getShortModelName, ownValue } from '../models.js'
|
|||
import { blobToText, getSqliteLoadError, isBlockedDatabaseError, isSqliteAvailable, isSqliteBusyError, openDatabase, type SqliteDatabase } from '../sqlite.js'
|
||||
import { estimateTokensFromChars } from '../token-estimate.js'
|
||||
import type { ProbeRoot, ParsedProviderCall, Provider, SessionParser, SessionSource } from './types.js'
|
||||
import type { CachedFile } from '../session-cache.js'
|
||||
import { isPermissionError, safeNumber } from '../parser.js'
|
||||
|
||||
const WARP_GROUP_CONTAINER = '2BBY89MBSN.dev.warp'
|
||||
|
|
@ -268,6 +269,42 @@ function allocateCost(weights: number[], totalUsd: number): number[] {
|
|||
return normalized.map(w => (totalUsd * w) / totalWeight)
|
||||
}
|
||||
|
||||
// Warp records usage per conversation, not per exchange, so every parse
|
||||
// re-splits the running total over all finished exchanges, and a later
|
||||
// exchange's spend would move onto earlier days. Exchanges the previous parse
|
||||
// cached keep their share; only the growth since then is split, over the new
|
||||
// exchanges (or added to the latest one when there is none). A total that
|
||||
// shrank, or a cost that changed rung, falls back to the fresh split.
|
||||
export function keepCachedWarpShares(prior: CachedFile, calls: ParsedProviderCall[]): ParsedProviderCall[] {
|
||||
const cached = new Map(prior.turns.flatMap(t => t.calls).map(c => [c.deduplicationKey, c]))
|
||||
const kept = calls.filter(c => cached.has(c.deduplicationKey))
|
||||
if (kept.length === 0) return calls
|
||||
const billed = calls[0]!.costFromBilling === true
|
||||
if (billed && kept.some(c => cached.get(c.deduplicationKey)!.costUSD === undefined)) return calls
|
||||
|
||||
const sum = (values: number[]) => values.reduce((a, b) => a + b, 0)
|
||||
const keptTokens = sum(kept.map(c => cached.get(c.deduplicationKey)!.usage.inputTokens))
|
||||
const keptCost = billed ? sum(kept.map(c => cached.get(c.deduplicationKey)!.costUSD!)) : 0
|
||||
const deltaTokens = sum(calls.map(c => c.inputTokens)) - keptTokens
|
||||
const deltaCost = billed ? sum(calls.map(c => c.costUSD)) - keptCost : 0
|
||||
if (deltaTokens < 0 || deltaCost < -1e-9) return calls
|
||||
|
||||
const fresh = calls.filter(c => !cached.has(c.deduplicationKey))
|
||||
const targets = fresh.length > 0 ? fresh : [calls[calls.length - 1]!]
|
||||
const tokenShares = allocateTokens(targets.map(c => c.inputTokens), deltaTokens)
|
||||
const costShares = allocateCost(targets.map(c => c.costUSD), Math.max(0, deltaCost))
|
||||
|
||||
return calls.map(call => {
|
||||
const prev = cached.get(call.deduplicationKey)
|
||||
const t = targets.indexOf(call)
|
||||
const inputTokens = (prev?.usage.inputTokens ?? 0) + (t >= 0 ? tokenShares[t]! : 0)
|
||||
const costUSD = billed
|
||||
? (prev?.costUSD ?? 0) + (t >= 0 ? costShares[t]! : 0)
|
||||
: calculateCost(call.model, inputTokens, 0, 0, 0, 0)
|
||||
return { ...call, inputTokens, costUSD }
|
||||
})
|
||||
}
|
||||
|
||||
function extractUserMessage(rawInput: string): string {
|
||||
try {
|
||||
const parsed = JSON.parse(rawInput) as unknown
|
||||
|
|
|
|||
|
|
@ -132,3 +132,42 @@ itUnlessNoSqlite('persists only the billing-derived cost, leaving the token floo
|
|||
expect(costByKey.has('warp:conv-floor:ex-conv-floor')).toBe(true)
|
||||
expect(costByKey.get('warp:conv-floor:ex-conv-floor')).toBeUndefined()
|
||||
})
|
||||
|
||||
itUnlessNoSqlite('puts a conversation\'s later spend on the new exchange, not back on earlier days', async () => {
|
||||
const { DatabaseSync } = requireForTest('node:sqlite')
|
||||
const db = new DatabaseSync(DB_PATH)
|
||||
db.exec(`CREATE TABLE agent_conversations (id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL, conversation_data TEXT NOT NULL, last_modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)`)
|
||||
db.exec(`CREATE TABLE ai_queries (id INTEGER PRIMARY KEY AUTOINCREMENT, exchange_id TEXT NOT NULL, conversation_id TEXT NOT NULL, start_ts DATETIME NOT NULL, input TEXT NOT NULL, working_directory TEXT, output_status TEXT NOT NULL, model_id TEXT NOT NULL DEFAULT '', planning_model_id TEXT NOT NULL DEFAULT '', coding_model_id TEXT NOT NULL DEFAULT '')`)
|
||||
db.exec(`CREATE TABLE blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, pane_leaf_uuid BLOB NOT NULL, stylized_command BLOB NOT NULL, stylized_output BLOB NOT NULL, exit_code INTEGER NOT NULL, did_execute BOOLEAN NOT NULL, completed_ts DATETIME, start_ts DATETIME, block_id TEXT NOT NULL DEFAULT '', ai_metadata TEXT)`)
|
||||
const conversation = (credits: number) => JSON.stringify({ conversation_usage_metadata: { credits_spent: credits, token_usage: tokenUsage() } })
|
||||
const exchange = (id: string, startTs: string, text: string) => db.prepare(`INSERT INTO ai_queries (exchange_id, conversation_id, start_ts, input, working_directory, output_status, model_id) VALUES (?,?,?,?,?,?,?)`)
|
||||
.run(id, 'conv', startTs, JSON.stringify([{ Query: { text } }]), '/tmp/warpproj', '"Completed"', 'auto-efficient')
|
||||
db.prepare('INSERT INTO agent_conversations (conversation_id, conversation_data, last_modified_at) VALUES (?,?,?)').run('conv', conversation(750), '2026-08-16 10:00:00')
|
||||
exchange('a', '2026-08-16 10:00:00.000000', 'x'.repeat(400))
|
||||
exchange('b', '2026-08-16 11:00:00.000000', 'x'.repeat(400))
|
||||
|
||||
const { clearSessionCache, parseAllSessions } = await import('../src/parser.js')
|
||||
const { loadCache } = await import('../src/session-cache.js')
|
||||
const cachedCosts = async () => {
|
||||
const out = new Map<string, number | undefined>()
|
||||
for (const file of Object.values((await loadCache()).providers['warp']?.files ?? {})) {
|
||||
for (const turn of file.turns) for (const call of turn.calls) out.set(call.deduplicationKey, call.costUSD)
|
||||
}
|
||||
return out
|
||||
}
|
||||
clearSessionCache()
|
||||
await parseAllSessions(undefined, 'warp')
|
||||
const day1 = await cachedCosts()
|
||||
|
||||
// Next day: a short prompt that costs 375 more credits.
|
||||
db.prepare('UPDATE agent_conversations SET conversation_data = ? WHERE conversation_id = ?').run(conversation(1125), 'conv')
|
||||
exchange('c', '2026-08-17 10:00:00.000000', 'x'.repeat(40))
|
||||
db.close()
|
||||
clearSessionCache()
|
||||
await parseAllSessions(undefined, 'warp')
|
||||
const day2 = await cachedCosts()
|
||||
|
||||
expect(day2.get('warp:conv:a')).toBeCloseTo(day1.get('warp:conv:a')!, 10)
|
||||
expect(day2.get('warp:conv:b')).toBeCloseTo(day1.get('warp:conv:b')!, 10)
|
||||
expect(day2.get('warp:conv:c')).toBeCloseTo(375 * CREDIT_USD_RATE, 10)
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue