mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix: four provider parsing and pricing attribution bugs (#1489)
Antigravity now stores the command basename instead of the full command line, so secrets in flags no longer reach the on-disk session cache, matching every other provider. A Copilot OpenTelemetry skill or tool is credited once per trace instead of once per chat span, so a multi-span trace no longer multiplies it in the skill and tool breakdowns; grand totals are unchanged, and the copilot parse version and the status snapshot version are bumped so warm caches re-derive. The daily-cache carried-remainder row now also carries a token shortfall, so per-model token sums reconcile to the day total where cost and calls already did. Bedrock provisioned-model and custom-model ARNs are recognised as unpriced Bedrock rather than hidden as local inference. Verified against the real cache: report, models and menubar totals identical to the cent.
This commit is contained in:
parent
80931d3ba3
commit
3925cade06
10 changed files with 231 additions and 10 deletions
|
|
@ -484,7 +484,12 @@ function creditCarriedRemainder(
|
|||
for (const key of REMAINDER_KEYS) {
|
||||
rest[key] = Math.max(0, num(totals[key]) - rows.reduce((sum, m) => sum + m[key], 0))
|
||||
}
|
||||
if (rest.calls <= 0 && rest.cost < CENT && rest.savingsUSD < CENT) return
|
||||
// Token remainders (whole tokens) are part of REMAINDER_KEYS too: a day whose
|
||||
// cost and calls reconcile but whose token totals fall short must still credit
|
||||
// the missing tokens to the carried row, or the model rows sum to fewer tokens
|
||||
// than the day headline.
|
||||
const tokenRemainder = rest.inputTokens + rest.outputTokens + rest.cacheReadTokens + rest.cacheWriteTokens
|
||||
if (rest.calls <= 0 && rest.cost < CENT && rest.savingsUSD < CENT && tokenRemainder < 1) return
|
||||
const acc = Object.hasOwn(models, CARRIED_MODEL_NAME) ? models[CARRIED_MODEL_NAME]! : emptyModelStats()
|
||||
for (const key of REMAINDER_KEYS) acc[key] += rest[key]
|
||||
setOwn(models, CARRIED_MODEL_NAME, acc)
|
||||
|
|
|
|||
|
|
@ -1090,6 +1090,11 @@ function looksLikeLocalModel(name: string): boolean {
|
|||
// one with no price must reach the unpriced list rather than be treated as
|
||||
// free local inference.
|
||||
if (/-v?\d+:\d+$/.test(name)) return false
|
||||
// Bedrock provisioned-model / custom-model ARNs carry colons from the ARN
|
||||
// structure (arn:aws:bedrock:<region>:<account>:provisioned-model/<id>), but
|
||||
// they are metered Bedrock, not local: an unpriced one must reach the
|
||||
// unpriced list rather than be hidden as free local inference.
|
||||
if (/^arn:aws:bedrock:/i.test(name)) return false
|
||||
// Ollama and LM Studio tags include `:tag` (e.g. qwen3.6:35b-a3b-bf16).
|
||||
if (name.includes(':') && !name.startsWith('http')) return true
|
||||
// GGUF / quantized fingerprints commonly seen in local inference.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { homedir } from 'os'
|
|||
import { fileURLToPath } from 'url'
|
||||
import https from 'https'
|
||||
|
||||
import { extractBashCommands } from '../bash-utils.js'
|
||||
import { getCodeburnCacheDir, readExistingTextFile } from '../cache-dir.js'
|
||||
import { calculateCost } from '../models.js'
|
||||
import { isSqliteAvailable, isSqliteBusyError, openDatabase } from '../sqlite.js'
|
||||
|
|
@ -843,7 +844,7 @@ function extractAntigravityToolFromStep(metadataBytes: Uint8Array, turn: TurnToo
|
|||
if (toolName === 'run_command') {
|
||||
turn.tools.push(toolName)
|
||||
const cmd = typeof args?.['CommandLine'] === 'string' ? args['CommandLine'].trim() : ''
|
||||
if (cmd) turn.bashCommands.push(cmd)
|
||||
if (cmd) turn.bashCommands.push(...extractBashCommands(cmd))
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1934,6 +1934,19 @@ function createOtelParser(
|
|||
}
|
||||
}
|
||||
|
||||
// Attribute trace-level tool/skill/bash metadata to a single chat
|
||||
// span. execute_tool spans happen ONCE in a trace, not once per chat
|
||||
// span, so re-reading them for every span billed a 5-span trace's one
|
||||
// skill call ~5x turns/cost (and split it across periods when the
|
||||
// trace crossed midnight). Order spans by start time and credit the
|
||||
// first one that actually yields, so the metadata lands on exactly one
|
||||
// call in the trace's opening period. Subagent names stay per-trace:
|
||||
// every chat span in a subagent's trace is genuinely that subagent's
|
||||
// call, so all of them are correctly labelled.
|
||||
chatSpanIds.sort((a, b) =>
|
||||
(spanMetaById.get(a)?.start_time_ms ?? 0) - (spanMetaById.get(b)?.start_time_ms ?? 0))
|
||||
const creditedTraces = new Set<string>()
|
||||
|
||||
// Yield one ParsedProviderCall per chat span
|
||||
for (const spanId of chatSpanIds) {
|
||||
const attrs = loadSpanAttributesFromTable(db, spanId)
|
||||
|
|
@ -1970,9 +1983,11 @@ function createOtelParser(
|
|||
seenKeys.add(jsonlDedupKey)
|
||||
}
|
||||
|
||||
const tools = toolsByTrace.get(spanMetadata.trace_id) ?? []
|
||||
const skills = skillsByTrace.get(spanMetadata.trace_id) ?? []
|
||||
const bashCommands = bashByTrace.get(spanMetadata.trace_id) ?? []
|
||||
const ownsTraceMetadata = !creditedTraces.has(spanMetadata.trace_id)
|
||||
if (ownsTraceMetadata) creditedTraces.add(spanMetadata.trace_id)
|
||||
const tools = ownsTraceMetadata ? (toolsByTrace.get(spanMetadata.trace_id) ?? []) : []
|
||||
const skills = ownsTraceMetadata ? (skillsByTrace.get(spanMetadata.trace_id) ?? []) : []
|
||||
const bashCommands = ownsTraceMetadata ? (bashByTrace.get(spanMetadata.trace_id) ?? []) : []
|
||||
const subagentTypes = subagentsByTrace.get(spanMetadata.trace_id)
|
||||
const timestamp = epochToISO(spanMetadata.start_time_ms)
|
||||
|
||||
|
|
|
|||
|
|
@ -390,7 +390,10 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
|
|||
// chatsession-otel-skills-v1: structured Skill calls are now extracted from
|
||||
// VS Code chatSessions and OTel execute_tool spans. Cached calls lack those
|
||||
// fields, so force one re-parse before serving period breakdowns.
|
||||
copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1',
|
||||
// otel-trace-metadata-once-v1: trace-level tool/skill/bash metadata is now
|
||||
// attributed to one chat span per trace instead of every span, so cached
|
||||
// calls carry the old per-span duplication - force one re-parse.
|
||||
copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1-session-store-v3-chatsession-otel-skills-v1-otel-trace-metadata-once-v1',
|
||||
// authoritative-usage-v4: persist one Grok session call from top-level
|
||||
// authoritative totals, use modelUsage only for priced attribution, clamp
|
||||
// reasoning per record, and label mixed sessions estimated.
|
||||
|
|
|
|||
|
|
@ -34,7 +34,10 @@ import { DAILY_CACHE_VERSION } from './daily-cache.js'
|
|||
// v10: current.skills is rebuilt from the newly reparsed Copilot
|
||||
// chatSessions/OTel calls; older snapshots can contain stale or empty skill
|
||||
// breakdowns for otherwise identical period queries.
|
||||
export const STATUS_SNAPSHOT_RENDER_VERSION = 10
|
||||
// v11: Copilot OTel trace-level tool/skill/bash metadata is now attributed
|
||||
// once per trace, so older snapshots can carry per-span-duplicated skill/tool
|
||||
// turns and cost for otherwise identical period queries.
|
||||
export const STATUS_SNAPSHOT_RENDER_VERSION = 11
|
||||
|
||||
/// The semantic key recorded on every status snapshot. A snapshot whose stored
|
||||
/// key differs (an older render revision, or a different daily-cache version)
|
||||
|
|
|
|||
|
|
@ -153,6 +153,58 @@ describe('loadDailyCache', () => {
|
|||
expect(JSON.parse(await readFile(legacy, 'utf-8'))).toEqual(saved)
|
||||
})
|
||||
|
||||
it('credits a token remainder to the carried row even when cost and calls reconcile', async () => {
|
||||
const saved = {
|
||||
version: 5,
|
||||
lastComputedDate: '2026-05-02',
|
||||
days: [
|
||||
{
|
||||
// cost + calls reconcile with the model rows, but the model tokens
|
||||
// fall 200 input / 100 output short of the day totals.
|
||||
date: '2026-05-02',
|
||||
cost: 10, calls: 5, sessions: 1,
|
||||
inputTokens: 1000, outputTokens: 500, cacheReadTokens: 0, cacheWriteTokens: 0,
|
||||
editTurns: 0, oneShotTurns: 0,
|
||||
models: { 'Opus 4.7': { calls: 5, cost: 10, savingsUSD: 0, inputTokens: 800, outputTokens: 400, cacheReadTokens: 0, cacheWriteTokens: 0 } },
|
||||
categories: {}, providers: {},
|
||||
},
|
||||
{
|
||||
// Fully reconciled — must not grow a carried row.
|
||||
date: '2026-05-03',
|
||||
cost: 4, calls: 2, sessions: 1,
|
||||
inputTokens: 600, outputTokens: 300, cacheReadTokens: 0, cacheWriteTokens: 0,
|
||||
editTurns: 0, oneShotTurns: 0,
|
||||
models: { 'Opus 4.7': { calls: 2, cost: 4, savingsUSD: 0, inputTokens: 600, outputTokens: 300, cacheReadTokens: 0, cacheWriteTokens: 0 } },
|
||||
categories: {}, providers: {},
|
||||
},
|
||||
],
|
||||
}
|
||||
const { writeFile, mkdir } = await import('fs/promises')
|
||||
await mkdir(TMP_CACHE_ROOT, { recursive: true })
|
||||
await writeFile(join(TMP_CACHE_ROOT, 'daily-cache.json'), JSON.stringify(saved), 'utf-8')
|
||||
|
||||
const cache = await loadDailyCache()
|
||||
const short = cache.days.find(d => d.date === '2026-05-02')!
|
||||
const reconciled = cache.days.find(d => d.date === '2026-05-03')!
|
||||
|
||||
// The carried row picks up exactly the missing tokens, with no calls/cost.
|
||||
const carried = short.models['Unknown (carried)']!
|
||||
expect(carried).toBeDefined()
|
||||
expect(carried.inputTokens).toBe(200)
|
||||
expect(carried.outputTokens).toBe(100)
|
||||
expect(carried.calls).toBe(0)
|
||||
expect(carried.cost).toBe(0)
|
||||
// Cost and calls are untouched; token sums now reconcile.
|
||||
expect(short.cost).toBe(10)
|
||||
expect(short.calls).toBe(5)
|
||||
const sum = (k: 'inputTokens' | 'outputTokens') => Object.values(short.models).reduce((a, m) => a + m[k], 0)
|
||||
expect(sum('inputTokens')).toBe(short.inputTokens)
|
||||
expect(sum('outputTokens')).toBe(short.outputTokens)
|
||||
|
||||
// A fully reconciled day gets no carried row (idempotent).
|
||||
expect(reconciled.models['Unknown (carried)']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('adopts a legacy file whose version matches the current one, once, without deleting it', async () => {
|
||||
const saved = {
|
||||
version: DAILY_CACHE_VERSION,
|
||||
|
|
|
|||
|
|
@ -1160,6 +1160,26 @@ describe('findUnpricedModels', () => {
|
|||
expect(isExpectedFreeModel('llama3.1:8b-instruct-q4_K_M')).toBe(true)
|
||||
})
|
||||
|
||||
it('flags Bedrock provisioned-model / custom-model ARNs as unpriced, not local', () => {
|
||||
// These ARNs carry colons from the ARN structure, so they used to fall to
|
||||
// the `:tag` branch and be hidden as free local inference. They are metered
|
||||
// Bedrock and, when unpriced, must reach the unpriced list.
|
||||
const provisioned = 'arn:aws:bedrock:us-east-1:123456789012:provisioned-model/2c3f9a1b'
|
||||
const custom = 'arn:aws:bedrock:eu-central-1:210987654321:custom-model/my-tuned-claude'
|
||||
expect(isExpectedFreeModel(provisioned)).toBe(false)
|
||||
expect(isExpectedFreeModel(custom)).toBe(false)
|
||||
expect(findUnpricedModels([
|
||||
{ model: provisioned, calls: 4, cost: 0, tokens: 2000 },
|
||||
{ model: custom, calls: 1, cost: 0, tokens: 300 },
|
||||
])).toEqual([
|
||||
{ model: provisioned, calls: 4, tokens: 2000 },
|
||||
{ model: custom, calls: 1, tokens: 300 },
|
||||
])
|
||||
// Real local tags are untouched by the ARN exemption.
|
||||
expect(isExpectedFreeModel('llama3.1:8b-instruct-q4_K_M')).toBe(true)
|
||||
expect(isExpectedFreeModel('qwen3.6:35b-a3b-bf16')).toBe(true)
|
||||
})
|
||||
|
||||
it('flags zero-rate pricing stubs but not explicit zero-rate user overrides', async () => {
|
||||
// LiteLLM ships [0,0] stubs for models it lists but has no price for;
|
||||
// a stub hit means "unknown price", not "free".
|
||||
|
|
|
|||
|
|
@ -806,7 +806,7 @@ describe('antigravity provider helpers', () => {
|
|||
'find_by_name',
|
||||
'write_to_file',
|
||||
])
|
||||
expect(firstCall.bashCommands).toEqual(['git status'])
|
||||
expect(firstCall.bashCommands).toEqual(['git'])
|
||||
expect(firstCall.skills).toEqual(['graphify'])
|
||||
expect(firstCall.subagentTypes).toEqual(['Codebase Researcher'])
|
||||
})
|
||||
|
|
@ -974,7 +974,7 @@ describe('antigravity provider helpers', () => {
|
|||
|
||||
// Turn 0 has tools and bash command
|
||||
expect(calls[0]!.tools).toEqual(['run_command', 'view_file'])
|
||||
expect(calls[0]!.bashCommands).toEqual(['npm test'])
|
||||
expect(calls[0]!.bashCommands).toEqual(['npm'])
|
||||
|
||||
// Turn 1 has no tools (send_message skipped) and no bash commands (did not leak from Turn 0)
|
||||
expect(calls[1]!.tools).toEqual([])
|
||||
|
|
@ -1044,8 +1044,68 @@ describe('antigravity provider helpers', () => {
|
|||
const calls = await collectAntigravityCalls({ path: dbPath, project: 'antigravity', provider: 'antigravity' })
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]!.tools).toEqual(['run_command', 'view_file'])
|
||||
expect(calls[0]!.bashCommands).toEqual(['git status'])
|
||||
expect(calls[0]!.bashCommands).toEqual(['git'])
|
||||
})
|
||||
})
|
||||
|
||||
it('stores only the basename for run_command, never the secret-bearing flags', async () => {
|
||||
if (!isSqliteAvailable()) return
|
||||
|
||||
await withTempAntigravityHome('codeburn-antigravity-secret-', async (tempHome) => {
|
||||
const fixture = JSON.parse(await readFile(
|
||||
new URL('../fixtures/antigravity-cli-current/gen-metadata.json', import.meta.url),
|
||||
'utf-8',
|
||||
)) as CurrentCliFixture
|
||||
|
||||
const conversationsDir = join(tempHome, '.gemini', 'antigravity', 'conversations')
|
||||
await mkdir(conversationsDir, { recursive: true })
|
||||
const dbPath = join(conversationsDir, `${fixture.conversationId}.db`)
|
||||
createCurrentAntigravityCliDb(dbPath, fixture)
|
||||
|
||||
const varint = (n: number): number[] => {
|
||||
const out: number[] = []
|
||||
let v = n
|
||||
while (v > 0x7f) { out.push((v & 0x7f) | 0x80); v = Math.floor(v / 128) }
|
||||
out.push(v)
|
||||
return out
|
||||
}
|
||||
const tag = (field: number, wire: number): number[] => varint(field * 8 + wire)
|
||||
const lenField = (field: number, bytes: number[]): number[] => [...tag(field, 2), ...varint(bytes.length), ...bytes]
|
||||
const strField = (field: number, str: string): number[] => lenField(field, Array.from(Buffer.from(str, 'utf-8')))
|
||||
const encodeToolStepMetadata = (toolName: string, argsJson: string): Buffer => Buffer.from(lenField(4, [
|
||||
...strField(1, 'call_secret'),
|
||||
...strField(2, toolName),
|
||||
...strField(3, argsJson),
|
||||
]))
|
||||
const withStepIndices = (fixtureHex: string, indices: number[]): Buffer => {
|
||||
const rest = Buffer.from(fixtureHex, 'hex').subarray(4)
|
||||
const packed = Buffer.from(indices.flatMap(n => varint(n)))
|
||||
return Buffer.concat([Buffer.from([...tag(2, 2), ...varint(packed.length), ...packed]), rest])
|
||||
}
|
||||
|
||||
const { DatabaseSync: Database } = requireForTest('node:sqlite')
|
||||
const db = new Database(dbPath) as TestDb
|
||||
try {
|
||||
db.prepare('UPDATE gen_metadata SET data = ? WHERE idx = 0').run(
|
||||
withStepIndices(fixture.rows[0]!.hex, [1]),
|
||||
)
|
||||
db.exec('CREATE TABLE steps (idx integer PRIMARY KEY, step_type integer, metadata blob)')
|
||||
const stmt = db.prepare('INSERT INTO steps (idx, step_type, metadata) VALUES (?, ?, ?)')
|
||||
stmt.run(0, 15, null)
|
||||
stmt.run(1, 21, encodeToolStepMetadata('run_command', JSON.stringify({ CommandLine: 'curl --api-key=secret123 https://example.com' })))
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
|
||||
const calls = await collectAntigravityCalls({ path: dbPath, project: 'antigravity', provider: 'antigravity' })
|
||||
expect(calls.length).toBeGreaterThan(0)
|
||||
// Tool breakdown still records the run_command call.
|
||||
expect(calls[0]!.tools).toEqual(['run_command'])
|
||||
// Command breakdown carries the basename only — no secret reaches disk.
|
||||
expect(calls[0]!.bashCommands).toEqual(['curl'])
|
||||
expect(JSON.stringify(calls[0]!)).not.toContain('secret123')
|
||||
expect(JSON.stringify(calls[0]!)).not.toContain('--api-key')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1733,6 +1733,63 @@ describe('copilot provider - OTel cache token parsing', () => {
|
|||
expect(calls[0]!.skills).toEqual(['ponytail'])
|
||||
})
|
||||
|
||||
it('attributes a trace-level skill to one chat span, not every span in the trace', async () => {
|
||||
if (!isSqliteAvailable()) return
|
||||
|
||||
createOtelDb(dbPath)
|
||||
// Five chat spans in ONE trace, each with its own tokens.
|
||||
const perSpanTokens = [
|
||||
{ input: 100, output: 20 },
|
||||
{ input: 200, output: 40 },
|
||||
{ input: 300, output: 60 },
|
||||
{ input: 400, output: 80 },
|
||||
{ input: 500, output: 100 },
|
||||
]
|
||||
perSpanTokens.forEach((t, i) => {
|
||||
insertSpan(dbPath, {
|
||||
spanId: `span-multi-${i}`, traceId: 'trace-multi', operationName: 'chat', startTimeMs: 1000 + i,
|
||||
attrs: {
|
||||
'gen_ai.conversation.id': 'conv-multi',
|
||||
'gen_ai.response.model': 'gpt-4.1',
|
||||
'gen_ai.usage.input_tokens': t.input,
|
||||
'gen_ai.usage.output_tokens': t.output,
|
||||
},
|
||||
})
|
||||
})
|
||||
// One skill call for the whole trace.
|
||||
insertSpan(dbPath, {
|
||||
spanId: 'span-multi-tool', traceId: 'trace-multi', operationName: 'execute_tool', startTimeMs: 1500,
|
||||
attrs: {
|
||||
'gen_ai.tool.name': 'skill',
|
||||
'gen_ai.tool.call.arguments': JSON.stringify({ skill: 'graphify' }),
|
||||
},
|
||||
})
|
||||
|
||||
const provider = createCopilotProvider('/nonexistent/jsonl', '/nonexistent/ws')
|
||||
const sources = await provider.discoverSessions()
|
||||
const src = sources.find(s => s.path.startsWith(dbPath))
|
||||
expect(src).toBeDefined()
|
||||
|
||||
const calls = await collectCalls(src!)
|
||||
|
||||
expect(calls).toHaveLength(5)
|
||||
// The skill and Skill tool land on exactly one span, not all five.
|
||||
const withSkill = calls.filter(c => (c.skills ?? []).includes('graphify'))
|
||||
expect(withSkill).toHaveLength(1)
|
||||
expect(calls.filter(c => c.tools.includes('Skill'))).toHaveLength(1)
|
||||
// Every other span carries no trace metadata.
|
||||
expect(calls.filter(c => (c.skills ?? []).length > 0)).toHaveLength(1)
|
||||
expect(calls.filter(c => c.tools.length > 0)).toHaveLength(1)
|
||||
// Per-span token costs are untouched by the attribution fix.
|
||||
const byInput = new Map(calls.map(c => [c.inputTokens, c]))
|
||||
for (const t of perSpanTokens) {
|
||||
const c = byInput.get(t.input)
|
||||
expect(c).toBeDefined()
|
||||
expect(c!.outputTokens).toBe(t.output)
|
||||
expect(c!.costUSD).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('skips OTel spans with zero input and output tokens', async () => {
|
||||
if (!isSqliteAvailable()) return
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue