mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
Merge pull request #1324 from getagentseal/feat/compare-cohorts
Cohort model comparison (Compare > Cohorts) over an explicit observation population
This commit is contained in:
commit
e0247585df
16 changed files with 2435 additions and 9 deletions
|
|
@ -47,6 +47,8 @@ const CHANNELS = [
|
|||
'codeburn:getCompare',
|
||||
'codeburn:getPeriodCompare',
|
||||
'codeburn:getPeriodCompareSessions',
|
||||
'codeburn:getCompareCohortModels',
|
||||
'codeburn:getCompareCohort',
|
||||
'codeburn:getYield',
|
||||
'codeburn:getSpendFlow',
|
||||
'codeburn:getBranchSpend',
|
||||
|
|
@ -114,6 +116,9 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> =
|
|||
// Claude sanitizes project paths to dash-leading slugs; the key rides in the
|
||||
// VALUE position of --key, so a dash-leading key must survive validation.
|
||||
{ channel: 'codeburn:getPeriodCompareSessions', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all', 'project', '-work-pricing'], argv: ['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--dimension', 'project', '--key', '-work-pricing'] },
|
||||
{ channel: 'codeburn:getCompareCohortModels', args: ['month', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b'] },
|
||||
{ channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha', '-Users-gone-alpha'], 'coding'], argv: ['compare', '--format', 'cohort-json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b', '--project-id=/Users/gone/alpha', '--project-id=-Users-gone-alpha', '--category', 'coding'] },
|
||||
{ channel: 'codeburn:getYield', args: ['today', 'all'], argv: ['yield', '--format', 'json', '--period', 'today'] },
|
||||
{ channel: 'codeburn:getYield', args: ['today', 'claude'], argv: ['yield', '--format', 'json', '--period', 'today', '--provider', 'claude'] },
|
||||
{ channel: 'codeburn:getSpendFlow', args: ['month', 'openai'], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--provider', 'openai'] },
|
||||
|
|
@ -261,6 +266,10 @@ describe('createBridgeHandlers (IPC input validation)', () => {
|
|||
{ name: 'device name that looks like a flag', channel: 'codeburn:removeDevice', args: ['-rf'] },
|
||||
{ name: 'relative export path', channel: 'codeburn:exportData', args: ['json', 'all', 'relative/out'] },
|
||||
{ name: 'compare model that looks like a flag', channel: 'codeburn:getCompare', args: ['month', 'all', '-a', 'model-b'] },
|
||||
{ name: 'cohort model that looks like a flag', channel: 'codeburn:getCompareCohort', args: ['month', 'all', '-a', 'model-b'] },
|
||||
{ name: 'cohort project identity containing NUL', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['bad\0id']] },
|
||||
{ name: 'empty cohort project identity', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, ['']] },
|
||||
{ name: 'unknown cohort category', channel: 'codeburn:getCompareCohort', args: ['month', 'all', 'model-a', 'model-b', undefined, undefined, 'not-a-category'] },
|
||||
{ name: 'price override model that looks like a flag', channel: 'codeburn:setPriceOverride', args: ['-x', { input: 1, output: 2 }] },
|
||||
{ name: 'non-positive price override rate', channel: 'codeburn:setPriceOverride', args: ['my-model', { input: 0, output: 2 }] },
|
||||
{ name: 'non-finite price override rate', channel: 'codeburn:setPriceOverride', args: ['my-model', { input: 1, output: Number.POSITIVE_INFINITY }] },
|
||||
|
|
@ -851,6 +860,14 @@ describe('project filter', () => {
|
|||
// contribution row either.
|
||||
await handlers['codeburn:getPeriodCompareSessions']!(rangeA, rangeB, 'all', 'model', 'sonnet')
|
||||
expect(calls[4]).toEqual(['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch', '--dimension', 'model', '--key', 'sonnet'])
|
||||
await handlers['codeburn:getCompareCohortModels']!('week', 'all')
|
||||
expect(calls[5]).toEqual(['compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch'])
|
||||
// --project-id narrows WITHIN the saved filter; it never replaces it.
|
||||
await handlers['codeburn:getCompareCohort']!('week', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha'])
|
||||
expect(calls[6]).toEqual([
|
||||
'compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch',
|
||||
'--model-a', 'model-a', '--model-b', 'model-b', '--project-id=/Users/gone/alpha',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -314,6 +314,29 @@ function vToken(value: string): string {
|
|||
if (value.startsWith('-')) throw new CliError('bad-args', 'argument must not start with "-"')
|
||||
return value
|
||||
}
|
||||
// Exact identities from the cohort facet report, not loose CLI patterns.
|
||||
// Keep the value attached to its flag so label-only ids starting with "-"
|
||||
// remain data; NUL is invalid in process argv.
|
||||
function vProjectIds(projects: string[] | undefined): string[] {
|
||||
if (!projects || projects.length === 0) return []
|
||||
for (const pattern of projects) {
|
||||
if (typeof pattern !== 'string' || pattern.length === 0 || pattern.includes('\0')) {
|
||||
throw new CliError('bad-args', 'invalid project identity')
|
||||
}
|
||||
}
|
||||
return projects.map(id => `--project-id=${id}`)
|
||||
}
|
||||
// Activity categories for the cohort selection: the ids behind the CLI's
|
||||
// --category (src/types.ts CATEGORY_LABELS keys). Duplicated here because the
|
||||
// main process deliberately does not import core src/ modules.
|
||||
const COHORT_CATEGORIES = new Set([
|
||||
'coding', 'debugging', 'feature', 'refactoring', 'testing', 'exploration',
|
||||
'planning', 'delegation', 'git', 'build/deploy', 'conversation', 'brainstorming', 'general',
|
||||
])
|
||||
function vCategory(category: string): string {
|
||||
if (!COHORT_CATEGORIES.has(category)) throw new CliError('bad-args', 'invalid category')
|
||||
return category
|
||||
}
|
||||
// Claude config source ids are `<kind>:<hex>` (src/providers/claude.ts) — the
|
||||
// colon is part of the real value, so the token class allows it while anchoring
|
||||
// the first char to alphanumeric so a leading "-" can never smuggle a flag.
|
||||
|
|
@ -600,6 +623,21 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
'--dimension', dimension, '--key', vContributionKey(key),
|
||||
]
|
||||
}),
|
||||
// Cohort mode: the facet query (models/projects/categories) and the report
|
||||
// for two models over an explicit selection. Same `compare` command, new
|
||||
// cohort-json format; project identities are exact, category is one id.
|
||||
'codeburn:getCompareCohortModels': run((period: string, provider: string, range?: DateRange) => [
|
||||
'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
|
||||
...projectArgs(), ...rangeArgs(vRange(range)),
|
||||
], 3),
|
||||
// The saved project filter still scopes the population; --project-id then
|
||||
// narrows it further to one identity the facet report offered.
|
||||
'codeburn:getCompareCohort': run((period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string) => [
|
||||
'compare', '--format', 'cohort-json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)),
|
||||
...projectArgs(),
|
||||
'--model-a', vToken(modelA), '--model-b', vToken(modelB), ...rangeArgs(vRange(range)),
|
||||
...(vProjectIds(projects)), ...(category ? ['--category', vCategory(category)] : []),
|
||||
], 7),
|
||||
'codeburn:getYield': run((period: string, provider: string, range?: DateRange) => [
|
||||
'yield', '--format', 'json', '--period', vPeriod(period),
|
||||
...providerArgs(vProvider(provider)),
|
||||
|
|
|
|||
|
|
@ -31,6 +31,9 @@ const bridge = {
|
|||
getCompare: (period: string, provider: string, modelA: string, modelB: string) => invoke('codeburn:getCompare', period, provider, modelA, modelB),
|
||||
getPeriodCompare: (rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean) => invoke('codeburn:getPeriodCompare', rangeA, rangeB, provider, background),
|
||||
getPeriodCompareSessions: (rangeA: DateRange, rangeB: DateRange, provider: string, dimension: string, key: string) => invoke('codeburn:getPeriodCompareSessions', rangeA, rangeB, provider, dimension, key),
|
||||
getCompareCohortModels: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getCompareCohortModels', period, provider, range, background),
|
||||
getCompareCohort: (period: string, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string, background?: boolean) =>
|
||||
invoke('codeburn:getCompareCohort', period, provider, modelA, modelB, range, projects, category, background),
|
||||
getYield: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getYield', period, provider, range, background),
|
||||
getSpendFlow: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getSpendFlow', period, provider, range, background),
|
||||
getBranchSpend: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getBranchSpend', period, provider, range, background),
|
||||
|
|
|
|||
|
|
@ -943,7 +943,7 @@ function AppMain() {
|
|||
) : section === 'models' ? (
|
||||
<Models period={period} provider={provider} range={customRange} refreshToken={refreshToken} onNavigate={navigate} onInvestigate={investigate} ready={ready} />
|
||||
) : section === 'compare' ? (
|
||||
<Compare period={period} provider={provider} range={customRange} refreshToken={refreshToken} ready={ready} />
|
||||
<Compare period={period} provider={provider} range={customRange} refreshToken={refreshToken} ready={ready} onInvestigate={investigate} />
|
||||
) : section === 'periods' ? (
|
||||
<PeriodCompare provider={provider} refreshToken={refreshToken} ready={ready} onInspectContribution={inspectContribution} />
|
||||
) : (
|
||||
|
|
|
|||
112
app/renderer/lib/cohortStats.test.ts
Normal file
112
app/renderer/lib/cohortStats.test.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
applyVolumeBand,
|
||||
computeBandCohortStats,
|
||||
costHistogram,
|
||||
linearPercentile,
|
||||
medianOf,
|
||||
} from './cohortStats'
|
||||
import type { CohortObservation } from './types'
|
||||
|
||||
function obs(over: Partial<CohortObservation> = {}): CohortObservation {
|
||||
return {
|
||||
sessionId: 's1',
|
||||
provider: 'claude',
|
||||
project: 'proj-a',
|
||||
timestamp: '2026-08-15T10:00:00Z',
|
||||
category: 'coding',
|
||||
model: 'model-a',
|
||||
costUSD: 0.1,
|
||||
costKnown: true,
|
||||
retries: 0,
|
||||
oneShot: true,
|
||||
inputTokens: 1000,
|
||||
outputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
cacheWriteTokens: 100,
|
||||
contextProxyTokens: 3000,
|
||||
tokensReported: true,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('renderer percentile mirror (pinned to the core convention)', () => {
|
||||
it('gives median 3 and P90 6.8 for [1, 2, 4, 8] with linear interpolation at (N-1)*p', () => {
|
||||
const sorted = [1, 2, 4, 8]
|
||||
expect(medianOf(sorted)).toBe(3)
|
||||
expect(linearPercentile(sorted, 0.9)).toBeCloseTo(6.8, 10)
|
||||
})
|
||||
|
||||
it('degenerates safely: empty → null, single value → itself', () => {
|
||||
expect(linearPercentile([], 0.9)).toBeNull()
|
||||
expect(linearPercentile([7], 0.9)).toBe(7)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyVolumeBand', () => {
|
||||
it('keeps the whole population when no band is set', () => {
|
||||
const observations = [obs(), obs({ outputTokens: 999999 })]
|
||||
const result = applyVolumeBand(observations, null)
|
||||
expect(result.kept).toHaveLength(2)
|
||||
expect(result.outsideBand).toBe(0)
|
||||
expect(result.missingMeasure).toBe(0)
|
||||
})
|
||||
|
||||
it('excludes observations outside the band and counts them', () => {
|
||||
const observations = [obs({ outputTokens: 100 }), obs({ outputTokens: 5000 }), obs({ outputTokens: 900000 })]
|
||||
const result = applyVolumeBand(observations, { measure: 'output', min: 1000, max: 10000 })
|
||||
expect(result.kept.map(o => o.outputTokens)).toEqual([5000])
|
||||
expect(result.outsideBand).toBe(2)
|
||||
})
|
||||
|
||||
it('never treats observations without token data as small: they are excluded and counted', () => {
|
||||
const observations = [obs({ tokensReported: false, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0 }), obs()]
|
||||
const result = applyVolumeBand(observations, { measure: 'output', min: null, max: 1000000 })
|
||||
expect(result.kept).toHaveLength(1)
|
||||
expect(result.missingMeasure).toBe(1)
|
||||
expect(result.outsideBand).toBe(0)
|
||||
})
|
||||
|
||||
it('bands the context proxy measure on input + cache read', () => {
|
||||
const low = obs({ inputTokens: 10, cacheReadTokens: 20, contextProxyTokens: 30 })
|
||||
const high = obs({ inputTokens: 5000, cacheReadTokens: 50000, contextProxyTokens: 55000 })
|
||||
const result = applyVolumeBand([low, high], { measure: 'contextProxy', min: 1000, max: null })
|
||||
expect(result.kept).toEqual([high])
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeBandCohortStats over the band-filtered population', () => {
|
||||
it('divides rates by the declared (band-filtered) population', () => {
|
||||
const kept = [
|
||||
obs({ retries: 1, oneShot: false, costUSD: 1 }),
|
||||
obs({ retries: 0, costUSD: 2 }),
|
||||
obs({ retries: 2, oneShot: false, costUSD: 4 }),
|
||||
obs({ retries: 0, costUSD: 8 }),
|
||||
]
|
||||
const stats = computeBandCohortStats('model-a', kept)
|
||||
expect(stats.observationCount).toBe(4)
|
||||
// The exact pinned vector, through the full band-stats path.
|
||||
expect(stats.costMedian).toBe(3)
|
||||
expect(stats.costP90).toBeCloseTo(6.8, 10)
|
||||
expect(stats.retryCount).toBe(3)
|
||||
expect(stats.retryRate).toBeCloseTo(0.75)
|
||||
expect(stats.oneShotRate).toBe(50)
|
||||
})
|
||||
|
||||
it('counts unknown cost observations separately and keeps them out of cost percentiles', () => {
|
||||
const kept = [obs({ costKnown: false, costUSD: 0 }), obs({ costUSD: 0.5 })]
|
||||
const stats = computeBandCohortStats('model-a', kept)
|
||||
expect(stats.unknownCostCount).toBe(1)
|
||||
expect(stats.costKnownCount).toBe(1)
|
||||
expect(stats.costMedian).toBe(0.5)
|
||||
})
|
||||
|
||||
it('keeps histograms deterministic and totalling the population', () => {
|
||||
const costs = [0.1, 0.2, 0.3, 0.4, 0.5]
|
||||
const h1 = costHistogram(costs)
|
||||
const h2 = costHistogram([...costs].reverse())
|
||||
expect(h1).toEqual(h2)
|
||||
expect(h1.counts.reduce((a, b) => a + b, 0)).toBe(5)
|
||||
})
|
||||
})
|
||||
134
app/renderer/lib/cohortStats.ts
Normal file
134
app/renderer/lib/cohortStats.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
import type { CohortObservation, CohortStats, CohortVolumeStats } from './types'
|
||||
|
||||
/**
|
||||
* Renderer-side cohort math over the DECLARED population a cohort-json report
|
||||
* carries. The core implementation is src/compare-cohorts.ts; this mirror
|
||||
* exists so volume-band changes recompute instantly from the report's own
|
||||
* observation list instead of respawning the CLI, and both sides pin the same
|
||||
* percentile convention in tests: sort ascending, position (N-1)*p, linear
|
||||
* interpolation — [1, 2, 4, 8] → median 3, P90 6.8.
|
||||
*/
|
||||
|
||||
/** Volume measure an observation carries. `contextProxy` is input + cache-read
|
||||
* tokens — a proxy, not a measured context window; callers must label it so. */
|
||||
export type VolumeMeasure = 'output' | 'input' | 'contextProxy'
|
||||
|
||||
export type VolumeBand = {
|
||||
measure: VolumeMeasure
|
||||
min: number | null
|
||||
max: number | null
|
||||
}
|
||||
|
||||
export function linearPercentile(sorted: readonly number[], p: number): number | null {
|
||||
if (sorted.length === 0) return null
|
||||
if (sorted.length === 1) return sorted[0] as number
|
||||
const pos = (sorted.length - 1) * p
|
||||
const lower = Math.floor(pos)
|
||||
const upper = Math.ceil(pos)
|
||||
if (lower === upper) return sorted[lower] as number
|
||||
const fraction = pos - lower
|
||||
return (sorted[lower] as number) * (1 - fraction) + (sorted[upper] as number) * fraction
|
||||
}
|
||||
|
||||
export function medianOf(sorted: readonly number[]): number | null {
|
||||
return linearPercentile(sorted, 0.5)
|
||||
}
|
||||
|
||||
export function volumeOf(observation: CohortObservation, measure: VolumeMeasure): number {
|
||||
if (measure === 'output') return observation.outputTokens
|
||||
if (measure === 'input') return observation.inputTokens
|
||||
return observation.contextProxyTokens
|
||||
}
|
||||
|
||||
export type BandFilterResult = {
|
||||
/** Observations inside the band — the new declared population. */
|
||||
kept: CohortObservation[]
|
||||
/** Observations dropped because they fall OUTSIDE the band edges. */
|
||||
outsideBand: number
|
||||
/** Observations dropped because they carry NO token measure at all. A band
|
||||
* must never read these as small context — they are excluded and counted. */
|
||||
missingMeasure: number
|
||||
}
|
||||
|
||||
export function applyVolumeBand(observations: readonly CohortObservation[], band: VolumeBand | null): BandFilterResult {
|
||||
if (!band || (band.min == null && band.max == null)) {
|
||||
return { kept: [...observations], outsideBand: 0, missingMeasure: 0 }
|
||||
}
|
||||
const kept: CohortObservation[] = []
|
||||
let outsideBand = 0
|
||||
let missingMeasure = 0
|
||||
for (const observation of observations) {
|
||||
if (!observation.tokensReported) {
|
||||
missingMeasure++
|
||||
continue
|
||||
}
|
||||
const value = volumeOf(observation, band.measure)
|
||||
if (band.min != null && value < band.min) { outsideBand++; continue }
|
||||
if (band.max != null && value > band.max) { outsideBand++; continue }
|
||||
kept.push(observation)
|
||||
}
|
||||
return { kept, outsideBand, missingMeasure }
|
||||
}
|
||||
|
||||
const HISTOGRAM_BUCKETS = 8
|
||||
|
||||
/** Same deterministic histogram as the core: linear edges 0 → P95 of known
|
||||
* costs, top bucket open-ended so outliers stretch nothing. */
|
||||
export function costHistogram(costs: readonly number[]): { edges: number[]; counts: number[] } {
|
||||
if (costs.length === 0) return { edges: [], counts: [] }
|
||||
const sorted = [...costs].sort((a, b) => a - b)
|
||||
const p95 = linearPercentile(sorted, 0.95) ?? 0
|
||||
if (p95 <= 0) return { edges: [], counts: [costs.length] }
|
||||
const edges: number[] = []
|
||||
for (let i = 1; i < HISTOGRAM_BUCKETS; i++) edges.push((p95 * i) / HISTOGRAM_BUCKETS)
|
||||
const counts = new Array(HISTOGRAM_BUCKETS).fill(0)
|
||||
for (const cost of costs) {
|
||||
let bucket = 0
|
||||
while (bucket < edges.length && cost >= (edges[bucket] as number)) bucket++
|
||||
counts[bucket]++
|
||||
}
|
||||
return { edges, counts }
|
||||
}
|
||||
|
||||
export function computeBandCohortStats(model: string, observations: readonly CohortObservation[]): CohortStats {
|
||||
const knownCosts = observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
|
||||
const knownCostSum = knownCosts.reduce((sum, c) => sum + c, 0)
|
||||
const sessionKeys = new Set(observations.map(o => `${o.project}/${o.sessionId}`))
|
||||
const reported = observations.filter(o => o.tokensReported)
|
||||
const byMeasure = (pick: (o: CohortObservation) => number) => reported.map(pick).sort((a, b) => a - b)
|
||||
const outputTokens = byMeasure(o => o.outputTokens)
|
||||
const inputTokens = byMeasure(o => o.inputTokens)
|
||||
const contextProxy = byMeasure(o => o.contextProxyTokens)
|
||||
|
||||
const retryCount = observations.reduce((sum, o) => sum + o.retries, 0)
|
||||
const oneShotCount = observations.filter(o => o.oneShot).length
|
||||
const n = observations.length
|
||||
|
||||
const volume: CohortVolumeStats = {
|
||||
outputMedian: medianOf(outputTokens),
|
||||
outputP90: linearPercentile(outputTokens, 0.9),
|
||||
inputMedian: medianOf(inputTokens),
|
||||
inputP90: linearPercentile(inputTokens, 0.9),
|
||||
contextProxyMedian: medianOf(contextProxy),
|
||||
contextProxyP90: linearPercentile(contextProxy, 0.9),
|
||||
missingMeasureCount: observations.filter(o => !o.tokensReported).length,
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
label: model,
|
||||
observationCount: n,
|
||||
distinctSessionCount: sessionKeys.size,
|
||||
retryCount,
|
||||
retryRate: n > 0 ? retryCount / n : null,
|
||||
oneShotCount,
|
||||
oneShotRate: n > 0 ? (oneShotCount / n) * 100 : null,
|
||||
costKnownCount: knownCosts.length,
|
||||
unknownCostCount: n - knownCosts.length,
|
||||
costMedian: medianOf(knownCosts),
|
||||
costP90: linearPercentile(knownCosts, 0.9),
|
||||
costMean: knownCosts.length > 0 ? knownCostSum / knownCosts.length : null,
|
||||
costHistogram: costHistogram(knownCosts),
|
||||
volume,
|
||||
}
|
||||
}
|
||||
|
|
@ -723,6 +723,101 @@ export type CompareJsonReport = {
|
|||
workingStyle: WorkingStyleRow[]
|
||||
}
|
||||
|
||||
// ————— src/compare-cohorts.ts (compare --format cohort-json) —————
|
||||
// Mirrors the core contracts 1:1. The renderer never imports the Node engine,
|
||||
// so these hand copies ARE the IPC types; tests on both sides pin the same
|
||||
// percentile convention ([1,2,4,8] → median 3, P90 6.8).
|
||||
|
||||
/** One observation = one edit turn whose behavioral calls carry exactly one
|
||||
* model. `costUSD` is that model's own recorded cost in the turn (never
|
||||
* another model's, never the session total). */
|
||||
export type CohortObservation = {
|
||||
sessionId: string
|
||||
provider: string
|
||||
project: string
|
||||
timestamp: string
|
||||
category: string
|
||||
model: string
|
||||
costUSD: number
|
||||
/** False when costUSD is 0 on a model the pricing rules do not declare free
|
||||
* — a pricing gap, never displayed as a real $0 observation. */
|
||||
costKnown: boolean
|
||||
retries: number
|
||||
oneShot: boolean
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
/** input + cache-read tokens: an explicit PROXY for context size, never a
|
||||
* measured context window. */
|
||||
contextProxyTokens: number
|
||||
/** False when the turn's calls report no tokens at all; volume bands must
|
||||
* exclude and count these, never read them as small. */
|
||||
tokensReported: boolean
|
||||
}
|
||||
|
||||
export type CohortVolumeStats = {
|
||||
outputMedian: number | null
|
||||
outputP90: number | null
|
||||
inputMedian: number | null
|
||||
inputP90: number | null
|
||||
contextProxyMedian: number | null
|
||||
contextProxyP90: number | null
|
||||
missingMeasureCount: number
|
||||
}
|
||||
|
||||
export type CohortStats = {
|
||||
model: string
|
||||
label: string
|
||||
/** Declared population the rates below divide by (selection filters, plus a
|
||||
* volume band when one is active). */
|
||||
observationCount: number
|
||||
distinctSessionCount: number
|
||||
retryCount: number
|
||||
retryRate: number | null
|
||||
oneShotCount: number
|
||||
oneShotRate: number | null
|
||||
costKnownCount: number
|
||||
unknownCostCount: number
|
||||
costMedian: number | null
|
||||
costP90: number | null
|
||||
costMean: number | null
|
||||
costHistogram: { edges: number[]; counts: number[] }
|
||||
volume: CohortVolumeStats
|
||||
}
|
||||
|
||||
export type CohortModelReport = {
|
||||
model: string
|
||||
label: string
|
||||
stats: CohortStats
|
||||
/** The declared population itself: every statistic is reproducible from it. */
|
||||
observations: CohortObservation[]
|
||||
exclusions: {
|
||||
multiModelTurnCount: number
|
||||
combinedMultiModelCostUSD: number
|
||||
noBehavioralModelTurns: number
|
||||
}
|
||||
}
|
||||
|
||||
export type CohortComparisonReport = {
|
||||
kind: 'cohort-comparison'
|
||||
period: { label: string; provider: string }
|
||||
selection: { projects: string[]; category: string | null; from: string | null; to: string | null }
|
||||
conventions: {
|
||||
percentile: string
|
||||
contextProxy: string
|
||||
attribution: string
|
||||
}
|
||||
modelA: CohortModelReport
|
||||
modelB: CohortModelReport
|
||||
}
|
||||
|
||||
export type CohortFacets = {
|
||||
kind: 'cohort-facets'
|
||||
models: ModelStats[]
|
||||
projects: Array<{ id: string; project: string; projectPath: string; sessions: number; costUSD: number }>
|
||||
categories: Array<{ id: string; label: string }>
|
||||
}
|
||||
// ---- Compare periods (period-diff; B minus A, A is the reference) ----
|
||||
// Mirrors the JSON emitted by `codeburn compare-periods --format json`
|
||||
// (src/period-diff.ts). Raw (unrounded) numbers; the UI formats.
|
||||
|
|
@ -983,6 +1078,10 @@ export interface CodeburnBridge {
|
|||
getSessionsContributions(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<SessionDrillRow[]>
|
||||
getCompareModels(period: Period, provider: string, background?: boolean): Promise<ModelStats[]>
|
||||
getCompare(period: Period, provider: string, modelA: string, modelB: string): Promise<CompareJsonReport>
|
||||
/** Cohort mode facets: models, canonical projects, activity categories. */
|
||||
getCompareCohortModels(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<CohortFacets>
|
||||
/** Cohort mode report; projects contains exact ids from CohortFacets. */
|
||||
getCompareCohort(period: Period, provider: string, modelA: string, modelB: string, range?: DateRange, projects?: string[], category?: string, background?: boolean): Promise<CohortComparisonReport>
|
||||
/** Compare periods (B minus A). Both ranges are required local YYYY-MM-DD keys. */
|
||||
getPeriodCompare(rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean): Promise<PeriodDiffReport>
|
||||
/** Sessions behind one project/model contribution, joined across A and B. */
|
||||
|
|
|
|||
|
|
@ -3,12 +3,14 @@ import { render, screen, waitFor, within } from '@testing-library/react'
|
|||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { CompareJsonReport, ModelStats } from '../lib/types'
|
||||
import type { CohortComparisonReport, CompareJsonReport, ModelStats } from '../lib/types'
|
||||
import { Compare } from './Compare'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getCompareModels: vi.fn<(period: string, provider: string) => Promise<ModelStats[]>>(),
|
||||
getCompare: vi.fn<(period: string, provider: string, modelA: string, modelB: string) => Promise<CompareJsonReport>>(),
|
||||
getCompareCohortModels: vi.fn<(period: string, provider: string) => Promise<import('../lib/types').CohortFacets>>(),
|
||||
getCompareCohort: vi.fn<(period: string, provider: string, modelA: string, modelB: string, range?: unknown, projects?: string[], category?: string) => Promise<CohortComparisonReport>>(),
|
||||
telemetryTrack: vi.fn<(name: string, props?: Record<string, unknown>) => Promise<boolean>>(),
|
||||
}))
|
||||
vi.mock('../lib/ipc', async orig => {
|
||||
|
|
@ -48,6 +50,8 @@ describe('Compare', () => {
|
|||
beforeEach(() => {
|
||||
mocks.getCompareModels.mockReset()
|
||||
mocks.getCompare.mockReset()
|
||||
mocks.getCompareCohortModels.mockReset()
|
||||
mocks.getCompareCohort.mockReset()
|
||||
mocks.telemetryTrack.mockReset().mockResolvedValue(true)
|
||||
})
|
||||
|
||||
|
|
@ -128,3 +132,176 @@ describe('Compare', () => {
|
|||
expect(mocks.getCompare).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Cohorts mode —————
|
||||
|
||||
const cohortReport: CohortComparisonReport = {
|
||||
kind: 'cohort-comparison',
|
||||
period: { label: 'Last 30 days', provider: 'all' },
|
||||
selection: { projects: [], category: null, from: null, to: null },
|
||||
conventions: {
|
||||
percentile: 'linear interpolation at position (N-1)*p',
|
||||
contextProxy: 'input + cache-read tokens (proxy, not a measured context window)',
|
||||
attribution: 'observation cost = recorded cost of the owning model\'s calls in the turn',
|
||||
},
|
||||
modelA: {
|
||||
model: 'Opus 4.8',
|
||||
label: 'Opus 4.8',
|
||||
stats: {
|
||||
model: 'Opus 4.8', label: 'Opus 4.8', observationCount: 4, distinctSessionCount: 2,
|
||||
retryCount: 3, retryRate: 0.75, oneShotCount: 2, oneShotRate: 50,
|
||||
costKnownCount: 4, unknownCostCount: 0,
|
||||
costMedian: 3, costP90: 6.8, costMean: 3.75,
|
||||
costHistogram: { edges: [1, 2, 3, 4, 5, 6, 7], counts: [1, 1, 0, 1, 0, 0, 0, 1] },
|
||||
volume: { outputMedian: 500, outputP90: 900, inputMedian: 1000, inputP90: 2000, contextProxyMedian: 3000, contextProxyP90: 5000, missingMeasureCount: 0 },
|
||||
},
|
||||
observations: [
|
||||
{ sessionId: 's1', provider: 'claude', project: '/work/app', timestamp: '2026-08-14T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 1, costKnown: true, retries: 1, oneShot: false, inputTokens: 1000, outputTokens: 500, cacheReadTokens: 2000, cacheWriteTokens: 100, contextProxyTokens: 3000, tokensReported: true },
|
||||
{ sessionId: 's1', provider: 'claude', project: '/work/app', timestamp: '2026-08-14T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 2, costKnown: true, retries: 0, oneShot: true, inputTokens: 1200, outputTokens: 600, cacheReadTokens: 2200, cacheWriteTokens: 100, contextProxyTokens: 3400, tokensReported: true },
|
||||
{ sessionId: 's2', provider: 'claude', project: '/work/kit', timestamp: '2026-08-15T10:00:00Z', category: 'debugging', model: 'Opus 4.8', costUSD: 4, costKnown: true, retries: 2, oneShot: false, inputTokens: 1500, outputTokens: 800, cacheReadTokens: 3000, cacheWriteTokens: 100, contextProxyTokens: 4500, tokensReported: true },
|
||||
{ sessionId: 's2', provider: 'claude', project: '/work/kit', timestamp: '2026-08-15T11:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 8, costKnown: true, retries: 0, oneShot: true, inputTokens: 4000, outputTokens: 900, cacheReadTokens: 5000, cacheWriteTokens: 100, contextProxyTokens: 9000, tokensReported: true },
|
||||
],
|
||||
exclusions: { multiModelTurnCount: 1, combinedMultiModelCostUSD: 0.15, noBehavioralModelTurns: 0 },
|
||||
},
|
||||
modelB: {
|
||||
model: 'Sonnet 5',
|
||||
label: 'Sonnet 5',
|
||||
stats: {
|
||||
model: 'Sonnet 5', label: 'Sonnet 5', observationCount: 0, distinctSessionCount: 0,
|
||||
retryCount: 0, retryRate: null, oneShotCount: 0, oneShotRate: null,
|
||||
costKnownCount: 0, unknownCostCount: 0,
|
||||
costMedian: null, costP90: null, costMean: null,
|
||||
costHistogram: { edges: [], counts: [] },
|
||||
volume: { outputMedian: null, outputP90: null, inputMedian: null, inputP90: null, contextProxyMedian: null, contextProxyP90: null, missingMeasureCount: 0 },
|
||||
},
|
||||
observations: [],
|
||||
exclusions: { multiModelTurnCount: 1, combinedMultiModelCostUSD: 0.15, noBehavioralModelTurns: 0 },
|
||||
},
|
||||
}
|
||||
|
||||
const facets = {
|
||||
kind: 'cohort-facets' as const,
|
||||
models: [modelA, modelB],
|
||||
projects: [
|
||||
{ id: '/work/app', project: '-work-app', projectPath: '/work/app', sessions: 1, costUSD: 10 },
|
||||
{ id: '/work/app-backend', project: '-work-app-backend', projectPath: '/work/app-backend', sessions: 1, costUSD: 5 },
|
||||
{ id: '/work/kit', project: '-work-kit', projectPath: '/work/kit', sessions: 1, costUSD: 5 },
|
||||
],
|
||||
categories: [
|
||||
{ id: 'coding', label: 'Coding' },
|
||||
{ id: 'debugging', label: 'Debugging' },
|
||||
],
|
||||
}
|
||||
|
||||
describe('Compare cohorts mode', () => {
|
||||
beforeEach(() => {
|
||||
mocks.getCompareModels.mockReset()
|
||||
mocks.getCompare.mockReset()
|
||||
mocks.getCompareCohortModels.mockReset()
|
||||
mocks.getCompareCohort.mockReset()
|
||||
mocks.telemetryTrack.mockReset().mockResolvedValue(true)
|
||||
// The classic view mounts first (the mode switch lives inside it), so the
|
||||
// classic mocks need implementations even in cohort-only tests.
|
||||
mocks.getCompareModels.mockResolvedValue([modelA, modelB])
|
||||
mocks.getCompare.mockResolvedValue(report)
|
||||
mocks.getCompareCohortModels.mockResolvedValue(facets)
|
||||
mocks.getCompareCohort.mockResolvedValue(cohortReport)
|
||||
})
|
||||
|
||||
async function openCohorts(onInvestigate?: (request: unknown) => void) {
|
||||
const user = userEvent.setup()
|
||||
render(<Compare period="30days" provider="all" onInvestigate={onInvestigate as never} />)
|
||||
await user.click(await screen.findByRole('tab', { name: 'Cohorts' }))
|
||||
await screen.findByLabelText('Cohort first model')
|
||||
await screen.findByLabelText('Cohort second model')
|
||||
await screen.findByText('Population')
|
||||
return user
|
||||
}
|
||||
|
||||
it('shows the population disclosure before the metrics and requests the cohort report', async () => {
|
||||
await openCohorts()
|
||||
expect(mocks.getCompareCohort).toHaveBeenCalledWith('30days', 'all', 'Opus 4.8', 'Sonnet 5', undefined, undefined, undefined)
|
||||
// Exclusion ledger visible: mixed-model turns with their combined cost.
|
||||
expect(screen.getAllByText(/Excluded turns mixing models/).length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('1 ($0.15)').length).toBe(2)
|
||||
// Metrics cards render the pinned convention numbers.
|
||||
expect(screen.getAllByText('$3.00').length).toBeGreaterThanOrEqual(1)
|
||||
expect(screen.getAllByText('$6.80').length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('renders a zero-observation cohort as explicit emptiness, not zeros', async () => {
|
||||
const user = await openCohorts()
|
||||
const second = screen.getByLabelText('Cohort second model')
|
||||
// Keep Sonnet 5 selected: its cohort is empty → the sample card explains it.
|
||||
expect(second).toBeInTheDocument()
|
||||
expect(await screen.findByText(/No observations match the current selection/)).toBeInTheDocument()
|
||||
expect(mocks.getCompareCohort).toHaveBeenCalled()
|
||||
void user
|
||||
})
|
||||
|
||||
it('passes a project selection through so out-of-selection observations are excluded before calculation', async () => {
|
||||
const user = await openCohorts()
|
||||
await user.click(screen.getByLabelText('Cohort project'))
|
||||
await user.click(await screen.findByRole('option', { name: 'work/app' }))
|
||||
await waitFor(() => expect(mocks.getCompareCohort).toHaveBeenCalledWith('30days', 'all', 'Opus 4.8', 'Sonnet 5', undefined, ['/work/app'], undefined))
|
||||
})
|
||||
|
||||
it('applies a volume band from the declared population and shows what it excluded', async () => {
|
||||
const user = await openCohorts()
|
||||
// Band on output tokens [0, 700]: keeps 2 of the 4 Opus observations
|
||||
// (output 500 and 600); the 800 and 900 ones are excluded and counted.
|
||||
await user.type(screen.getByLabelText('Volume band minimum'), '0')
|
||||
await user.type(screen.getByLabelText('Volume band maximum'), '700')
|
||||
await waitFor(() => expect(screen.getByText(/Volume band excludes 2 observation/)).toBeInTheDocument())
|
||||
// The recomputed median over the kept costs [1, 2] is 1.5.
|
||||
expect(screen.getAllByText('$1.50').length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('counts band exclusions of observations without token data, never reading them as small', async () => {
|
||||
const user = await openCohorts()
|
||||
// A report as the CLI would answer for the /work/app project: two
|
||||
// token-bearing observations plus one with NO token measure at all.
|
||||
const withMissing = {
|
||||
...cohortReport,
|
||||
modelA: {
|
||||
...cohortReport.modelA,
|
||||
observations: [
|
||||
cohortReport.modelA.observations[0]!,
|
||||
cohortReport.modelA.observations[1]!,
|
||||
{ sessionId: 's3', provider: 'claude', project: '/work/app', timestamp: '2026-08-16T10:00:00Z', category: 'coding', model: 'Opus 4.8', costUSD: 0.5, costKnown: true, retries: 0, oneShot: true, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, contextProxyTokens: 0, tokensReported: false },
|
||||
],
|
||||
},
|
||||
}
|
||||
mocks.getCompareCohort.mockResolvedValue(withMissing)
|
||||
// A new selection = a new memo key = a real re-fetch of the new payload.
|
||||
await user.click(screen.getByLabelText('Cohort project'))
|
||||
await user.click(await screen.findByRole('option', { name: 'work/app' }))
|
||||
await user.type(screen.getByLabelText('Volume band minimum'), '0')
|
||||
await user.type(screen.getByLabelText('Volume band maximum'), '700')
|
||||
await waitFor(() => expect(screen.getByText(/without any token measure/)).toBeInTheDocument())
|
||||
// The missing-measure observation is excluded from the banded stats
|
||||
// (2 of the 4 observations in the spread mock survive the band; the mock
|
||||
// carries the original stats object, hence 4). The first Inspect samples
|
||||
// card is model A's.
|
||||
expect(screen.getAllByText('Inspect samples')[0]!.closest('.cmp-card')).toHaveTextContent('2 of 4 in selection')
|
||||
})
|
||||
|
||||
it('drills a sample through to its session with the shared investigation key', async () => {
|
||||
const onInvestigate = vi.fn()
|
||||
const user = await openCohorts(onInvestigate)
|
||||
await user.click(screen.getAllByTitle(/^Open session: /)[0]!)
|
||||
expect(onInvestigate).toHaveBeenCalledWith({
|
||||
filters: expect.objectContaining({ sessions: [{ provider: 'claude', sessionId: 's2' }] }),
|
||||
sessionId: 'claude\u0000/work/kit\u0000s2',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns to the classic comparison unchanged', async () => {
|
||||
const user = await openCohorts()
|
||||
mocks.getCompareModels.mockResolvedValue([modelA, modelB])
|
||||
mocks.getCompare.mockResolvedValue(report)
|
||||
await user.click(screen.getByRole('tab', { name: 'Classic' }))
|
||||
expect(await screen.findByLabelText('First model')).toBeInTheDocument()
|
||||
expect(await screen.findByText('Performance')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,17 +1,37 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
import { CliErrorPanel } from '../components/CliErrorPanel'
|
||||
import { Dropdown } from '../components/Dropdown'
|
||||
import { EmptyNote } from '../components/EmptyState'
|
||||
import { Panel } from '../components/Panel'
|
||||
import { SegTabs } from '../components/SegTabs'
|
||||
import { SectionSkeleton } from '../components/Skeleton'
|
||||
import { SwitchingBanner } from '../components/SwitchingBanner'
|
||||
import { usePolled } from '../hooks/usePolled'
|
||||
import { formatCompact, formatUsd } from '../lib/format'
|
||||
import {
|
||||
applyVolumeBand,
|
||||
computeBandCohortStats,
|
||||
type VolumeBand,
|
||||
type VolumeMeasure,
|
||||
} from '../lib/cohortStats'
|
||||
import { formatCompact, formatUsd, shortenProjectPath } from '../lib/format'
|
||||
import { codeburn } from '../lib/ipc'
|
||||
import { reportMemoKey } from '../lib/reportMemoKey'
|
||||
import { sessionFilters } from '../lib/investigation'
|
||||
import { trackEvent } from '../lib/track'
|
||||
import type { CompareJsonReport, ComparisonRow, DateRange, ModelStats, Period, WorkingStyleRow } from '../lib/types'
|
||||
import type { InvestigateRequest } from './Overview'
|
||||
import { sessionRowKey } from './Sessions'
|
||||
import type {
|
||||
CohortComparisonReport,
|
||||
CohortModelReport,
|
||||
CohortObservation,
|
||||
CompareJsonReport,
|
||||
ComparisonRow,
|
||||
DateRange,
|
||||
ModelStats,
|
||||
Period,
|
||||
WorkingStyleRow,
|
||||
} from '../lib/types'
|
||||
|
||||
function fmtMetric(v: number | null, fn: 'cost' | 'number' | 'percent' | 'decimal'): string {
|
||||
if (v === null) return '—'
|
||||
|
|
@ -31,18 +51,72 @@ function RangeNote() {
|
|||
)
|
||||
}
|
||||
|
||||
type CompareMode = 'classic' | 'cohorts'
|
||||
|
||||
export function Compare({
|
||||
period,
|
||||
provider,
|
||||
range = null,
|
||||
refreshToken = 0,
|
||||
ready = true,
|
||||
onInvestigate,
|
||||
}: {
|
||||
period: Period
|
||||
provider: string
|
||||
range?: DateRange | null
|
||||
refreshToken?: number
|
||||
ready?: boolean
|
||||
onInvestigate?: (request: InvestigateRequest) => void
|
||||
}) {
|
||||
const [mode, setMode] = useState<CompareMode>('classic')
|
||||
|
||||
if (mode === 'cohorts') {
|
||||
return (
|
||||
<div className="cmp-body">
|
||||
<div className="cmp-picker" aria-label="Compare mode">
|
||||
<SegTabs
|
||||
options={[
|
||||
{ value: 'classic', label: 'Classic' },
|
||||
{ value: 'cohorts', label: 'Cohorts' },
|
||||
]}
|
||||
value={mode}
|
||||
onChange={next => setMode(next as CompareMode)}
|
||||
/>
|
||||
</div>
|
||||
<CohortCompare period={period} provider={provider} range={range} refreshToken={refreshToken} ready={ready} onInvestigate={onInvestigate} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="cmp-body">
|
||||
<div className="cmp-picker" aria-label="Compare mode">
|
||||
<SegTabs
|
||||
options={[
|
||||
{ value: 'classic', label: 'Classic' },
|
||||
{ value: 'cohorts', label: 'Cohorts' },
|
||||
]}
|
||||
value={mode}
|
||||
onChange={next => setMode(next as CompareMode)}
|
||||
/>
|
||||
</div>
|
||||
<ClassicCompare period={period} provider={provider} range={range} refreshToken={refreshToken} ready={ready} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ClassicCompare({
|
||||
period,
|
||||
provider,
|
||||
range,
|
||||
refreshToken,
|
||||
ready,
|
||||
}: {
|
||||
period: Period
|
||||
provider: string
|
||||
range: DateRange | null
|
||||
refreshToken: number
|
||||
ready: boolean
|
||||
}) {
|
||||
const models = usePolled<ModelStats[]>(
|
||||
() => codeburn.getCompareModels(period, provider),
|
||||
|
|
@ -286,3 +360,457 @@ function ContextCard({ modelA, modelB }: { modelA: ModelStats; modelB: ModelStat
|
|||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ————— Cohorts mode: model comparison over an explicit, inspectable population —————
|
||||
|
||||
const SAMPLES_INITIAL_COUNT = 20
|
||||
|
||||
type BandMeasureLabel = { value: VolumeMeasure; label: string }
|
||||
|
||||
const BAND_MEASURES: BandMeasureLabel[] = [
|
||||
{ value: 'output', label: 'Output tokens' },
|
||||
{ value: 'input', label: 'Input tokens' },
|
||||
{ value: 'contextProxy', label: 'Context proxy (input + cache read)' },
|
||||
]
|
||||
|
||||
function CohortCompare({
|
||||
period,
|
||||
provider,
|
||||
range,
|
||||
refreshToken,
|
||||
ready,
|
||||
onInvestigate,
|
||||
}: {
|
||||
period: Period
|
||||
provider: string
|
||||
range: DateRange | null
|
||||
refreshToken: number
|
||||
ready: boolean
|
||||
onInvestigate?: (request: InvestigateRequest) => void
|
||||
}) {
|
||||
const facets = usePolled(
|
||||
() => codeburn.getCompareCohortModels(period, provider, range ?? undefined),
|
||||
[period, provider, range?.from, range?.to, refreshToken],
|
||||
{ enabled: ready, memoKey: reportMemoKey('cohortmodels-v2', period, provider, range) },
|
||||
)
|
||||
|
||||
const [modelA, setModelA] = useState<string | null>(null)
|
||||
const [modelB, setModelB] = useState<string | null>(null)
|
||||
const [project, setProject] = useState<string>('')
|
||||
const [category, setCategory] = useState<string>('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!facets.data) return
|
||||
const available = new Set(facets.data.models.map(model => model.model))
|
||||
setModelA(current => current && available.has(current) ? current : facets.data?.models[0]?.model ?? null)
|
||||
setModelB(current => current && available.has(current) ? current : facets.data?.models[1]?.model ?? null)
|
||||
// A project/category that vanished from the population must not keep
|
||||
// filtering silently: fall back to "all".
|
||||
setProject(current => {
|
||||
if (!current) return ''
|
||||
return facets.data?.projects.some(p => p.id === current) ? current : ''
|
||||
})
|
||||
}, [facets.data])
|
||||
|
||||
const report = usePolled<CohortComparisonReport>(
|
||||
() => codeburn.getCompareCohort(period, provider, modelA ?? '', modelB ?? '', range ?? undefined, project ? [project] : undefined, category || undefined),
|
||||
[period, provider, modelA, modelB, range?.from, range?.to, project, category, refreshToken],
|
||||
{
|
||||
enabled: ready && !!modelA && !!modelB && modelA !== modelB,
|
||||
memoKey: reportMemoKey('cohort-v2', period, provider, range, JSON.stringify([modelA, modelB, project, category])),
|
||||
},
|
||||
)
|
||||
|
||||
if (!facets.data) {
|
||||
if (facets.error) return <CliErrorPanel error={facets.error} subject="model comparisons" />
|
||||
return <SectionSkeleton label="Scanning model usage…" rows={4} />
|
||||
}
|
||||
|
||||
if (facets.data.models.length < 2) {
|
||||
return (
|
||||
<Panel title="Cohorts">
|
||||
<EmptyNote>Need at least two models with usage in this range to compare.</EmptyNote>
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
|
||||
const modelRows = facets.data.models
|
||||
const nudgeDistinct = (chosen: string) => modelRows.find(model => model.model !== chosen)?.model ?? null
|
||||
const intervalLabel = range ? `${range.from} → ${range.to}` : (report.data?.period.label ?? period)
|
||||
|
||||
return (
|
||||
<>
|
||||
{facets.switching && <SwitchingBanner />}
|
||||
<div className="cmp-picker" aria-label="Cohort selection">
|
||||
<Dropdown
|
||||
id="cohort-first-model"
|
||||
ariaLabel="Cohort first model"
|
||||
value={modelA ?? ''}
|
||||
options={modelRows.map(model => ({ value: model.model, label: `${model.model} · ${model.calls.toLocaleString()} calls` }))}
|
||||
onChange={next => {
|
||||
setModelA(next)
|
||||
if (next === modelB) setModelB(nudgeDistinct(next))
|
||||
}}
|
||||
/>
|
||||
<span className="cmp-vs">vs</span>
|
||||
<Dropdown
|
||||
id="cohort-second-model"
|
||||
ariaLabel="Cohort second model"
|
||||
value={modelB ?? ''}
|
||||
options={modelRows.map(model => ({ value: model.model, label: `${model.model} · ${model.calls.toLocaleString()} calls` }))}
|
||||
onChange={next => {
|
||||
setModelB(next)
|
||||
if (next === modelA) setModelA(nudgeDistinct(next))
|
||||
}}
|
||||
/>
|
||||
<Dropdown
|
||||
id="cohort-project"
|
||||
ariaLabel="Cohort project"
|
||||
value={project}
|
||||
options={[{ value: '', label: 'All projects' }, ...facets.data.projects.map(p => ({ value: p.id, label: shortenProjectPath(p.id) }))]}
|
||||
onChange={setProject}
|
||||
/>
|
||||
<Dropdown
|
||||
id="cohort-category"
|
||||
ariaLabel="Cohort activity category"
|
||||
value={category}
|
||||
options={[{ value: '', label: 'All categories' }, ...facets.data.categories.map(c => ({ value: c.id, label: c.label }))]}
|
||||
onChange={setCategory}
|
||||
/>
|
||||
</div>
|
||||
<p className="cmp-range-note" role="status">
|
||||
Cohort interval: {intervalLabel}. One observation = one edit turn driven by exactly one
|
||||
behavioral model; turns mixing models are excluded and counted below.
|
||||
</p>
|
||||
{modelA && modelB && modelA !== modelB && (
|
||||
<CohortReport report={report} onInvestigate={onInvestigate} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function CohortReport({ report, onInvestigate }: {
|
||||
report: ReturnType<typeof usePolled<CohortComparisonReport>>
|
||||
onInvestigate?: (request: InvestigateRequest) => void
|
||||
}) {
|
||||
const [band, setBand] = useState<VolumeBand | null>(null)
|
||||
|
||||
if (!report.data) {
|
||||
if (report.error) return <CliErrorPanel error={report.error} subject="model comparisons" />
|
||||
return <SectionSkeleton label="Comparing cohorts…" rows={4} />
|
||||
}
|
||||
|
||||
const data = report.data
|
||||
// Volume bands recompute from the report's own declared population — instant,
|
||||
// deterministic, and reproducible from the sample lists.
|
||||
const sideA = cohortSide(data.modelA, band)
|
||||
const sideB = cohortSide(data.modelB, band)
|
||||
|
||||
return (
|
||||
<div className="cmp-body">
|
||||
<PopulationCard data={data} sideA={sideA} sideB={sideB} band={band} onBandChange={setBand} />
|
||||
<div className="cmp-pair">
|
||||
<CohortModelCard side={sideA} />
|
||||
<CohortModelCard side={sideB} />
|
||||
</div>
|
||||
<div className="cmp-pair">
|
||||
<VolumeCard title="Token volume (median · P90)" side={sideA} />
|
||||
<VolumeCard title="Token volume (median · P90)" side={sideB} />
|
||||
</div>
|
||||
<div className="cmp-pair">
|
||||
<SampleInspector side={sideA} onInvestigate={onInvestigate} />
|
||||
<SampleInspector side={sideB} onInvestigate={onInvestigate} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function cohortSide(model: CohortModelReport, band: VolumeBand | null) {
|
||||
const filtered = applyVolumeBand(model.observations, band)
|
||||
const stats = band ? computeBandCohortStats(model.model, filtered.kept) : model.stats
|
||||
return {
|
||||
model,
|
||||
band,
|
||||
kept: filtered.kept,
|
||||
excludedOutsideBand: filtered.outsideBand,
|
||||
excludedMissingMeasure: filtered.missingMeasure,
|
||||
stats,
|
||||
}
|
||||
}
|
||||
|
||||
type CohortSide = ReturnType<typeof cohortSide>
|
||||
|
||||
function PopulationCard({ data, sideA, sideB, band, onBandChange }: {
|
||||
data: CohortComparisonReport
|
||||
sideA: CohortSide
|
||||
sideB: CohortSide
|
||||
band: VolumeBand | null
|
||||
onBandChange: (band: VolumeBand | null) => void
|
||||
}) {
|
||||
const bandExcludedTotal = sideA.excludedOutsideBand + sideB.excludedOutsideBand
|
||||
const missingMeasureTotal = sideA.excludedMissingMeasure + sideB.excludedMissingMeasure
|
||||
return (
|
||||
<div className="panel cmp-card">
|
||||
<div className="cmp-head">
|
||||
<h3>Population</h3>
|
||||
<span className="cmp-head-note">Who is being compared, before any metric</span>
|
||||
</div>
|
||||
<div className="cmp-metrics">
|
||||
<div className="cmp-metric-head"><span>Selection</span><span>{data.modelA.label}</span><span>{data.modelB.label}</span></div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label">Observations (edit turns, one model)</span>
|
||||
<span className="cmp-value">{sideA.stats.observationCount.toLocaleString()}</span>
|
||||
<span className="cmp-value">{sideB.stats.observationCount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label">Distinct sessions they come from</span>
|
||||
<span className="cmp-value">{sideA.stats.distinctSessionCount.toLocaleString()}</span>
|
||||
<span className="cmp-value">{sideB.stats.distinctSessionCount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label" title="Edit turns whose behavioral calls span 2+ models: attributed to nobody, cost shown so you can see what stays out">Excluded turns mixing models</span>
|
||||
<span className="cmp-value">{data.modelA.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelA.exclusions.combinedMultiModelCostUSD)})</span>
|
||||
<span className="cmp-value">{data.modelB.exclusions.multiModelTurnCount.toLocaleString()} ({formatUsd(data.modelB.exclusions.combinedMultiModelCostUSD)})</span>
|
||||
</div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label" title="Edit turns with no behavioral model call — no model can own them">Excluded turns without a model</span>
|
||||
<span className="cmp-value">{data.modelA.exclusions.noBehavioralModelTurns.toLocaleString()}</span>
|
||||
<span className="cmp-value">{data.modelB.exclusions.noBehavioralModelTurns.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label" title="Observations priced at $0 on a model without a free-rate rule: unknown cost, kept for retry stats, kept out of cost stats">Unknown cost (not zero)</span>
|
||||
<span className="cmp-value">{sideA.stats.unknownCostCount.toLocaleString()}</span>
|
||||
<span className="cmp-value">{sideB.stats.unknownCostCount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label">Projects / category in selection</span>
|
||||
<span className="cmp-value cmp-value-wide">{describeSelection(data)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<VolumeBandFilter band={band} onChange={onBandChange} />
|
||||
{(bandExcludedTotal > 0 || missingMeasureTotal > 0) && (
|
||||
<div className="cmp-foot" role="status">
|
||||
Volume band excludes {bandExcludedTotal.toLocaleString()} observation(s) outside the band
|
||||
{missingMeasureTotal > 0 ? ` and ${missingMeasureTotal.toLocaleString()} without any token measure (never counted as small)` : ''}.
|
||||
Rates below use the remaining declared population.
|
||||
</div>
|
||||
)}
|
||||
<div className="cmp-foot">
|
||||
Context proxy = input + cache-read tokens (a proxy, not a measured context window).
|
||||
Percentiles use linear interpolation at position (N-1)·p. Outliers are never removed;
|
||||
no winner is picked — this is a descriptive comparison.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function describeSelection(data: CohortComparisonReport): string {
|
||||
const projects = data.selection.projects
|
||||
const projectLabel = projects.length === 0
|
||||
? 'all'
|
||||
: projects.length <= 2 ? projects.join(', ') : `${projects.length} projects`
|
||||
const category = data.selection.category ?? 'all categories'
|
||||
const interval = data.selection.from && data.selection.to ? `${data.selection.from} → ${data.selection.to}` : data.period.label
|
||||
return `${projectLabel} · ${category} · ${interval}`
|
||||
}
|
||||
|
||||
function VolumeBandFilter({ band, onChange }: { band: VolumeBand | null; onChange: (band: VolumeBand | null) => void }) {
|
||||
const measure = band?.measure ?? 'output'
|
||||
const min = band?.min?.toString() ?? ''
|
||||
const max = band?.max?.toString() ?? ''
|
||||
|
||||
const push = (next: { measure?: VolumeMeasure; min?: string; max?: string }) => {
|
||||
const nextMeasure = next.measure ?? measure
|
||||
const minRaw = next.min ?? min
|
||||
const maxRaw = next.max ?? max
|
||||
const minNum = minRaw.trim() === '' ? null : Number(minRaw)
|
||||
const maxNum = maxRaw.trim() === '' ? null : Number(maxRaw)
|
||||
const validMin = minNum != null && Number.isFinite(minNum) ? minNum : null
|
||||
const validMax = maxNum != null && Number.isFinite(maxNum) ? maxNum : null
|
||||
if (validMin == null && validMax == null) {
|
||||
onChange(null)
|
||||
return
|
||||
}
|
||||
onChange({ measure: nextMeasure, min: validMin, max: validMax })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="cmp-band" role="group" aria-label="Volume band filter">
|
||||
<span className="cmp-band-label">Volume band</span>
|
||||
<Dropdown
|
||||
id="cohort-band-measure"
|
||||
ariaLabel="Volume band measure"
|
||||
value={measure}
|
||||
options={BAND_MEASURES.map(m => ({ value: m.value, label: m.label }))}
|
||||
onChange={next => push({ measure: next as VolumeMeasure })}
|
||||
/>
|
||||
<input
|
||||
className="cmp-band-input"
|
||||
aria-label="Volume band minimum"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder="min"
|
||||
value={min}
|
||||
onChange={event => push({ min: event.target.value })}
|
||||
/>
|
||||
<span className="cmp-band-sep">–</span>
|
||||
<input
|
||||
className="cmp-band-input"
|
||||
aria-label="Volume band maximum"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder="max"
|
||||
value={max}
|
||||
onChange={event => push({ max: event.target.value })}
|
||||
/>
|
||||
{band && (
|
||||
<button type="button" className="cmp-band-clear" onClick={() => onChange(null)}>Clear band</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CohortModelCard({ side }: { side: CohortSide }) {
|
||||
const stats = side.stats
|
||||
const histogram = stats.costHistogram
|
||||
const maxCount = Math.max(1, ...histogram.counts)
|
||||
return (
|
||||
<div className="panel cmp-card">
|
||||
<div className="cmp-head"><h3>Cost per edit turn</h3><span className="cmp-head-note">{side.model.label}</span></div>
|
||||
<div className="cmp-metrics">
|
||||
<div className="cmp-metric"><span className="cmp-label">Median cost</span><span className="cmp-value">{fmtCost(stats.costMedian)}</span></div>
|
||||
<div className="cmp-metric"><span className="cmp-label">P90 cost</span><span className="cmp-value">{fmtCost(stats.costP90)}</span></div>
|
||||
<div className="cmp-metric"><span className="cmp-label">Mean cost</span><span className="cmp-value">{fmtCost(stats.costMean)}</span></div>
|
||||
<div className="cmp-metric"><span className="cmp-label" title="One-shot = the edit turn produced no observed retry. Zero observed retries never proves code correctness.">One-shot rate</span><span className="cmp-value">{fmtMetric(stats.oneShotRate, 'percent')} <span className="cmp-turns">({stats.oneShotCount}/{stats.observationCount})</span></span></div>
|
||||
<div className="cmp-metric"><span className="cmp-label" title="Observed retries per edit turn. Absence of observed retries does not prove correctness.">Retry rate</span><span className="cmp-value">{fmtMetric(stats.retryRate, 'decimal')} <span className="cmp-turns">({stats.retryCount})</span></span></div>
|
||||
<div className="cmp-metric"><span className="cmp-label">Cost known for</span><span className="cmp-value">{stats.costKnownCount}/{stats.observationCount} observations</span></div>
|
||||
</div>
|
||||
<div className="cmp-histogram" role="img" aria-label={`Cost distribution for ${side.model.label}`}>
|
||||
{histogram.edges.length === 0 && histogram.counts.length === 1 ? (
|
||||
<div className="cmp-hist-note">All known costs ≈ $0 (free models).</div>
|
||||
) : (
|
||||
histogram.counts.map((count, index) => (
|
||||
<div className="cmp-hist-row" key={index}>
|
||||
<span className="cmp-hist-label">{bucketLabel(histogram.edges, index)}</span>
|
||||
<span className="cmp-track"><span className="cmp-bar" style={{ width: `${(count / maxCount) * 100}%` }} /></span>
|
||||
<span className="cmp-hist-count">{count.toLocaleString()}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fmtCost(value: number | null): string {
|
||||
return value === null ? '—' : formatUsd(value)
|
||||
}
|
||||
|
||||
function bucketLabel(edges: number[], index: number): string {
|
||||
if (edges.length === 0) return '$0'
|
||||
if (index === 0) return `< ${formatUsd(edges[0] as number)}`
|
||||
if (index === edges.length) return `≥ ${formatUsd(edges[edges.length - 1] as number)}`
|
||||
return `${formatUsd(edges[index - 1] as number)}–${formatUsd(edges[index] as number)}`
|
||||
}
|
||||
|
||||
function VolumeCard({ title, side }: { title: string; side: CohortSide }) {
|
||||
const volume = side.stats.volume
|
||||
const rows = [
|
||||
['Output tokens', fmtVolume(volume.outputMedian), fmtVolume(volume.outputP90)],
|
||||
['Input tokens', fmtVolume(volume.inputMedian), fmtVolume(volume.inputP90)],
|
||||
['Context proxy (in + cache read)', fmtVolume(volume.contextProxyMedian), fmtVolume(volume.contextProxyP90)],
|
||||
]
|
||||
return (
|
||||
<div className="panel cmp-card">
|
||||
<div className="cmp-head"><h3>{title}</h3><span className="cmp-head-note">{side.model.label}</span></div>
|
||||
<div className="cmp-metrics">
|
||||
<div className="cmp-metric-head"><span>Volume</span><span>Median</span><span>P90</span></div>
|
||||
{rows.map(([label, median, p90]) => (
|
||||
<div className="cmp-metric" key={label}>
|
||||
<span className="cmp-label" title={label.startsWith('Context') ? 'input + cache-read tokens: a proxy for context size, not a measured context window' : undefined}>{label}</span>
|
||||
<span className="cmp-value">{median}</span>
|
||||
<span className="cmp-value">{p90}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="cmp-metric">
|
||||
<span className="cmp-label">Observations without token data</span>
|
||||
<span className="cmp-value" >{volume.missingMeasureCount.toLocaleString()}</span>
|
||||
<span className="cmp-value" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fmtVolume(value: number | null): string {
|
||||
return value === null ? '—' : formatCompact(value)
|
||||
}
|
||||
|
||||
/** Inspect samples: the declared population, inspectable row by row. Activating
|
||||
* a row drills through to the owning session with the shared investigation
|
||||
* navigation, keyed by the same provider/project/session triple Sessions uses. */
|
||||
function SampleInspector({ side, onInvestigate }: {
|
||||
side: CohortSide
|
||||
onInvestigate?: (request: InvestigateRequest) => void
|
||||
}) {
|
||||
const [showAll, setShowAll] = useState(false)
|
||||
const observations = useMemo(
|
||||
() => [...side.kept].sort((a, b) => b.costUSD - a.costUSD || a.timestamp.localeCompare(b.timestamp)),
|
||||
[side.kept],
|
||||
)
|
||||
const visible = showAll ? observations : observations.slice(0, SAMPLES_INITIAL_COUNT)
|
||||
|
||||
return (
|
||||
<div className="panel cmp-card">
|
||||
<div className="cmp-head">
|
||||
<h3>Inspect samples</h3>
|
||||
<span className="cmp-head-note">{side.model.label} · {side.stats.observationCount.toLocaleString()} of {side.model.stats.observationCount.toLocaleString()} in selection</span>
|
||||
</div>
|
||||
{observations.length === 0 ? (
|
||||
<div className="cmp-category-body">
|
||||
<EmptyNote>No observations match the current selection{side.band ? ' and volume band' : ''}. Nothing is compared.</EmptyNote>
|
||||
</div>
|
||||
) : (
|
||||
<div className="cmp-samples">
|
||||
{visible.map((observation, index) => (
|
||||
<SampleRow key={`${observation.sessionId}-${observation.timestamp}-${index}`} observation={observation} onInvestigate={onInvestigate} />
|
||||
))}
|
||||
{observations.length > SAMPLES_INITIAL_COUNT && (
|
||||
<button type="button" className="cmp-samples-more" onClick={() => setShowAll(current => !current)}>
|
||||
{showAll ? 'Show fewer' : `Show all ${observations.length.toLocaleString()} observations`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SampleRow({ observation, onInvestigate }: {
|
||||
observation: CohortObservation
|
||||
onInvestigate?: (request: InvestigateRequest) => void
|
||||
}) {
|
||||
const activate = () => {
|
||||
onInvestigate?.({
|
||||
filters: sessionFilters({ provider: observation.provider, sessionId: observation.sessionId }),
|
||||
sessionId: sessionRowKey(observation),
|
||||
})
|
||||
}
|
||||
return (
|
||||
<button type="button" className="cmp-sample" onClick={activate}
|
||||
title={`Open session: ${observation.project}/${observation.sessionId}`}
|
||||
aria-label={`Sample from ${shortenProjectPath(observation.project)} at ${observation.timestamp}`}>
|
||||
<span className="cmp-sample-time">{observation.timestamp.slice(0, 16).replace('T', ' ')}</span>
|
||||
<span className="cmp-sample-project" title={observation.project}>{shortenProjectPath(observation.project)}</span>
|
||||
<span className="cmp-sample-session" title={observation.sessionId}>{observation.sessionId.slice(0, 10)}</span>
|
||||
<span className="cmp-sample-cat">{observation.category}</span>
|
||||
<span className="cmp-sample-cost" title={observation.costKnown ? undefined : 'Unknown cost: this model has no pricing and no free-rate rule — not counted as $0'}>
|
||||
{observation.costKnown ? formatUsd(observation.costUSD) : 'unknown'}
|
||||
</span>
|
||||
<span className="cmp-sample-tokens" title="input / output / context proxy tokens">
|
||||
{observation.tokensReported ? `${formatCompact(observation.inputTokens)} / ${formatCompact(observation.outputTokens)} / ${formatCompact(observation.contextProxyTokens)}` : 'no token data'}
|
||||
</span>
|
||||
<span className="cmp-sample-retries">{observation.oneShot ? 'one-shot' : `${observation.retries} retry`}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -907,6 +907,28 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
|
|||
.cmp-bar-value { color: var(--mut); font-family: var(--mono); font-size: 10.5px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.cmp-turns { color: var(--mut2); }
|
||||
|
||||
/* Compare · Cohorts mode */
|
||||
.cmp-value-wide { overflow: hidden; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cmp-band { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px 14px; border-top: 1px solid var(--line2); }
|
||||
.cmp-band-label { color: var(--mut); font-size: 11px; font-weight: 600; }
|
||||
.cmp-band .dropdown { max-width: 250px; }
|
||||
.cmp-band .dropdown-trigger { min-height: 27px; padding: 4px 9px; font-size: 11px; }
|
||||
.cmp-band-input { width: 90px; min-height: 27px; padding: 4px 8px; border: 1px solid var(--line2); border-radius: 6px; background: var(--fill); color: var(--ink); font-family: var(--mono); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.cmp-band-sep { color: var(--mut2); }
|
||||
.cmp-band-clear { border: 0; background: none; color: var(--accent); font-size: 11px; cursor: pointer; padding: 2px 4px; }
|
||||
.cmp-histogram { display: flex; flex-direction: column; gap: 4px; padding: 10px 14px 12px; border-top: 1px solid var(--line2); }
|
||||
.cmp-hist-row { display: grid; grid-template-columns: 110px minmax(0, 1fr) 44px; align-items: center; gap: 8px; }
|
||||
.cmp-hist-label { overflow: hidden; color: var(--mut2); font-family: var(--mono); font-size: 9.5px; font-variant-numeric: tabular-nums; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cmp-hist-count { color: var(--mut); font-family: var(--mono); font-size: 10px; font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.cmp-hist-note { color: var(--mut2); font-size: 10.5px; }
|
||||
.cmp-samples { display: flex; flex-direction: column; max-height: 320px; overflow-y: auto; }
|
||||
.cmp-sample { display: grid; grid-template-columns: 104px minmax(70px, 1fr) 84px 74px 70px minmax(120px, 1.3fr) 70px; align-items: center; column-gap: 8px; width: 100%; padding: 6px 14px; border: 0; border-bottom: 1px solid var(--line2); background: none; color: var(--mut); font-family: var(--mono); font-size: 10px; font-variant-numeric: tabular-nums; text-align: left; cursor: pointer; }
|
||||
.cmp-sample:hover { background: var(--fill); }
|
||||
.cmp-sample-project, .cmp-sample-session, .cmp-sample-cat { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cmp-sample-cost, .cmp-sample-tokens, .cmp-sample-retries { text-align: right; white-space: nowrap; }
|
||||
.cmp-sample-time { color: var(--mut2); }
|
||||
.cmp-samples-more { border: 0; background: none; color: var(--accent); font-size: 11px; cursor: pointer; padding: 8px 14px; text-align: left; }
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.spend-top-row { grid-template-columns: 1fr; }
|
||||
.spend-breakdowns { grid-template-columns: 1fr; }
|
||||
|
|
@ -918,8 +940,11 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
|
|||
.sessions-toolbar, .sessions-search { width: 100%; }
|
||||
.sessions-search { min-width: 0; }
|
||||
.cmp-picker { gap: 5px; }
|
||||
.cmp-picker .dropdown { max-width: 46vw; }
|
||||
.cmp-category { grid-template-columns: 70px minmax(0, 1fr); }
|
||||
.cmp-bar-row { grid-template-columns: minmax(0, 1fr) 76px; }
|
||||
.cmp-sample { grid-template-columns: 90px minmax(60px, 1fr) 70px 60px minmax(100px, 1fr) 60px; }
|
||||
.cmp-sample-cat { display: none; }
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
|
|
|
|||
97
docs/compare-cohorts.md
Normal file
97
docs/compare-cohorts.md
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
# Cohort model comparison (Compare → Cohorts)
|
||||
|
||||
The classic Compare view answers "how do these two models differ across my whole
|
||||
history?" by aggregating everything each model ever did. The **Cohorts** mode —
|
||||
new in this change — answers a narrower question: **how do the two models behave
|
||||
on the same kind of work, over a population you can inspect?**
|
||||
|
||||
## What an observation is (V1 definition)
|
||||
|
||||
* An observation is one **edit turn** (a turn that edited files) whose
|
||||
**behavioral calls** carry **exactly one model**. That model owns the
|
||||
observation. "Behavioral call" is CodeBurn's existing definition
|
||||
(`src/behavioral-weight.ts`): real requests, excluding supplementary
|
||||
accounting rows.
|
||||
* The **cost attributed to the model** is the recorded cost of *that model's own
|
||||
calls inside the turn*. A session that used several models never transfers the
|
||||
cost of one model to another, and no session total is attributed to a
|
||||
"dominant" model.
|
||||
Supplementary accounting for that model remains part of its cost and token
|
||||
totals, without adding observations or changing behavioral ownership.
|
||||
* Edit turns whose behavioral calls span **two or more models** are excluded
|
||||
from both cohorts, counted, and shown with their combined cost. This is the
|
||||
one place cohort counts diverge from `compare --format json`, which owns a
|
||||
turn by its *first* behavioral call (`primaryTurnModel`, `src/compare-stats.ts`)
|
||||
and so still counts a mixed turn for that first model. Cohort observations
|
||||
therefore equal a model's `editTurns` except for mixed turns it led.
|
||||
* An edit turn with no behavioral model call at all is excluded the same way.
|
||||
* A `$0` cost on a model the pricing rules do not declare free (local models,
|
||||
subscription SKUs, explicit zero-rate overrides) is **unknown cost, not zero**:
|
||||
such observations keep their retry/one-shot weight (which needs no pricing)
|
||||
and are counted separately, but stay out of cost percentiles.
|
||||
|
||||
The classic mode's formulas are untouched; both modes remain available.
|
||||
|
||||
## What the mode shows
|
||||
|
||||
In order, before any metric:
|
||||
|
||||
1. **Population** — included observations per model, the distinct sessions they
|
||||
come from, excluded turns that mix models (with their combined cost),
|
||||
excluded turns without a behavioral model, and the unknown-cost count.
|
||||
2. **Inspect samples** — the declared population itself, one row per
|
||||
observation (timestamp, project, session, category, cost, input / output /
|
||||
context-proxy tokens, retries). Every number on the page is reproducible
|
||||
from this list. Activating a row drills through to the owning session with
|
||||
the shared investigation navigation, keyed by the same provider/project/
|
||||
session triple the sessions report uses.
|
||||
3. **Cost per edit turn** — median, P90, mean over cost-known observations, the
|
||||
one-shot rate and retry rate over the declared population (zero *observed*
|
||||
retries never proves code correctness), and a compact cost histogram whose
|
||||
top bucket is open-ended so outliers are never dropped.
|
||||
4. **Token volume** — median/P90 of output, input, and the **context proxy**
|
||||
(input + cache-read tokens — a proxy, never presented as a measured context
|
||||
window).
|
||||
|
||||
## Selection and the volume band
|
||||
|
||||
The selection covers model A, model B, the interval (a custom date range when
|
||||
one is active, otherwise the selected period), one project, and one activity
|
||||
category. On the CLI the same selection exists as:
|
||||
|
||||
```bash
|
||||
codeburn compare --format cohort-json # facets: models, projects, categories
|
||||
codeburn compare --format cohort-json \
|
||||
--model-a <model> --model-b <model> \
|
||||
[--period 30days | --from 2026-08-01 --to 2026-08-31] \
|
||||
[--project <name|path>]... [--exclude <name|path>]... \
|
||||
[--category coding]
|
||||
```
|
||||
|
||||
The desktop project picker uses the facet's canonical `id` and passes it as
|
||||
`--project-id=<id>` (repeatable, `cohort-json` only). This selects exactly one
|
||||
identity, so selecting `/work/app` cannot also include `/work/app-backend`.
|
||||
The CLI's existing `--project` option continues to accept loose name patterns.
|
||||
|
||||
The **volume band** narrows the population to observations inside a token range
|
||||
(output, input, or the context proxy). A band explicitly excludes — and counts —
|
||||
observations that fall outside it **and** observations that carry no token
|
||||
measure at all (missing data is never read as "small"). Rates are recomputed
|
||||
over the remaining declared population.
|
||||
|
||||
## Fixed conventions
|
||||
|
||||
* Percentiles use **linear interpolation at position (N-1)·p** — for costs
|
||||
[1, 2, 4, 8] the median is 3 and P90 is 6.8. Pinned by tests on both the core
|
||||
(`tests/compare-cohorts.test.ts`) and the renderer mirror
|
||||
(`app/renderer/lib/cohortStats.test.ts`).
|
||||
* No outlier removal, no sample equalizing, no automatic winner: the mode is a
|
||||
descriptive comparison of your own history. N and variation are always shown.
|
||||
|
||||
## Population-first contract
|
||||
|
||||
The `cohort-json` payload embeds the full observation list per model, so any
|
||||
statistic is reproducible from the payload (and from the Inspect samples list)
|
||||
without re-running anything. Volume-band math runs in the renderer over that
|
||||
list (`app/renderer/lib/cohortStats.ts`, a mirror of the core math with the same
|
||||
pinned convention) so band changes are instant.
|
||||
455
src/compare-cohorts.ts
Normal file
455
src/compare-cohorts.ts
Normal file
|
|
@ -0,0 +1,455 @@
|
|||
// Cohort model comparison: compare two models over EXPLICIT groups of similar
|
||||
// work — an explicit, inspectable population of edit-turn observations the user
|
||||
// can reproduce, not the classic whole-history aggregate.
|
||||
//
|
||||
// V1 OBSERVATION DEFINITION (normative, mirrored in docs/compare-cohorts.md):
|
||||
// * An observation is one EDIT turn (`turn.hasEdits`) whose behavioral calls
|
||||
// (`isBehavioralCall`, src/behavioral-weight.ts) carry EXACTLY ONE distinct
|
||||
// model. That model owns the observation.
|
||||
// * The cost attributed to the model is the RECORDED cost of that model's own
|
||||
// calls inside the turn (`costUSD` summed over the turn's calls of that
|
||||
// model only). Costs of any other model in the turn are never transferred,
|
||||
// and the session's total cost is never attributed to a dominant model.
|
||||
// * Edit turns whose behavioral calls span 2+ distinct models are EXCLUDED
|
||||
// from both cohorts, counted, and shown with their combined cost.
|
||||
// * An edit turn with zero behavioral calls is excluded the same way (no
|
||||
// model can own it).
|
||||
// * `costUSD === 0` on a model the existing pricing rules do not declare free
|
||||
// (`isExpectedFreeModel`, src/models.ts) is UNKNOWN cost, not zero: such
|
||||
// observations keep their retry/one-shot weight (which needs no pricing)
|
||||
// and are counted separately, excluded only from cost statistics.
|
||||
// The classic compare formulas (src/compare-stats.ts) are untouched.
|
||||
|
||||
import type { ClassifiedTurn, ProjectSummary, TaskCategory } from './types.js'
|
||||
import { CATEGORY_LABELS } from './types.js'
|
||||
import { isBehavioralCall } from './behavioral-weight.js'
|
||||
import { callBillableOutputTokens, inferSessionProvider } from './session-output.js'
|
||||
import { getShortModelName, isExpectedFreeModel } from './models.js'
|
||||
import { aggregateModelStats, findModelStat, type ModelStats } from './compare-stats.js'
|
||||
import { spendProjectIdentity } from './spend-flow.js'
|
||||
|
||||
// The CLI's cohort branch resolves these through this one dynamic import; both
|
||||
// are the classic module's own implementations (single identity source).
|
||||
export { aggregateModelStats, findModelStat }
|
||||
|
||||
const SYNTHETIC = '<synthetic>'
|
||||
|
||||
/// Cost per behavioral model id inside one turn. `<synthetic>` is filtered: it
|
||||
/// is accounting text, never a served model.
|
||||
function behavioralCostByModel(turn: ClassifiedTurn): Map<string, number> {
|
||||
const byModel = new Map<string, number>()
|
||||
for (const call of turn.assistantCalls) {
|
||||
if (!isBehavioralCall(call)) continue
|
||||
if (call.model === SYNTHETIC) continue
|
||||
byModel.set(call.model, (byModel.get(call.model) ?? 0) + call.costUSD)
|
||||
}
|
||||
return byModel
|
||||
}
|
||||
|
||||
export type CohortObservation = {
|
||||
/** Owning session id. Not globally unique by itself: pair with `provider` and
|
||||
* `project` for identity, per the app's canonical-identity rules. */
|
||||
sessionId: string
|
||||
/** Same provider/project/session triple the sessions report keys rows by, so
|
||||
* drill-through resolves an observation to exactly one session row. */
|
||||
provider: string
|
||||
project: string
|
||||
timestamp: string
|
||||
category: TaskCategory
|
||||
/** The single behavioral model of the turn (canonical id). */
|
||||
model: string
|
||||
/** Recorded cost of the owning model's calls in this turn. */
|
||||
costUSD: number
|
||||
/** False when costUSD is 0 on a model the pricing rules do not declare free
|
||||
* — a pricing gap, never reported as a $0 observation. */
|
||||
costKnown: boolean
|
||||
retries: number
|
||||
oneShot: boolean
|
||||
/** Token volumes summed over the owning model's calls in the turn. */
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
/** inputTokens + cacheReadTokens. An explicit PROXY for context size, not a
|
||||
* measured context window; every UI label must say so. */
|
||||
contextProxyTokens: number
|
||||
/** False when the owning model's calls in the turn report no tokens at all.
|
||||
* Volume bands must exclude and count these, never read them as small. */
|
||||
tokensReported: boolean
|
||||
}
|
||||
|
||||
export type ExcludedMultiModelTurn = {
|
||||
sessionId: string
|
||||
project: string
|
||||
timestamp: string
|
||||
category: TaskCategory
|
||||
/** Canonical model ids of the turn's behavioral calls (2+). */
|
||||
models: string[]
|
||||
/** Combined recorded cost of all behavioral calls in the turn. Shown so the
|
||||
* user can see what the V1 rule keeps out; attributed to NO cohort. */
|
||||
costUSD: number
|
||||
}
|
||||
|
||||
export type CohortExclusions = {
|
||||
/** Edit turns in the selection with 2+ distinct behavioral models. */
|
||||
multiModelTurns: ExcludedMultiModelTurn[]
|
||||
/** Edit turns in the selection whose behavioral calls carry no model. */
|
||||
noBehavioralModelTurns: number
|
||||
combinedMultiModelCostUSD: number
|
||||
}
|
||||
|
||||
export type CohortSelection = {
|
||||
projects: ProjectSummary[]
|
||||
/** Inclusive; undefined = every activity category. */
|
||||
category?: TaskCategory
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the selection once and split every edit turn into cohort observations or
|
||||
* exclusions. Both cohorts see the same turn stream, so a mixed session
|
||||
* contributes observations to each of its models and its multi-model turns to
|
||||
* nobody — only to the ONE shared exclusion ledger both reports attach.
|
||||
*/
|
||||
export function extractCohortObservations(
|
||||
selection: CohortSelection,
|
||||
): { perModel: Map<string, CohortObservation[]>; exclusions: CohortExclusions } {
|
||||
const perModel = new Map<string, CohortObservation[]>()
|
||||
const exclusions: CohortExclusions = {
|
||||
multiModelTurns: [],
|
||||
noBehavioralModelTurns: 0,
|
||||
combinedMultiModelCostUSD: 0,
|
||||
}
|
||||
|
||||
const cohortFor = (model: string): CohortObservation[] => {
|
||||
let obs = perModel.get(model)
|
||||
if (!obs) {
|
||||
obs = []
|
||||
perModel.set(model, obs)
|
||||
}
|
||||
return obs
|
||||
}
|
||||
|
||||
for (const project of selection.projects) {
|
||||
for (const session of project.sessions) {
|
||||
for (const turn of session.turns) {
|
||||
if (!turn.hasEdits) continue
|
||||
if (selection.category && turn.category !== selection.category) continue
|
||||
|
||||
const byModel = behavioralCostByModel(turn)
|
||||
|
||||
if (byModel.size === 0) {
|
||||
// Shared ledger: no behavioral model owns this edit turn.
|
||||
exclusions.noBehavioralModelTurns++
|
||||
continue
|
||||
}
|
||||
if (byModel.size > 1) {
|
||||
const models = [...byModel.keys()].sort()
|
||||
const cost = [...byModel.values()].reduce((sum, c) => sum + c, 0)
|
||||
exclusions.multiModelTurns.push({
|
||||
sessionId: session.sessionId,
|
||||
project: session.project || project.project,
|
||||
timestamp: turn.timestamp,
|
||||
category: turn.category,
|
||||
models,
|
||||
costUSD: cost,
|
||||
})
|
||||
exclusions.combinedMultiModelCostUSD += cost
|
||||
continue
|
||||
}
|
||||
|
||||
const model = byModel.keys().next().value as string
|
||||
let cost = 0
|
||||
let inputTokens = 0
|
||||
let outputTokens = 0
|
||||
let cacheReadTokens = 0
|
||||
let cacheWriteTokens = 0
|
||||
let tokensReported = false
|
||||
for (const call of turn.assistantCalls) {
|
||||
// Supplementary accounting is weightless for requests, but retains
|
||||
// real cost and tokens attributable to this observation's model.
|
||||
if (call.model !== model) continue
|
||||
cost += call.costUSD
|
||||
const callInput = call.usage.inputTokens
|
||||
const callOutput = call.usage.outputTokens
|
||||
const callCacheRead = call.usage.cacheReadInputTokens
|
||||
const callCacheWrite = call.usage.cacheCreationInputTokens
|
||||
inputTokens += callInput
|
||||
outputTokens += callBillableOutputTokens(call)
|
||||
cacheReadTokens += callCacheRead
|
||||
cacheWriteTokens += callCacheWrite
|
||||
if (callInput > 0 || callOutput > 0 || callCacheRead > 0 || callCacheWrite > 0) tokensReported = true
|
||||
}
|
||||
|
||||
// Unknown ≠ zero: reuse the app's own pricing-gap rules (models.ts).
|
||||
const costKnown = cost > 0 || isExpectedFreeModel(model)
|
||||
|
||||
const acc = cohortFor(model)
|
||||
acc.push({
|
||||
sessionId: session.sessionId,
|
||||
provider: inferSessionProvider(session),
|
||||
project: session.project || project.project,
|
||||
timestamp: turn.timestamp,
|
||||
category: turn.category,
|
||||
model,
|
||||
costUSD: cost,
|
||||
costKnown,
|
||||
retries: turn.retries,
|
||||
oneShot: turn.retries === 0,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheReadTokens,
|
||||
cacheWriteTokens,
|
||||
contextProxyTokens: inputTokens + cacheReadTokens,
|
||||
tokensReported,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { perModel, exclusions }
|
||||
}
|
||||
|
||||
/// Percentile convention FIXED for this feature (pinned in tests on both the
|
||||
/// core and the renderer mirror): sort ascending, position (N-1)*p, linear
|
||||
/// interpolation between neighbors. [1, 2, 4, 8] → median 3, P90 6.8.
|
||||
export function linearPercentile(sorted: readonly number[], p: number): number | null {
|
||||
if (sorted.length === 0) return null
|
||||
if (sorted.length === 1) return sorted[0] as number
|
||||
const pos = (sorted.length - 1) * p
|
||||
const lower = Math.floor(pos)
|
||||
const upper = Math.ceil(pos)
|
||||
if (lower === upper) return sorted[lower] as number
|
||||
const fraction = pos - lower
|
||||
return (sorted[lower] as number) * (1 - fraction) + (sorted[upper] as number) * fraction
|
||||
}
|
||||
|
||||
export function medianOf(sorted: readonly number[]): number | null {
|
||||
return linearPercentile(sorted, 0.5)
|
||||
}
|
||||
|
||||
export type CostHistogram = {
|
||||
/// Half-open buckets [edge[i], edge[i+1]) over the KNOWN costs. The LAST
|
||||
/// bucket is open-ended: outliers are never dropped, they land there and stay
|
||||
/// in every percentile. Empty edges means "everything is $0 (free models)".
|
||||
edges: number[]
|
||||
counts: number[]
|
||||
}
|
||||
|
||||
const HISTOGRAM_BUCKETS = 8
|
||||
|
||||
/** Deterministic linear edges from 0 to the 95th percentile of the known
|
||||
* costs; the top bucket is open-ended so outliers stretch nothing. */
|
||||
export function costHistogram(costs: readonly number[]): CostHistogram {
|
||||
if (costs.length === 0) return { edges: [], counts: [] }
|
||||
const sorted = [...costs].sort((a, b) => a - b)
|
||||
const p95 = linearPercentile(sorted, 0.95) ?? 0
|
||||
const top = p95 > 0 ? p95 : 0
|
||||
if (top <= 0) return { edges: [], counts: [costs.length] }
|
||||
const edges: number[] = []
|
||||
for (let i = 1; i < HISTOGRAM_BUCKETS; i++) edges.push((top * i) / HISTOGRAM_BUCKETS)
|
||||
const counts = new Array(HISTOGRAM_BUCKETS).fill(0)
|
||||
for (const cost of costs) {
|
||||
let bucket = 0
|
||||
while (bucket < edges.length && cost >= (edges[bucket] as number)) bucket++
|
||||
counts[bucket]++
|
||||
}
|
||||
return { edges, counts }
|
||||
}
|
||||
|
||||
export type CohortVolumeStats = {
|
||||
outputMedian: number | null
|
||||
outputP90: number | null
|
||||
inputMedian: number | null
|
||||
inputP90: number | null
|
||||
contextProxyMedian: number | null
|
||||
contextProxyP90: number | null
|
||||
/** Observations with no token measure at all: visible, never read as small. */
|
||||
missingMeasureCount: number
|
||||
}
|
||||
|
||||
export type CohortStats = {
|
||||
model: string
|
||||
label: string
|
||||
/** Declared population: observations after the selection filters (and after a
|
||||
* volume band when one is active). Every rate below uses THIS denominator. */
|
||||
observationCount: number
|
||||
distinctSessionCount: number
|
||||
/** Retry / one-shot over the declared population (classic meaning: observed
|
||||
* retries only; zero observed retries never proves code correctness). */
|
||||
retryCount: number
|
||||
retryRate: number | null
|
||||
oneShotCount: number
|
||||
oneShotRate: number | null
|
||||
/** Cost statistics over cost-KNOWN observations only. */
|
||||
costKnownCount: number
|
||||
unknownCostCount: number
|
||||
costMedian: number | null
|
||||
costP90: number | null
|
||||
costMean: number | null
|
||||
costHistogram: CostHistogram
|
||||
volume: CohortVolumeStats
|
||||
}
|
||||
|
||||
export function computeCohortStats(model: string, observations: readonly CohortObservation[]): CohortStats {
|
||||
const knownCosts = observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
|
||||
const knownCostSum = knownCosts.reduce((sum, c) => sum + c, 0)
|
||||
const sessionKeys = new Set(observations.map(o => `${o.project}/${o.sessionId}`))
|
||||
const byMeasure = (pick: (o: CohortObservation) => number) =>
|
||||
observations.filter(o => o.tokensReported).map(pick).sort((a, b) => a - b)
|
||||
const outputTokens = byMeasure(o => o.outputTokens)
|
||||
const inputTokens = byMeasure(o => o.inputTokens)
|
||||
const contextProxy = byMeasure(o => o.contextProxyTokens)
|
||||
|
||||
const retryCount = observations.reduce((sum, o) => sum + o.retries, 0)
|
||||
const oneShotCount = observations.filter(o => o.oneShot).length
|
||||
const n = observations.length
|
||||
|
||||
return {
|
||||
model,
|
||||
label: getShortModelName(model),
|
||||
observationCount: n,
|
||||
distinctSessionCount: sessionKeys.size,
|
||||
retryCount,
|
||||
retryRate: n > 0 ? retryCount / n : null,
|
||||
oneShotCount,
|
||||
oneShotRate: n > 0 ? (oneShotCount / n) * 100 : null,
|
||||
costKnownCount: knownCosts.length,
|
||||
unknownCostCount: n - knownCosts.length,
|
||||
costMedian: medianOf(knownCosts),
|
||||
costP90: linearPercentile(knownCosts, 0.9),
|
||||
costMean: knownCosts.length > 0 ? knownCostSum / knownCosts.length : null,
|
||||
costHistogram: costHistogram(knownCosts),
|
||||
volume: {
|
||||
outputMedian: medianOf(outputTokens),
|
||||
outputP90: linearPercentile(outputTokens, 0.9),
|
||||
inputMedian: medianOf(inputTokens),
|
||||
inputP90: linearPercentile(inputTokens, 0.9),
|
||||
contextProxyMedian: medianOf(contextProxy),
|
||||
contextProxyP90: linearPercentile(contextProxy, 0.9),
|
||||
missingMeasureCount: observations.filter(o => !o.tokensReported).length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ————— Report contracts (JSON over the IPC bridge) —————
|
||||
|
||||
export type CohortModelReport = {
|
||||
model: string
|
||||
label: string
|
||||
stats: CohortStats
|
||||
/** The DECLARED population: every observation the stats above were computed
|
||||
* from, so any number in the report is reproducible from this list. */
|
||||
observations: CohortObservation[]
|
||||
/** Exclusions as seen from this cohort (the same shared ledger on both). */
|
||||
exclusions: {
|
||||
multiModelTurnCount: number
|
||||
combinedMultiModelCostUSD: number
|
||||
noBehavioralModelTurns: number
|
||||
}
|
||||
}
|
||||
|
||||
export type CohortComparisonReport = {
|
||||
kind: 'cohort-comparison'
|
||||
period: { label: string; provider: string }
|
||||
selection: { projects: string[]; category: string | null; from: string | null; to: string | null }
|
||||
/** Conventions the UI must surface, not bury. */
|
||||
conventions: {
|
||||
percentile: string
|
||||
contextProxy: string
|
||||
attribution: string
|
||||
}
|
||||
modelA: CohortModelReport
|
||||
modelB: CohortModelReport
|
||||
}
|
||||
|
||||
export type CohortFacets = {
|
||||
kind: 'cohort-facets'
|
||||
/** Models with usage in the population (classic ModelStats shape): one
|
||||
* canonical identity per row (aliases folded), the same list the classic
|
||||
* picker shows, so both Compare modes agree on which models exist. */
|
||||
models: ModelStats[]
|
||||
/** Canonical project identities of the population. */
|
||||
projects: Array<{ id: string; project: string; projectPath: string; sessions: number; costUSD: number }>
|
||||
categories: Array<{ id: TaskCategory; label: string }>
|
||||
}
|
||||
|
||||
export function cohortCategoryOptions(): Array<{ id: TaskCategory; label: string }> {
|
||||
return Object.entries(CATEGORY_LABELS).map(([id, label]) => ({ id: id as TaskCategory, label }))
|
||||
}
|
||||
|
||||
export function buildCohortComparison(
|
||||
projects: ProjectSummary[],
|
||||
modelA: string,
|
||||
modelB: string,
|
||||
label: string,
|
||||
provider: string,
|
||||
selection: { category?: TaskCategory; from?: string | null; to?: string | null } = {},
|
||||
): CohortComparisonReport {
|
||||
const { perModel, exclusions } = extractCohortObservations({ projects, category: selection.category })
|
||||
const sharedExclusions = {
|
||||
multiModelTurnCount: exclusions.multiModelTurns.length,
|
||||
combinedMultiModelCostUSD: exclusions.combinedMultiModelCostUSD,
|
||||
noBehavioralModelTurns: exclusions.noBehavioralModelTurns,
|
||||
}
|
||||
|
||||
const build = (model: string): CohortModelReport => {
|
||||
const observations = perModel.get(model) ?? []
|
||||
return {
|
||||
model,
|
||||
label: getShortModelName(model),
|
||||
stats: computeCohortStats(model, observations),
|
||||
observations,
|
||||
exclusions: sharedExclusions,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'cohort-comparison',
|
||||
period: { label, provider },
|
||||
selection: {
|
||||
projects: [...new Set(projects.map(p => p.project))].sort(),
|
||||
category: selection.category ?? null,
|
||||
from: selection.from ?? null,
|
||||
to: selection.to ?? null,
|
||||
},
|
||||
conventions: {
|
||||
percentile: 'linear interpolation at position (N-1)*p',
|
||||
contextProxy: 'input + cache-read tokens (proxy, not a measured context window)',
|
||||
attribution: 'observation cost = recorded cost of the owning model\'s calls in the turn',
|
||||
},
|
||||
modelA: build(modelA),
|
||||
modelB: build(modelB),
|
||||
}
|
||||
}
|
||||
|
||||
export function buildCohortFacets(projects: ProjectSummary[]): CohortFacets {
|
||||
const projectMap = new Map<string, { id: string; project: string; projectPath: string; sessions: number; costUSD: number }>()
|
||||
for (const p of projects) {
|
||||
const { id } = spendProjectIdentity(p)
|
||||
const existing = projectMap.get(id)
|
||||
if (existing) {
|
||||
existing.sessions += p.sessions.length
|
||||
existing.costUSD += p.totalCostUSD
|
||||
} else {
|
||||
projectMap.set(id, { id, project: p.project, projectPath: p.projectPath, sessions: p.sessions.length, costUSD: p.totalCostUSD })
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: 'cohort-facets',
|
||||
models: aggregateModelStats(projects),
|
||||
projects: [...projectMap.values()].sort((a, b) => b.costUSD - a.costUSD),
|
||||
categories: cohortCategoryOptions(),
|
||||
}
|
||||
}
|
||||
|
||||
/** Desktop selections name exact project identities. Keep the public CLI's
|
||||
* loose --project patterns independent of this explicit selection. */
|
||||
export function selectCohortProjects(projects: ProjectSummary[], ids: readonly string[] = []): ProjectSummary[] {
|
||||
if (ids.length === 0) return projects
|
||||
const selected = new Set(ids)
|
||||
return projects.filter(project => selected.has(spendProjectIdentity(project).id))
|
||||
}
|
||||
|
||||
export function renderCohortJson(report: CohortComparisonReport | CohortFacets): string {
|
||||
return JSON.stringify(report, null, 2)
|
||||
}
|
||||
69
src/main.ts
69
src/main.ts
|
|
@ -451,6 +451,15 @@ function assertFormat(value: string, allowed: readonly string[], command: string
|
|||
}
|
||||
}
|
||||
|
||||
/** Task-category ids (types.ts CATEGORY_LABELS keys), shared with `--task`. */
|
||||
function assertCategory(value: string): void {
|
||||
if (value in CATEGORY_LABELS) return
|
||||
process.stderr.write(
|
||||
`codeburn: unknown category "${value}". Valid values: ${Object.keys(CATEGORY_LABELS).join(', ')}.\n`
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
type AliasRow = { from: string; to: string }
|
||||
|
||||
function toAliasRows(aliases: Record<string, string>): AliasRow[] {
|
||||
|
|
@ -2232,16 +2241,70 @@ program
|
|||
.description('Compare two AI models side-by-side')
|
||||
.option('-p, --period <period>', 'Analysis period: today, week, 30days, month, all, lifetime', 'all')
|
||||
.option('--provider <provider>', 'Filter by provider (e.g. claude, gemini, cursor, copilot)', 'all')
|
||||
.option('--format <format>', 'Output format: tui, json', 'tui')
|
||||
.option('--format <format>', 'Output format: tui, json, cohort-json', 'tui')
|
||||
.option('--model-a <model>', 'First model to compare')
|
||||
.option('--model-b <model>', 'Second model to compare')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.option('--from <date>', 'Custom range start (YYYY-MM-DD)')
|
||||
.option('--to <date>', 'Custom range end (YYYY-MM-DD)')
|
||||
.option('--category <category>', 'cohort-json only: keep edit-turn observations of one activity category')
|
||||
.option('--project-id <id>', 'cohort-json only: exact canonical project identity (repeatable)', collect, [])
|
||||
.action(async (opts) => {
|
||||
assertProvider(opts.provider, 'compare')
|
||||
assertFormat(opts.format, ['tui', 'json'], 'compare')
|
||||
assertFormat(opts.format, ['tui', 'json', 'cohort-json'], 'compare')
|
||||
if (opts.projectId.length > 0 && opts.format !== 'cohort-json') {
|
||||
process.stderr.write('codeburn compare: --project-id requires --format cohort-json.\n')
|
||||
process.exit(1)
|
||||
}
|
||||
await loadPricing()
|
||||
const { range, label } = getDateRange(opts.period)
|
||||
let customRange: DateRange | null = null
|
||||
try {
|
||||
customRange = parseDateRangeFlags(opts.from, opts.to)
|
||||
} catch (err) {
|
||||
console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
const { range, label } = customRange
|
||||
? { range: customRange, label: formatDateRangeLabel(opts.from, opts.to) }
|
||||
: getDateRange(opts.period)
|
||||
if (opts.format === 'cohort-json') {
|
||||
if (opts.category !== undefined) assertCategory(opts.category)
|
||||
const { aggregateModelStats, buildCohortComparison, buildCohortFacets, findModelStat, renderCohortJson, selectCohortProjects } = await import('./compare-cohorts.js')
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(range))
|
||||
const projects = selectCohortProjects(filterProjectsByName(parsed, opts.project, opts.exclude), opts.projectId)
|
||||
|
||||
// Without --model-a/--model-b the cohort format answers the FACET query:
|
||||
// the models, canonical project identities, and activity categories the
|
||||
// desktop cohort pickers are built from (one parse, one contract).
|
||||
if (!opts.modelA && !opts.modelB) {
|
||||
process.stdout.write(renderCohortJson(buildCohortFacets(projects)) + '\n')
|
||||
return
|
||||
}
|
||||
if (!opts.modelA || !opts.modelB) {
|
||||
process.stderr.write('codeburn compare: --model-a and --model-b must be provided together.\n')
|
||||
process.exit(1)
|
||||
}
|
||||
// Resolve against the same period/provider population as the desktop
|
||||
// model picker. A selected project may have zero work for either model.
|
||||
const models = aggregateModelStats(parsed)
|
||||
const modelA = findModelStat(models, opts.modelA)
|
||||
const modelB = findModelStat(models, opts.modelB)
|
||||
if (!modelA) {
|
||||
process.stderr.write(`codeburn compare: model not found: "${opts.modelA}".\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (!modelB) {
|
||||
process.stderr.write(`codeburn compare: model not found: "${opts.modelB}".\n`)
|
||||
process.exit(1)
|
||||
}
|
||||
process.stdout.write(renderCohortJson(buildCohortComparison(
|
||||
projects, modelA.model, modelB.model, label, opts.provider,
|
||||
{ category: opts.category as TaskCategory | undefined, from: opts.from ?? null, to: opts.to ?? null },
|
||||
)) + '\n')
|
||||
return
|
||||
}
|
||||
if (opts.format === 'json') {
|
||||
const { aggregateModelStats, buildCompareJson, findModelStat, projectSessionIds, renderCompareJson, scanSelfCorrections } = await import('./compare-stats.js')
|
||||
const parsed = await parseAllSessions(range, opts.provider)
|
||||
|
|
|
|||
|
|
@ -107,9 +107,11 @@ const SERVE_OPTIONS: Readonly<Record<string, Readonly<Record<string, ServeOption
|
|||
'--contributions': 'flag',
|
||||
},
|
||||
compare: {
|
||||
'-p': 'value', '--period': 'value', '--provider': 'value', '--format': 'value',
|
||||
'-p': 'value', '--period': 'value', '--from': 'value', '--to': 'value',
|
||||
'--provider': 'value', '--format': 'value',
|
||||
'--model-a': 'value', '--model-b': 'value',
|
||||
'--project': 'value', '--exclude': 'value',
|
||||
'--category': 'value', '--project-id': 'value',
|
||||
},
|
||||
yield: {
|
||||
'-p': 'value', '--period': 'value', '--provider': 'value', '--format': 'value',
|
||||
|
|
|
|||
238
tests/cli-compare-cohort.test.ts
Normal file
238
tests/cli-compare-cohort.test.ts
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// End-to-end over the real CLI: the cohort branch of `compare` must apply the
|
||||
// --project / --exclude / --category / --from--to selection BEFORE computing
|
||||
// anything, and the reported statistics must be reproducible from the sample
|
||||
// list the same payload carries. Unit tests pin the math; this one proves the
|
||||
// selection flags actually reach it.
|
||||
|
||||
// Each test spawns `tsx src/cli.ts`, which re-transpiles the CLI per spawn.
|
||||
beforeAll(() => {
|
||||
vi.setConfig({ testTimeout: 60_000 })
|
||||
})
|
||||
|
||||
const SIBLINGS = [
|
||||
{ dir: '-Users-gone-alpha', cwd: '/Users/gone/alpha', session: 's-alpha' },
|
||||
{ dir: '-Users-gone-beta', cwd: '/Users/gone/beta', session: 's-beta' },
|
||||
]
|
||||
|
||||
const OPUS = 'claude-opus-4-20250514'
|
||||
const SONNET = 'claude-3-5-sonnet-20241022'
|
||||
|
||||
let homes: string[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
while (homes.length > 0) {
|
||||
const home = homes.pop()
|
||||
if (home) await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function assistantLine(session: string, cwd: string, model: string, minutesAgo: number, costWeights: { input: number; output: number } = { input: 90_000, output: 12_000 }): string {
|
||||
return JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
|
||||
sessionId: session,
|
||||
cwd,
|
||||
message: {
|
||||
type: 'message', role: 'assistant', model, id: `${session}-${model}-${minutesAgo}`,
|
||||
content: [{ type: 'tool_use', id: `tu-${minutesAgo}`, name: 'Edit', input: {} }],
|
||||
usage: {
|
||||
input_tokens: costWeights.input,
|
||||
output_tokens: costWeights.output,
|
||||
cache_creation_input_tokens: 0,
|
||||
cache_read_input_tokens: 300_000,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function userLine(session: string, cwd: string, minutesAgo: number, text = 'please edit the file'): string {
|
||||
return JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: new Date(Date.now() - minutesAgo * 60_000).toISOString(),
|
||||
sessionId: session,
|
||||
cwd,
|
||||
message: { role: 'user', content: text },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Two sibling projects:
|
||||
* - alpha: 2 opus edit turns, 1 sonnet edit turn, 1 opus+sonnet MIXED turn
|
||||
* - beta: 1 opus edit turn
|
||||
*/
|
||||
async function seedHome(): Promise<string> {
|
||||
const home = await mkdtemp(join(tmpdir(), 'codeburn-compare-cohort-'))
|
||||
homes.push(home)
|
||||
const minutes = (n: number) => 5 + n
|
||||
const alphaLines = [
|
||||
userLine('s-alpha', '/Users/gone/alpha', minutes(1)),
|
||||
assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(2)),
|
||||
userLine('s-alpha', '/Users/gone/alpha', minutes(3)),
|
||||
assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(4)),
|
||||
userLine('s-alpha', '/Users/gone/alpha', minutes(5)),
|
||||
assistantLine('s-alpha', '/Users/gone/alpha', SONNET, minutes(6)),
|
||||
// Mixed turn: two assistant lines of different models between user msgs.
|
||||
userLine('s-alpha', '/Users/gone/alpha', minutes(7)),
|
||||
assistantLine('s-alpha', '/Users/gone/alpha', OPUS, minutes(8)),
|
||||
assistantLine('s-alpha', '/Users/gone/alpha', SONNET, minutes(9)),
|
||||
]
|
||||
const betaLines = [
|
||||
userLine('s-beta', '/Users/gone/beta', minutes(1)),
|
||||
assistantLine('s-beta', '/Users/gone/beta', OPUS, minutes(2)),
|
||||
]
|
||||
const alphaDir = join(home, '.claude', 'projects', SIBLINGS[0]!.dir)
|
||||
const betaDir = join(home, '.claude', 'projects', SIBLINGS[1]!.dir)
|
||||
await mkdir(alphaDir, { recursive: true })
|
||||
await mkdir(betaDir, { recursive: true })
|
||||
await writeFile(join(alphaDir, `${SIBLINGS[0]!.session}.jsonl`), alphaLines.join('\n') + '\n', 'utf-8')
|
||||
await writeFile(join(betaDir, `${SIBLINGS[1]!.session}.jsonl`), betaLines.join('\n') + '\n', 'utf-8')
|
||||
return home
|
||||
}
|
||||
|
||||
function runCli(args: string[], home: string) {
|
||||
return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: join(home, '.claude'), CODEBURN_CACHE_DIR: join(home, 'cache'), TZ: 'UTC' },
|
||||
encoding: 'utf-8',
|
||||
timeout: 60_000,
|
||||
})
|
||||
}
|
||||
|
||||
type CohortReport = {
|
||||
kind: string
|
||||
modelA: { model: string; stats: { observationCount: number; distinctSessionCount: number; costMedian: number | null; costP90: number | null; unknownCostCount: number }; observations: Array<{ costUSD: number; costKnown: boolean; sessionId: string; project: string; category: string }> }
|
||||
modelB: { model: string; stats: { observationCount: number }; observations: unknown[] }
|
||||
conventions: Record<string, string>
|
||||
}
|
||||
|
||||
describe('compare --format cohort-json', () => {
|
||||
it('answers the facet query without models: models, canonical projects, categories', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days'], home)
|
||||
expect(result.status).toBe(0)
|
||||
// tsx emits a Node deprecation line on stderr; the meaningful assertion is
|
||||
// that no codeburn-level warning (e.g. an unmatched project pattern) fired.
|
||||
expect(result.stderr).not.toContain('codeburn')
|
||||
const facets = JSON.parse(result.stdout)
|
||||
expect(facets.kind).toBe('cohort-facets')
|
||||
expect(facets.models.map((m: { model: string }) => m.model).sort()).toEqual([OPUS, SONNET].sort())
|
||||
expect(facets.projects.map((p: { project: string }) => p.project).sort())
|
||||
.toEqual(['-Users-gone-alpha', '-Users-gone-beta'])
|
||||
expect(facets.categories.length).toBeGreaterThan(5)
|
||||
})
|
||||
|
||||
it('attributes each single-model edit turn to its own model and reports the mixed turn as excluded', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET], home)
|
||||
expect(result.status).toBe(0)
|
||||
const report = JSON.parse(result.stdout) as CohortReport
|
||||
expect(report.kind).toBe('cohort-comparison')
|
||||
// alpha: 2 opus turns + beta: 1 opus turn = 3 observations; the mixed turn
|
||||
// belongs to NOBODY. Sonnet: 1 single-model turn.
|
||||
expect(report.modelA.stats.observationCount).toBe(3)
|
||||
expect(report.modelB.stats.observationCount).toBe(1)
|
||||
expect(report.modelA.observations).toHaveLength(3)
|
||||
// Reproducibility: the median is recomputable from the sample list.
|
||||
const costs = report.modelA.observations.map(o => o.costUSD).sort((a, b) => a - b)
|
||||
const median = costs.length % 2 === 1
|
||||
? costs[(costs.length - 1) / 2]
|
||||
: (costs[costs.length / 2 - 1]! + costs[costs.length / 2]!) / 2
|
||||
expect(report.modelA.stats.costMedian).toBeCloseTo(median, 10)
|
||||
expect(report.modelA.stats.distinctSessionCount).toBe(2)
|
||||
// Conventions are part of the payload, not folklore.
|
||||
expect(report.conventions.attribution).toContain('owning model')
|
||||
})
|
||||
|
||||
it('lets a rooted --project exclude observations before any statistic is computed', async () => {
|
||||
const home = await seedHome()
|
||||
const filtered = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET, '--project', '/Users/gone/alpha'], home)
|
||||
expect(filtered.status).toBe(0)
|
||||
const report = JSON.parse(filtered.stdout) as CohortReport
|
||||
expect(report.modelA.stats.observationCount).toBe(2)
|
||||
expect(report.modelA.observations.every(o => o.project === '-Users-gone-alpha')).toBe(true)
|
||||
// And the payload's selection records the restriction.
|
||||
expect(JSON.parse(filtered.stdout).selection.projects).toEqual(['-Users-gone-alpha'])
|
||||
})
|
||||
|
||||
it('reports zero-observation cohorts with null stats instead of zeros when a category keeps nothing', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET, '--category', 'testing'], home)
|
||||
expect(result.status).toBe(0)
|
||||
const report = JSON.parse(result.stdout) as CohortReport
|
||||
expect(report.modelA.stats.observationCount).toBe(0)
|
||||
expect(report.modelA.stats.costMedian).toBeNull()
|
||||
expect(report.modelA.observations).toEqual([])
|
||||
expect(report.modelB.stats.observationCount).toBe(0)
|
||||
})
|
||||
|
||||
it('selects an exact project id while preserving loose --project matching', async () => {
|
||||
const home = await seedHome()
|
||||
const siblingPath = '/Users/gone/alpha-backend'
|
||||
const siblingDir = join(home, '.claude', 'projects', '-Users-gone-alpha-backend')
|
||||
await mkdir(siblingDir, { recursive: true })
|
||||
await writeFile(join(siblingDir, 's-sibling.jsonl'), [
|
||||
userLine('s-sibling', siblingPath, 10),
|
||||
assistantLine('s-sibling', siblingPath, OPUS, 9),
|
||||
].join('\n') + '\n')
|
||||
const args = ['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', OPUS, '--model-b', SONNET]
|
||||
const exact = runCli([...args, '--project-id=/Users/gone/alpha'], home)
|
||||
expect(exact.status).toBe(0)
|
||||
const report = JSON.parse(exact.stdout) as CohortReport
|
||||
expect(report.modelA.stats.observationCount).toBe(2)
|
||||
expect(report.modelA.observations.every(o => o.project === '-Users-gone-alpha')).toBe(true)
|
||||
const loose = runCli([...args, '--project', 'alpha'], home)
|
||||
expect(loose.status).toBe(0)
|
||||
expect(JSON.parse(loose.stdout).modelA.stats.observationCount).toBe(3)
|
||||
const oneModel = runCli([...args, '--project-id=/Users/gone/alpha-backend'], home)
|
||||
expect(oneModel.status).toBe(0)
|
||||
const oneModelReport = JSON.parse(oneModel.stdout) as CohortReport
|
||||
expect(oneModelReport.modelA.stats.observationCount).toBe(1)
|
||||
expect(oneModelReport.modelB.stats.observationCount).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects an unknown category with a usable message', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--category', 'not-a-category'], home)
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain('unknown category "not-a-category"')
|
||||
})
|
||||
|
||||
it('rejects an unknown model like the classic format does', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--period', '30days', '--model-a', 'nope-1', '--model-b', OPUS], home)
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain('model not found: "nope-1"')
|
||||
})
|
||||
|
||||
it('accepts an explicit --from/--to interval', async () => {
|
||||
const home = await seedHome()
|
||||
const from = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
|
||||
const to = new Date().toISOString().slice(0, 10)
|
||||
const result = runCli(['compare', '--format', 'cohort-json', '--model-a', OPUS, '--model-b', SONNET, '--from', from, '--to', to], home)
|
||||
expect(result.status).toBe(0)
|
||||
const report = JSON.parse(result.stdout) as CohortReport & { selection: { from: string; to: string } }
|
||||
expect(report.selection.from).toBe(from)
|
||||
expect(report.selection.to).toBe(to)
|
||||
expect(report.modelA.stats.observationCount).toBe(3)
|
||||
})
|
||||
|
||||
it('leaves the classic json contract untouched (an array of ModelStats)', async () => {
|
||||
const home = await seedHome()
|
||||
const result = runCli(['compare', '--format', 'json', '--period', '30days'], home)
|
||||
expect(result.status).toBe(0)
|
||||
const classic = JSON.parse(result.stdout)
|
||||
expect(Array.isArray(classic)).toBe(true)
|
||||
expect(classic.map((m: { model: string }) => m.model).sort()).toEqual([OPUS, SONNET].sort())
|
||||
// Classic rows carry the classic fields, untouched by the cohort work.
|
||||
expect(classic[0]).toHaveProperty('editTurns')
|
||||
expect(classic[0]).toHaveProperty('editCost')
|
||||
expect(classic[0]).not.toHaveProperty('observations')
|
||||
})
|
||||
})
|
||||
438
tests/compare-cohorts.test.ts
Normal file
438
tests/compare-cohorts.test.ts
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
buildCohortComparison,
|
||||
buildCohortFacets,
|
||||
computeCohortStats,
|
||||
costHistogram,
|
||||
extractCohortObservations,
|
||||
linearPercentile,
|
||||
medianOf,
|
||||
selectCohortProjects,
|
||||
type CohortObservation,
|
||||
} from '../src/compare-cohorts.js'
|
||||
import { aggregateSessions } from '../src/sessions-report.js'
|
||||
import { findModelStat } from '../src/compare-stats.js'
|
||||
import { getShortModelName } from '../src/models.js'
|
||||
import type { ClassifiedTurn, ProjectSummary, SessionSummary } from '../src/types.js'
|
||||
|
||||
let keySeq = 0
|
||||
|
||||
function makeTurn(model: string | string[], cost: number, opts: {
|
||||
hasEdits?: boolean
|
||||
retries?: number
|
||||
category?: string
|
||||
timestamp?: string
|
||||
sessionId?: string
|
||||
outputTokens?: number
|
||||
inputTokens?: number
|
||||
unpriced?: boolean
|
||||
extraCalls?: Array<{ model: string; cost: number }>
|
||||
} = {}): ClassifiedTurn {
|
||||
const models = Array.isArray(model) ? model : [model]
|
||||
const calls = models.map((m, i) => ({
|
||||
provider: 'claude',
|
||||
model: m,
|
||||
usage: {
|
||||
inputTokens: opts.inputTokens ?? 1200,
|
||||
outputTokens: opts.outputTokens ?? 300,
|
||||
cacheCreationInputTokens: 400,
|
||||
cacheReadInputTokens: 5000,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
},
|
||||
costUSD: i === 0 ? cost : 0,
|
||||
tools: opts.hasEdits === false ? ['Read'] : ['Edit'],
|
||||
mcpTools: [],
|
||||
skills: [],
|
||||
subagentTypes: [],
|
||||
hasAgentSpawn: false,
|
||||
hasPlanMode: false,
|
||||
speed: 'standard' as const,
|
||||
timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
|
||||
bashCommands: [],
|
||||
deduplicationKey: `key-${keySeq++}`,
|
||||
}))
|
||||
for (const extra of opts.extraCalls ?? []) {
|
||||
calls.push({
|
||||
provider: 'claude',
|
||||
model: extra.model,
|
||||
usage: {
|
||||
inputTokens: 1000,
|
||||
outputTokens: 250,
|
||||
cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 4000,
|
||||
cachedInputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
webSearchRequests: 0,
|
||||
},
|
||||
costUSD: extra.cost,
|
||||
tools: ['Edit'],
|
||||
mcpTools: [],
|
||||
skills: [],
|
||||
subagentTypes: [],
|
||||
hasAgentSpawn: false,
|
||||
hasPlanMode: false,
|
||||
speed: 'standard' as const,
|
||||
timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
|
||||
bashCommands: [],
|
||||
deduplicationKey: `key-${keySeq++}`,
|
||||
})
|
||||
}
|
||||
return {
|
||||
timestamp: opts.timestamp ?? '2026-08-15T10:00:00Z',
|
||||
category: (opts.category ?? 'coding') as ClassifiedTurn['category'],
|
||||
retries: opts.retries ?? 0,
|
||||
hasEdits: opts.hasEdits ?? true,
|
||||
userMessage: '',
|
||||
sessionId: opts.sessionId ?? 'sess-1',
|
||||
assistantCalls: calls,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSession(sessionId: string, turns: ClassifiedTurn[]): SessionSummary {
|
||||
return {
|
||||
sessionId,
|
||||
project: 'proj-a',
|
||||
firstTimestamp: turns[0]?.timestamp ?? '',
|
||||
lastTimestamp: turns[turns.length - 1]?.timestamp ?? '',
|
||||
totalCostUSD: 0,
|
||||
totalInputTokens: 0,
|
||||
totalOutputTokens: 0,
|
||||
totalCacheReadTokens: 0,
|
||||
totalCacheWriteTokens: 0,
|
||||
apiCalls: turns.reduce((s, t) => s + t.assistantCalls.length, 0),
|
||||
turns,
|
||||
modelBreakdown: {},
|
||||
toolBreakdown: {},
|
||||
mcpBreakdown: {},
|
||||
bashBreakdown: {},
|
||||
categoryBreakdown: {} as SessionSummary['categoryBreakdown'],
|
||||
skillBreakdown: {} as SessionSummary['skillBreakdown'],
|
||||
}
|
||||
}
|
||||
|
||||
function makeProject(sessionId: string, turns: ClassifiedTurn[], project = 'proj-a'): ProjectSummary {
|
||||
const session = makeSession(sessionId, turns)
|
||||
session.project = project
|
||||
return {
|
||||
project,
|
||||
projectPath: `/work/${project}`,
|
||||
sessions: [session],
|
||||
totalCostUSD: 0,
|
||||
totalProxiedCostUSD: 0,
|
||||
totalApiCalls: session.apiCalls,
|
||||
}
|
||||
}
|
||||
|
||||
// ————— The pinned percentile convention —————
|
||||
|
||||
describe('percentile convention (pinned)', () => {
|
||||
it('gives median 3 and P90 6.8 for [1, 2, 4, 8] with linear interpolation at (N-1)*p', () => {
|
||||
const sorted = [1, 2, 4, 8]
|
||||
expect(medianOf(sorted)).toBe(3)
|
||||
expect(linearPercentile(sorted, 0.9)).toBeCloseTo(6.8, 10)
|
||||
})
|
||||
|
||||
it('interpolates at exact positions without rounding', () => {
|
||||
expect(linearPercentile([10, 20], 0.5)).toBe(15)
|
||||
expect(linearPercentile([10], 0.9)).toBe(10)
|
||||
expect(linearPercentile([], 0.9)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Observation extraction —————
|
||||
|
||||
describe('extractCohortObservations', () => {
|
||||
it('retains supplementary spend and tokens without giving it behavioral ownership', () => {
|
||||
const turn = makeTurn('opus-4-6', 1, { inputTokens: 100 })
|
||||
turn.assistantCalls.push({
|
||||
...turn.assistantCalls[0]!, costUSD: 9, supplementaryAccounting: true,
|
||||
usage: { ...turn.assistantCalls[0]!.usage, inputTokens: 900 },
|
||||
}, {
|
||||
...turn.assistantCalls[0]!, model: 'sonnet-5', costUSD: 7, supplementaryAccounting: true,
|
||||
})
|
||||
const { perModel, exclusions } = extractCohortObservations({ projects: [makeProject('s1', [turn])] })
|
||||
expect(perModel.get('opus-4-6')).toHaveLength(1)
|
||||
expect(perModel.get('opus-4-6')![0]).toMatchObject({ costUSD: 10, inputTokens: 1000 })
|
||||
expect(perModel.has('sonnet-5')).toBe(false)
|
||||
expect(exclusions.multiModelTurns).toEqual([])
|
||||
})
|
||||
|
||||
it('owns an edit turn by its single behavioral model and attributes only that model\'s cost', () => {
|
||||
// One turn: opus behavioral call ($0.10) + sonnet behavioral call ($0.05)
|
||||
// would be MULTI-model; here instead: opus call costs 0.10, a second call
|
||||
// of the SAME model adds 0.02 — both belong to the observation.
|
||||
const project = makeProject('s1', [
|
||||
makeTurn('opus-4-6', 0.10, { extraCalls: [{ model: 'opus-4-6', cost: 0.02 }] }),
|
||||
])
|
||||
const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
|
||||
const obs = perModel.get('opus-4-6')!
|
||||
expect(obs).toHaveLength(1)
|
||||
expect(obs[0]!.costUSD).toBeCloseTo(0.12)
|
||||
expect(obs[0]!.model).toBe('opus-4-6')
|
||||
// No other model gets an observation; nothing was excluded.
|
||||
expect(perModel.size).toBe(1)
|
||||
expect(exclusions.multiModelTurns).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('excludes multi-model edit turns and transfers no cost to either model', () => {
|
||||
const project = makeProject('s1', [
|
||||
makeTurn(['opus-4-6', 'sonnet-5'], 0.10, { extraCalls: [{ model: 'sonnet-5', cost: 0.05 }] }),
|
||||
makeTurn('opus-4-6', 0.10),
|
||||
])
|
||||
const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
|
||||
// The mixed turn is counted once, shown with combined cost 0.15, and NO
|
||||
// cohort receives any of it. opus keeps only its own single-model turn.
|
||||
expect(exclusions.multiModelTurns).toHaveLength(1)
|
||||
expect(exclusions.multiModelTurns[0]!.models).toEqual(['opus-4-6', 'sonnet-5'])
|
||||
expect(exclusions.combinedMultiModelCostUSD).toBeCloseTo(0.15)
|
||||
expect(perModel.get('opus-4-6')).toHaveLength(1)
|
||||
expect(perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.10)
|
||||
expect(perModel.has('sonnet-5')).toBe(false)
|
||||
})
|
||||
|
||||
it('reports one shared exclusion ledger even when a cohort has zero observations', () => {
|
||||
const project = makeProject('s1', [
|
||||
makeTurn(['opus-4-6', 'mystery-pro-9'], 0.10, { extraCalls: [{ model: 'mystery-pro-9', cost: 0.05 }] }),
|
||||
])
|
||||
const { exclusions } = extractCohortObservations({ projects: [project] })
|
||||
expect(exclusions.multiModelTurns).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('counts edit turns with no behavioral model', () => {
|
||||
const turn = makeTurn('opus-4-6', 0)
|
||||
turn.assistantCalls[0]!.supplementaryAccounting = true
|
||||
const project = makeProject('s1', [turn])
|
||||
const { perModel, exclusions } = extractCohortObservations({ projects: [project] })
|
||||
expect(exclusions.noBehavioralModelTurns).toBe(1)
|
||||
expect(perModel.size).toBe(0)
|
||||
})
|
||||
|
||||
it('respects the category selection before anything is counted', () => {
|
||||
const project = makeProject('s1', [
|
||||
makeTurn('opus-4-6', 0.10, { category: 'coding' }),
|
||||
makeTurn('opus-4-6', 0.20, { category: 'debugging' }),
|
||||
])
|
||||
const coding = extractCohortObservations({ projects: [project], category: 'coding' })
|
||||
expect(coding.perModel.get('opus-4-6')).toHaveLength(1)
|
||||
expect(coding.perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.10)
|
||||
|
||||
const debugging = extractCohortObservations({ projects: [project], category: 'debugging' })
|
||||
expect(debugging.perModel.get('opus-4-6')![0]!.costUSD).toBeCloseTo(0.20)
|
||||
})
|
||||
|
||||
it('skips non-edit turns entirely', () => {
|
||||
const project = makeProject('s1', [makeTurn('opus-4-6', 0.10, { hasEdits: false })])
|
||||
const { perModel } = extractCohortObservations({ projects: [project] })
|
||||
expect(perModel.size).toBe(0)
|
||||
})
|
||||
|
||||
it('pairs project and session for identity (a bare sessionId is not a global key)', () => {
|
||||
const p1 = makeProject('same-id', [makeTurn('opus-4-6', 0.10)], 'proj-a')
|
||||
const p2 = makeProject('same-id', [makeTurn('opus-4-6', 0.10)], 'proj-b')
|
||||
const stats = computeCohortStats('opus-4-6', [
|
||||
...(extractCohortObservations({ projects: [p1] }).perModel.get('opus-4-6') ?? []),
|
||||
...(extractCohortObservations({ projects: [p2] }).perModel.get('opus-4-6') ?? []),
|
||||
])
|
||||
// Two sessions share the literal id; distinct sessions must be 2.
|
||||
expect(stats.distinctSessionCount).toBe(2)
|
||||
expect(stats.observationCount).toBe(2)
|
||||
})
|
||||
|
||||
it('carries the same provider/project/session triple the sessions report keys rows by', () => {
|
||||
const project = makeProject('s1', [makeTurn('opus-4-6', 0.10)], 'proj-a')
|
||||
const [observation] = extractCohortObservations({ projects: [project] }).perModel.get('opus-4-6') ?? []
|
||||
const [row] = aggregateSessions([project])
|
||||
expect([observation?.provider, observation?.project, observation?.sessionId])
|
||||
.toEqual([row?.provider, row?.project, row?.sessionId])
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Cost semantics: unknown ≠ zero —————
|
||||
|
||||
describe('canonical cohort project selection', () => {
|
||||
it('keeps same-label projects distinct and selects exact identities without prefix matching', () => {
|
||||
const projects = ['/work/app', '/work/app-backend', '/other/app'].map((projectPath, i) => ({
|
||||
...makeProject(`s${i}`, [makeTurn('opus-4-6', i + 1)], 'app'), projectPath,
|
||||
}))
|
||||
const facets = buildCohortFacets(projects)
|
||||
expect(facets.projects.map(p => p.id).sort()).toEqual(projects.map(p => p.projectPath).sort())
|
||||
expect(selectCohortProjects(projects, ['/work/app'])).toEqual([projects[0]])
|
||||
expect(selectCohortProjects(projects, ['/work/app', '/other/app'])).toEqual([projects[0], projects[2]])
|
||||
expect(selectCohortProjects(projects, ['app'])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('unknown cost handling', () => {
|
||||
it('marks an unpriced model\'s $0 observations as unknown and keeps them out of cost stats but in retry stats', () => {
|
||||
const project = makeProject('s1', [
|
||||
makeTurn('mystery-pro-9', 0, { retries: 3 }),
|
||||
makeTurn('mystery-pro-9', 0, { retries: 0 }),
|
||||
])
|
||||
const { perModel } = extractCohortObservations({ projects: [project] })
|
||||
const obs = perModel.get('mystery-pro-9')!
|
||||
expect(obs.every(o => !o.costKnown)).toBe(true)
|
||||
const stats = computeCohortStats('mystery-pro-9', obs)
|
||||
expect(stats.observationCount).toBe(2)
|
||||
expect(stats.unknownCostCount).toBe(2)
|
||||
expect(stats.costKnownCount).toBe(0)
|
||||
expect(stats.costMedian).toBeNull()
|
||||
expect(stats.costP90).toBeNull()
|
||||
// Retry statistics never need pricing: they still count.
|
||||
expect(stats.retryCount).toBe(3)
|
||||
expect(stats.oneShotCount).toBe(1)
|
||||
expect(stats.retryRate).toBeCloseTo(1.5)
|
||||
})
|
||||
|
||||
it('keeps legitimately free models (local / flat-rate) as known-zero cost', () => {
|
||||
const project = makeProject('s1', [makeTurn('qwen3:35b', 0)])
|
||||
const { perModel } = extractCohortObservations({ projects: [project] })
|
||||
const obs = perModel.get('qwen3:35b')!
|
||||
expect(obs[0]!.costKnown).toBe(true)
|
||||
const stats = computeCohortStats('qwen3:35b', obs)
|
||||
expect(stats.unknownCostCount).toBe(0)
|
||||
expect(stats.costMedian).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Cohort statistics —————
|
||||
|
||||
describe('computeCohortStats', () => {
|
||||
function obs(cost: number, over: Partial<CohortObservation> = {}): CohortObservation {
|
||||
return {
|
||||
sessionId: 's1',
|
||||
project: 'proj-a',
|
||||
timestamp: '2026-08-15T10:00:00Z',
|
||||
category: 'coding',
|
||||
model: 'opus-4-6',
|
||||
costUSD: cost,
|
||||
costKnown: true,
|
||||
retries: 0,
|
||||
oneShot: true,
|
||||
inputTokens: 1000,
|
||||
outputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
cacheWriteTokens: 100,
|
||||
contextProxyTokens: 3000,
|
||||
tokensReported: true,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
it('produces the pinned [1,2,4,8] convention through the full stats path', () => {
|
||||
const stats = computeCohortStats('opus-4-6', [obs(1), obs(2), obs(4), obs(8)])
|
||||
expect(stats.costMedian).toBe(3)
|
||||
expect(stats.costP90).toBeCloseTo(6.8, 10)
|
||||
})
|
||||
|
||||
it('handles N=0 with nulls and no NaN anywhere', () => {
|
||||
const stats = computeCohortStats('opus-4-6', [])
|
||||
expect(stats.observationCount).toBe(0)
|
||||
expect(stats.costMedian).toBeNull()
|
||||
expect(stats.costP90).toBeNull()
|
||||
expect(stats.retryRate).toBeNull()
|
||||
expect(stats.oneShotRate).toBeNull()
|
||||
expect(stats.costHistogram.counts).toEqual([])
|
||||
expect(stats.volume.outputMedian).toBeNull()
|
||||
expect(JSON.stringify(stats)).not.toContain('NaN')
|
||||
})
|
||||
|
||||
it('handles N=1: median and P90 both equal the single value', () => {
|
||||
const stats = computeCohortStats('opus-4-6', [obs(0.42)])
|
||||
expect(stats.costMedian).toBeCloseTo(0.42)
|
||||
expect(stats.costP90).toBeCloseTo(0.42)
|
||||
expect(stats.oneShotRate).toBe(100)
|
||||
})
|
||||
|
||||
it('keeps a huge outlier in every statistic and the histogram top bucket', () => {
|
||||
const costs = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 5.0]
|
||||
const stats = computeCohortStats('opus-4-6', costs.map(c => obs(c)))
|
||||
// Outlier still in the population and the percentiles.
|
||||
expect(stats.observationCount).toBe(10)
|
||||
expect(stats.costP90).toBeGreaterThan(0.09)
|
||||
expect(stats.costMedian).toBeCloseTo(0.055)
|
||||
const hist = stats.costHistogram
|
||||
expect(hist.counts.reduce((a, b) => a + b, 0)).toBe(10)
|
||||
// The 95th-percentile edge pushes the outlier into the last bucket.
|
||||
expect(hist.counts[hist.counts.length - 1]).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('handles very unequal groups by never inventing values for the small one', () => {
|
||||
const big = Array.from({ length: 50 }, (_, i) => obs(0.01 * (i + 1)))
|
||||
const stats = computeCohortStats('opus-4-6', big)
|
||||
expect(stats.observationCount).toBe(50)
|
||||
expect(stats.costMedian).toBeCloseTo(0.255)
|
||||
const tiny = computeCohortStats('sonnet-5', [obs(0.9, { model: 'sonnet-5' })])
|
||||
expect(tiny.observationCount).toBe(1)
|
||||
})
|
||||
|
||||
it('computes volume percentiles only over observations that report tokens', () => {
|
||||
const withTokens = obs(0.10)
|
||||
const without = obs(0.10, { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, tokensReported: false })
|
||||
const stats = computeCohortStats('opus-4-6', [withTokens, without])
|
||||
expect(stats.volume.missingMeasureCount).toBe(1)
|
||||
expect(stats.volume.outputMedian).toBe(500)
|
||||
// Cost statistics still cover BOTH observations (cost is known for both).
|
||||
expect(stats.costKnownCount).toBe(2)
|
||||
})
|
||||
|
||||
it('is reproducible from the report\'s observation list', () => {
|
||||
const project = makeProject('s1', [
|
||||
makeTurn('opus-4-6', 0.10, { retries: 1 }),
|
||||
makeTurn('opus-4-6', 0.30, { retries: 0 }),
|
||||
makeTurn('sonnet-5', 0.05, { retries: 2 }),
|
||||
])
|
||||
const report = buildCohortComparison([project], 'opus-4-6', 'sonnet-5', 'Test label', 'claude')
|
||||
// Recompute the medians from the reported sample lists; they must match.
|
||||
for (const side of [report.modelA, report.modelB]) {
|
||||
const known = side.observations.filter(o => o.costKnown).map(o => o.costUSD).sort((a, b) => a - b)
|
||||
const recomputed = medianOf(known)
|
||||
expect(recomputed).toBeCloseTo(side.stats.costMedian ?? NaN)
|
||||
expect(side.stats.observationCount).toBe(side.observations.length)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Histogram determinism —————
|
||||
|
||||
describe('costHistogram', () => {
|
||||
it('is deterministic and totals the population', () => {
|
||||
const costs = [0.1, 0.2, 0.3, 0.4, 0.5]
|
||||
const h1 = costHistogram(costs)
|
||||
const h2 = costHistogram([...costs].reverse())
|
||||
expect(h1).toEqual(h2)
|
||||
expect(h1.counts.reduce((a, b) => a + b, 0)).toBe(costs.length)
|
||||
})
|
||||
|
||||
it('collapses to a single bucket when every cost is zero', () => {
|
||||
const h = costHistogram([0, 0, 0])
|
||||
expect(h.edges).toEqual([])
|
||||
expect(h.counts).toEqual([3])
|
||||
})
|
||||
})
|
||||
|
||||
// ————— Facets and alias resolution —————
|
||||
|
||||
describe('facets and model identity', () => {
|
||||
it('lists canonical project identities once with merged session counts', () => {
|
||||
const p1 = makeProject('s1', [makeTurn('opus-4-6', 0.10)], 'proj-a')
|
||||
const p2 = makeProject('s2', [makeTurn('opus-4-6', 0.10)], 'proj-a')
|
||||
const facets = buildCohortFacets([p1, p2])
|
||||
expect(facets.projects).toHaveLength(1)
|
||||
expect(facets.projects[0]!.sessions).toBe(2)
|
||||
expect(facets.categories.length).toBeGreaterThan(5)
|
||||
})
|
||||
|
||||
it('resolves display-name aliases to the canonical id like the classic picker', () => {
|
||||
const project = makeProject('s1', [makeTurn('claude-opus-4-6-20260610', 0.10)])
|
||||
const facets = buildCohortFacets([project])
|
||||
const canonical = facets.models[0]!.model
|
||||
expect(canonical).toBe('claude-opus-4-6-20260610')
|
||||
// findModelStat is the shared alias-aware lookup; a display name like
|
||||
// "Opus 4.6" resolves to the same canonical row.
|
||||
const byDisplay = findModelStat(facets.models, getShortModelName(canonical))
|
||||
expect(byDisplay?.model).toBe(canonical)
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue