mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
feat(sessions): show each session's cache hit rate (#1861)
The sessions table, the interactive sessions view, the JSON rows and the desktop Sessions page now show a cache hit rate per session. It is cache reads divided by input plus cache reads plus cache writes, the share of the prompt that came from cache. A session with no cache reads or writes is unmeasured and shows a dash instead of 0%. The session drawer, the compare views, the menubar payload and the JSON report now use the same formula through one helper, so every surface reports the same number. Optimize already used it, so its finding does not move.
This commit is contained in:
parent
792d1ab119
commit
bcccfdeb17
20 changed files with 121 additions and 58 deletions
|
|
@ -5,6 +5,7 @@ import type { ClassifiedTurn, ProjectSummary } from './types.js'
|
|||
import { behavioralCallWeight, isBehavioralCall } from './behavioral-weight.js'
|
||||
import { modelRowKey } from './models.js'
|
||||
import { callBillableOutputTokens } from './session-output.js'
|
||||
import { sessionCacheHitPercent } from './sessions-report.js'
|
||||
|
||||
const PLANNING_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TodoWrite', 'EnterPlanMode', 'ExitPlanMode'])
|
||||
|
||||
|
|
@ -188,12 +189,7 @@ const METRICS: MetricDef[] = [
|
|||
label: 'Cache hit rate',
|
||||
formatFn: 'percent',
|
||||
higherIsBetter: true,
|
||||
compute: s => {
|
||||
// Cache-hit = reads over reads + fresh input (excludes cache writes), to
|
||||
// match src/menubar-json.ts:cacheHitPercent and the rest of the app.
|
||||
const total = s.inputTokens + s.cacheReadTokens
|
||||
return total > 0 ? (s.cacheReadTokens / total) * 100 : null
|
||||
},
|
||||
compute: s => sessionCacheHitPercent(s.inputTokens, s.cacheReadTokens, s.cacheWriteTokens),
|
||||
},
|
||||
]
|
||||
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import { BSU, patchStdoutForWindows } from './ink-win.js'
|
|||
import { startUserTimingGuard } from './user-timing-guard.js'
|
||||
import { folderNameOriginKey, isTemporaryProjectPath, linkedOriginKey, originRepoName, projectOriginKey, TEMPORARY_PROJECTS } from './git-origin.js'
|
||||
import { countSessions } from './session-output.js'
|
||||
import { sessionCacheHitPercent } from './sessions-report.js'
|
||||
|
||||
type View = 'dashboard' | 'optimize' | 'compare'
|
||||
|
||||
|
|
@ -612,9 +613,7 @@ function Overview({ projects, label, width, planUsages, durable }: { projects: P
|
|||
const totalOutput = durable ? durable.outputTokens : allSessions.reduce((s, sess) => s + sess.totalOutputTokens, 0)
|
||||
const totalCacheRead = durable ? durable.cacheReadTokens : allSessions.reduce((s, sess) => s + sess.totalCacheReadTokens, 0)
|
||||
const totalCacheWrite = durable ? durable.cacheWriteTokens : allSessions.reduce((s, sess) => s + sess.totalCacheWriteTokens, 0)
|
||||
const allInputTokens = totalInput + totalCacheRead + totalCacheWrite
|
||||
const cacheHit = allInputTokens > 0
|
||||
? (totalCacheRead / allInputTokens) * 100 : 0
|
||||
const cacheHit = sessionCacheHitPercent(totalInput, totalCacheRead, totalCacheWrite) ?? 0
|
||||
const activePlanUsages = planUsages ?? []
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { ESTIMATED_COST_LEGEND, excludedGatewayNote, formatTokens, isEstimatedCo
|
|||
import { toDateString } from './daily-cache.js'
|
||||
import { statusSnapshotSemanticKey } from './status-snapshot-semantic.js'
|
||||
import { dateKey } from './day-aggregator.js'
|
||||
import { foldedSessionRows } from './sessions-report.js'
|
||||
import { foldedSessionRows, sessionCacheHitPercent } from './sessions-report.js'
|
||||
import { behavioralCallWeight } from './behavioral-weight.js'
|
||||
import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js'
|
||||
import type { AppliedFix } from './act/types.js'
|
||||
|
|
@ -618,10 +618,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey:
|
|||
const totalOutput = durable.data.outputTokens
|
||||
const totalCacheRead = durable.data.cacheReadTokens
|
||||
const totalCacheWrite = durable.data.cacheWriteTokens
|
||||
// Match src/menubar-json.ts:cacheHitPercent: reads over reads+fresh-input. cache_write
|
||||
// counts tokens being stored, not served, so it doesn't belong in the denominator.
|
||||
const cacheHitDenom = totalInput + totalCacheRead
|
||||
const cacheHitPercent = cacheHitDenom > 0 ? Math.round((totalCacheRead / cacheHitDenom) * 1000) / 10 : 0
|
||||
const cacheHitPercent = Math.round((sessionCacheHitPercent(totalInput, totalCacheRead, totalCacheWrite) ?? 0) * 10) / 10
|
||||
|
||||
// Daily rows come from the same durable day set as the headline so they sum
|
||||
// to it, carried days included. Both JSON call sites always pass durable
|
||||
|
|
|
|||
|
|
@ -143,7 +143,7 @@ import { getCurrency } from './currency.js'
|
|||
import type { GranularHistory } from './granular-history.js'
|
||||
import { getShortModelName, modelRowKey } from './models.js'
|
||||
import type { ReworkedFile } from './workflow-insights.js'
|
||||
import type { PrRow, BranchRow } from './sessions-report.js'
|
||||
import { sessionCacheHitPercent, type PrRow, type BranchRow } from './sessions-report.js'
|
||||
import type { LiveSessionsBlock } from './live-sessions.js'
|
||||
import type { CursorSyncStatus } from './cursor-sync.js'
|
||||
import { buildTelemetrySnapshot, type TelemetrySnapshot, type TelemetrySnapshotInput } from './telemetry-snapshot.js'
|
||||
|
|
@ -566,12 +566,6 @@ function aggregateOneShotRate(categories: PeriodData['categories']): number | nu
|
|||
return oneShots / edits
|
||||
}
|
||||
|
||||
function cacheHitPercent(inputTokens: number, cacheReadTokens: number): number {
|
||||
const denom = inputTokens + cacheReadTokens
|
||||
if (denom === 0) return 0
|
||||
return (cacheReadTokens / denom) * 100
|
||||
}
|
||||
|
||||
function buildTopActivities(categories: PeriodData['categories']): MenubarPayload['current']['topActivities'] {
|
||||
return categories.slice(0, TOP_ACTIVITIES_LIMIT).map(cat => ({
|
||||
name: cat.name,
|
||||
|
|
@ -831,7 +825,7 @@ export function buildMenubarPayload(
|
|||
outputTokens: current.outputTokens,
|
||||
cacheReadTokens: current.cacheReadTokens,
|
||||
cacheWriteTokens: current.cacheWriteTokens,
|
||||
cacheHitPercent: cacheHitPercent(current.inputTokens, current.cacheReadTokens),
|
||||
cacheHitPercent: sessionCacheHitPercent(current.inputTokens, current.cacheReadTokens, current.cacheWriteTokens) ?? 0,
|
||||
codexCredits: current.codexCredits ?? 0,
|
||||
estimatedCostUSD: current.estimatedCostUSD ?? 0,
|
||||
topActivities: buildTopActivities(current.categories),
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import { recommendModelDefault, type ModelDefaultRecommendation } from './act/mo
|
|||
import { appliedFixGlyph, formatAppliedFix, type AppliedFix } from './act/types.js'
|
||||
import { isUserStartedSession, userStartedProjects } from './session-population.js'
|
||||
import { countSessions, inferSessionProvider, sessionBillableOutputTokens } from './session-output.js'
|
||||
import { sessionCacheHitPercent } from './sessions-report.js'
|
||||
import { aggregateFileChurn, buildCoachingNotes, scanUserCorrections, medianTimeToFirstEditMs, worstOneShotCategory, type ReworkedFile } from './workflow-insights.js'
|
||||
|
||||
// ============================================================================
|
||||
|
|
@ -3980,14 +3981,11 @@ export function detectLowCacheHitSessions(projects: ProjectSummary[]): WasteFind
|
|||
if (!isOptimizeSession(session)) continue
|
||||
const reads = session.totalCacheReadTokens
|
||||
const writes = session.totalCacheWriteTokens
|
||||
// Parsers record unreported cache usage as 0, so a session with no cache
|
||||
// tokens at all is unmeasured, not a 0% hit rate.
|
||||
if (reads + writes === 0) continue
|
||||
const hitPercent = sessionCacheHitPercent(session.totalInputTokens, reads, writes)
|
||||
if (hitPercent === null) continue
|
||||
if (session.apiCalls < LOW_CACHE_HIT_MIN_CALLS) continue
|
||||
const totalInput = session.totalInputTokens + reads + writes
|
||||
if (totalInput < LOW_CACHE_HIT_MIN_INPUT_TOKENS) continue
|
||||
// Same formula as the dashboard overview: reads over all input incl. writes.
|
||||
const hitPercent = (reads / totalInput) * 100
|
||||
if (hitPercent >= LOW_CACHE_HIT_TARGET_PERCENT) continue
|
||||
candidates.push({
|
||||
project: project.project,
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ export type SessionRow = {
|
|||
outputTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
cacheHitPercent: number | null
|
||||
startedAt: string
|
||||
endedAt: string
|
||||
durationMs: number
|
||||
|
|
@ -42,6 +43,14 @@ function sessionCostLabel(cost: number): string {
|
|||
return `$${cost.toFixed(2)}`
|
||||
}
|
||||
|
||||
export function sessionCacheHitPercent(input: number, reads: number, writes: number): number | null {
|
||||
return reads + writes === 0 ? null : reads / (input + reads + writes) * 100
|
||||
}
|
||||
|
||||
export function cacheHitLabel(percent: number | null): string {
|
||||
return percent === null ? '\u2014' : `${Math.round(percent)}%`
|
||||
}
|
||||
|
||||
function durationMs(startedAt: string, endedAt: string): number {
|
||||
const duration = new Date(endedAt).getTime() - new Date(startedAt).getTime()
|
||||
return Number.isFinite(duration) ? duration : 0
|
||||
|
|
@ -62,6 +71,7 @@ export function aggregateSessions(projects: ProjectSummary[]): SessionRow[] {
|
|||
outputTokens: sessionBillableOutputTokens(session),
|
||||
cacheReadTokens: session.totalCacheReadTokens,
|
||||
cacheWriteTokens: session.totalCacheWriteTokens,
|
||||
cacheHitPercent: sessionCacheHitPercent(session.totalInputTokens, session.totalCacheReadTokens, session.totalCacheWriteTokens),
|
||||
startedAt: session.firstTimestamp,
|
||||
endedAt: session.lastTimestamp,
|
||||
durationMs: durationMs(session.firstTimestamp, session.lastTimestamp),
|
||||
|
|
@ -74,7 +84,7 @@ export function renderJson(rows: SessionRow[]): string {
|
|||
return JSON.stringify(rows, null, 2)
|
||||
}
|
||||
|
||||
type SessionColumnKey = 'started' | 'session' | 'children' | 'project' | 'provider' | 'models' | 'cost' | 'saved' | 'calls' | 'turns'
|
||||
type SessionColumnKey = 'started' | 'session' | 'children' | 'project' | 'provider' | 'models' | 'cost' | 'cache' | 'saved' | 'calls' | 'turns'
|
||||
type SessionColumn = {
|
||||
key: SessionColumnKey
|
||||
header: string
|
||||
|
|
@ -106,7 +116,7 @@ function fitColumns(columns: SessionColumn[], available: number, dropOrder?: Ses
|
|||
const fitted = columns.map(col => ({ ...col }))
|
||||
|
||||
// Remove low-value columns before squeezing names into unreadable slivers.
|
||||
for (const key of dropOrder ?? ['turns', 'saved', 'provider', 'calls'] as SessionColumnKey[]) {
|
||||
for (const key of dropOrder ?? ['turns', 'saved', 'provider', 'calls', 'cache'] as SessionColumnKey[]) {
|
||||
if (frameWidth(fitted) <= available) break
|
||||
const index = fitted.findIndex(col => col.key === key && col.optional)
|
||||
if (index >= 0) fitted.splice(index, 1)
|
||||
|
|
@ -194,6 +204,7 @@ function cellValue(row: SessionRow, key: SessionColumnKey): string {
|
|||
case 'provider': return row.provider
|
||||
case 'models': return sessionModelLabel(row.models)
|
||||
case 'cost': return markEstimated(sessionCostLabel(row.cost), row.isEstimated)
|
||||
case 'cache': return cacheHitLabel(row.cacheHitPercent)
|
||||
case 'saved': return `$${row.savingsUSD.toFixed(2)}`
|
||||
case 'calls': return row.calls.toLocaleString('en-US')
|
||||
case 'turns': return row.turns.toLocaleString('en-US')
|
||||
|
|
@ -242,6 +253,7 @@ function sessionColumns(hasSavings: boolean, childrenColumn: boolean): SessionCo
|
|||
{ key: 'provider', header: 'Provider', width: 9, minWidth: 8, optional: true },
|
||||
{ key: 'models', header: 'Models', width: 22, minWidth: 10, flex: 2 },
|
||||
{ key: 'cost', header: 'Cost', width: 9, minWidth: 7, right: true },
|
||||
{ key: 'cache', header: 'Cache', width: 6, minWidth: 6, right: true, optional: true },
|
||||
...(hasSavings ? [{ key: 'saved' as const, header: 'Saved', width: 9, minWidth: 7, right: true, optional: true }] : []),
|
||||
{ key: 'calls', header: 'Calls', width: 7, minWidth: 5, right: true, optional: true },
|
||||
{ key: 'turns', header: 'Turns', width: 7, minWidth: 5, right: true, optional: true },
|
||||
|
|
@ -321,6 +333,9 @@ function groupWorkUnitRows<T extends SessionRow>(rows: T[], resolution: WorkUnit
|
|||
}
|
||||
const cost = sum(member => member.cost)
|
||||
const estimatedCost = sum(member => member.estimatedCost)
|
||||
const inputTokens = sum(member => member.inputTokens)
|
||||
const cacheReadTokens = sum(member => member.cacheReadTokens)
|
||||
const cacheWriteTokens = sum(member => member.cacheWriteTokens)
|
||||
entries.push({
|
||||
row: {
|
||||
...root,
|
||||
|
|
@ -331,10 +346,11 @@ function groupWorkUnitRows<T extends SessionRow>(rows: T[], resolution: WorkUnit
|
|||
savingsUSD: sum(member => member.savingsUSD),
|
||||
calls: sum(member => member.calls),
|
||||
turns: sum(member => member.turns),
|
||||
inputTokens: sum(member => member.inputTokens),
|
||||
inputTokens,
|
||||
outputTokens: sum(member => member.outputTokens),
|
||||
cacheReadTokens: sum(member => member.cacheReadTokens),
|
||||
cacheWriteTokens: sum(member => member.cacheWriteTokens),
|
||||
cacheReadTokens,
|
||||
cacheWriteTokens,
|
||||
cacheHitPercent: sessionCacheHitPercent(inputTokens, cacheReadTokens, cacheWriteTokens),
|
||||
startedAt,
|
||||
endedAt,
|
||||
durationMs: durationMs(startedAt, endedAt),
|
||||
|
|
@ -392,7 +408,7 @@ export function renderWorkUnitTable(rows: SessionRow[], resolution: WorkUnitReso
|
|||
const totalCost = entries.reduce((total, entry) => total + entry.display.row.cost, 0)
|
||||
const unitCount = entries.filter(entry => entry.display.childCount > 0).length
|
||||
const footer = `${rows.length.toLocaleString('en-US')} sessions \u2022 ${unitCount.toLocaleString('en-US')} work unit${unitCount === 1 ? '' : 's'} \u2022 $${totalCost.toFixed(2)} total \u2022 newest first${estimatedLegend(displays.map(d => d.row))}`
|
||||
return renderSessionGrid(sessionColumns(hasSavings, true), displays, workUnitCell, footer, available, ['children', 'turns', 'saved', 'provider', 'calls'])
|
||||
return renderSessionGrid(sessionColumns(hasSavings, true), displays, workUnitCell, footer, available, ['children', 'turns', 'saved', 'provider', 'calls', 'cache'])
|
||||
}
|
||||
|
||||
/// `sessions --by-work-unit --format json`: an add-only envelope. `sessions`
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { formatTokens, markEstimated } from './format.js'
|
|||
import { patchStdoutForWindows } from './ink-win.js'
|
||||
import { startUserTimingGuard } from './user-timing-guard.js'
|
||||
import {
|
||||
cacheHitLabel,
|
||||
cleanSessionProjectLabel,
|
||||
sessionDisplayName,
|
||||
sessionModelLabel,
|
||||
|
|
@ -17,7 +18,7 @@ const MUTED = '#71717A'
|
|||
const BORDER = '#3F3F46'
|
||||
|
||||
type Column = {
|
||||
key: 'started' | 'session' | 'project' | 'provider' | 'models' | 'cost' | 'calls' | 'turns'
|
||||
key: 'started' | 'session' | 'project' | 'provider' | 'models' | 'cost' | 'cache' | 'calls' | 'turns'
|
||||
label: string
|
||||
width: number
|
||||
right?: boolean
|
||||
|
|
@ -56,6 +57,7 @@ function columnsFor(width: number): Column[] {
|
|||
{ key: 'provider', label: 'PROVIDER', width: 9 },
|
||||
{ key: 'models', label: 'MODELS', width: 24 },
|
||||
{ key: 'cost', label: 'COST', width: 9, right: true },
|
||||
{ key: 'cache', label: 'CACHE', width: 6, right: true },
|
||||
{ key: 'calls', label: 'CALLS', width: 7, right: true },
|
||||
{ key: 'turns', label: 'TURNS', width: 7, right: true },
|
||||
]
|
||||
|
|
@ -106,6 +108,7 @@ function rowValue(row: SessionRow, key: Column['key']): string {
|
|||
case 'provider': return row.provider
|
||||
case 'models': return sessionModelLabel(row.models)
|
||||
case 'cost': return markEstimated(`$${row.cost.toFixed(2)}`, row.isEstimated)
|
||||
case 'cache': return cacheHitLabel(row.cacheHitPercent)
|
||||
case 'calls': return row.calls.toLocaleString('en-US')
|
||||
case 'turns': return row.turns.toLocaleString('en-US')
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue