fix(hermes): rebuild ledger cursors that double-counted reasoning

Hermes costs live in the session ledger, so the reasoning fix alone left
every recorded calculated cost overstated. Ledger v4 carries the v3 cursors
and marks those whose calculated observations hold reasoning tokens. The
next snapshot a still-present state.db row supplies replaces such a cursor
with one observation at the recomputed cost; the hermes parse version moves
so every session re-parses once and supplies that snapshot.

Sessions whose source row is gone get no snapshot and keep the v3 figure.
Days the daily cache already sealed also keep their old Hermes totals, as
no DAILY_CACHE_VERSION bump is part of this change.
This commit is contained in:
Resham Joshi 2026-11-06 04:49:02 -08:00
parent 1b775bfc01
commit 41a0651e72
3 changed files with 63 additions and 6 deletions

View file

@ -25,8 +25,14 @@ import type { CachedCall, ProviderSection } from './session-cache.js'
// v3 discards the local-only v2 migration candidate. Seeding v2 from the warm
// session cache could preserve lifetime totals while assigning historical
// observations to the migration day, inflating that day's scoped Hermes spend.
export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v3.json'
export const HERMES_SESSION_LEDGER_VERSION = 3 as const
// v4: the calculated basis stopped adding reasoning tokens on top of an output
// count that already holds them. A v3 cursor that priced reasoning that way is
// carried with `rebuild` set, and the next snapshot its source still supplies
// replaces it with one recomputed observation. A cursor whose source is gone
// gets no such snapshot and keeps the v3 figure.
export const HERMES_SESSION_LEDGER_FILENAME = 'hermes-session-ledger.v4.json'
export const HERMES_SESSION_LEDGER_VERSION = 4 as const
const HERMES_SESSION_LEDGER_V3_FILENAME = 'hermes-session-ledger.v3.json'
export type HermesCostBasis = 'actual' | 'estimated' | 'calculated' | 'included'
@ -57,6 +63,7 @@ export type HermesSessionCursor = {
sessionId: string
lastSeen: HermesLastSeen
observations: HermesObservation[]
rebuild?: true
}
export type HermesSessionLedger = {
@ -361,10 +368,10 @@ function validateCursor(v: unknown): v is HermesSessionCursor {
return true
}
function validateLedger(raw: unknown): raw is HermesSessionLedger {
function validateLedger(raw: unknown, version: number = HERMES_SESSION_LEDGER_VERSION): raw is HermesSessionLedger {
if (!raw || typeof raw !== 'object') return false
const o = raw as Record<string, unknown>
if (o['version'] !== HERMES_SESSION_LEDGER_VERSION) return false
if (o['version'] !== version) return false
if (!o['cursors'] || typeof o['cursors'] !== 'object' || Array.isArray(o['cursors'])) return false
for (const profileCursors of Object.values(o['cursors'] as Record<string, unknown>)) {
if (!profileCursors || typeof profileCursors !== 'object' || Array.isArray(profileCursors)) return false
@ -373,9 +380,31 @@ function validateLedger(raw: unknown): raw is HermesSessionLedger {
return true
}
function migrateV3Ledger(): HermesSessionLedger | null {
const path = join(getCodeburnCacheDir(), HERMES_SESSION_LEDGER_V3_FILENAME)
if (!existsSync(path)) return null
try {
const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'))
if (!validateLedger(parsed, 3)) return null
const cursors: HermesSessionLedger['cursors'] = {}
for (const [profile, sessions] of Object.entries(parsed.cursors)) {
cursors[profile] = {}
for (const [sessionId, cursor] of Object.entries(sessions)) {
const reasoningPriced = cursor.observations.some(o => o.costBasis === 'calculated' && o.reasoningTokens > 0)
cursors[profile][sessionId] = reasoningPriced ? { ...cursor, rebuild: true } : cursor
}
}
return { version: HERMES_SESSION_LEDGER_VERSION, cursors }
} catch {
return null
}
}
function readLedgerFromDisk(): HermesSessionLedger {
const path = hermesSessionLedgerPath()
if (!existsSync(path)) {
const migrated = migrateV3Ledger()
if (migrated) return migrated
// The v1 file is superseded and can never be read again: the parse-version
// bump forces a cold re-parse that rebuilds every cursor from source.
// Left behind it is dead bytes that only invite a future reader to trust
@ -448,7 +477,9 @@ export async function persistHermesSessionLedger(ledger: HermesSessionLedger): P
export async function recordHermesSnapshot(snapshot: HermesSnapshot): Promise<HermesSessionCursor> {
const ledger = loadHermesSessionLedger()
const existing = getHermesCursor(ledger, snapshot.profile, snapshot.sessionId)
const stored = getHermesCursor(ledger, snapshot.profile, snapshot.sessionId)
// An all-zero snapshot is a reset or a vanished row, not a source to rebuild from.
const existing = stored?.rebuild && hasPositiveTokenDelta(snapshot.tokens) ? undefined : stored
const { cursor, dirty } = applyHermesSnapshot(existing, snapshot)
if (dirty) await persistHermesSessionLedger(putCursor(ledger, cursor))
return cursor

View file

@ -539,7 +539,9 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// `billing` (`included` -> subscription, `actual` -> metered). Cached calls
// hold none, so they must re-parse.
// helper-usage-v1: auxiliary-model rows in session_model_usage now become calls.
hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-cost-provenance-v3-billing-route-v1-billing-mode-v1-helper-usage-v1',
// ledger-v4: sessions re-parse so v4 can rebuild the cursors whose calculated
// cost added reasoning on top of output.
hermes: 'reasoning-output-accounting-v1-est-cost-routed-ids-workspace-pr-v5-cost-provenance-v3-billing-route-v1-billing-mode-v1-helper-usage-v1-ledger-v4',
// reported-cost-v1: OpenClaw's per-message `usage.cost.total` is now
// preserved through the cache via `costFromBilling`. This is OpenClaw's
// first parse version; adding it moves the provider's env fingerprint,

View file

@ -547,6 +547,30 @@ skipUnlessSqlite('hermes provider', () => {
expect(billableOutputTokens('hermes', calls[0]!.outputTokens, calls[0]!.reasoningTokens)).toBe(200)
})
it('recomputes a v3 ledger cursor that priced reasoning on top of output, and keeps one whose source is gone', async () => {
const model = 'claude-sonnet-4-20250514'
const tokens = { inputTokens: 1000, outputTokens: 200, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 50 }
const v3Cursor = (sessionId: string, costUSD: number) => ({
profile: 'default', sessionId,
lastSeen: { ...tokens, costUSD, costBasis: 'calculated' },
observations: [{ index: 0, timestamp: '2026-05-23T12:33:20.000Z', ...tokens, costUSD, costBasis: 'calculated', supplementaryAccounting: false }],
})
await writeFile(join(cacheDir, 'hermes-session-ledger.v3.json'), JSON.stringify({
version: 3,
cursors: { default: { 'live-session': v3Cursor('live-session', calculateCost(model, 1000, 250, 0, 0, 0)), 'gone-session': v3Cursor('gone-session', 9.99) } },
}))
const dbPath = createHermesDb(tmpDir)
withTestDb(dbPath, (db) => {
insertSession(db, { id: 'live-session', model, ...tokens, estimatedCost: null, actualCost: null, startedAt: 1779539600 })
})
const live = await collectCalls(tmpDir, `${dbPath}#hermes-session=live-session`)
expect(live).toHaveLength(1)
expect(live[0]!.costUSD).toBe(calculateCost(model, 1000, 200, 0, 0, 0))
const gone = await collectCalls(tmpDir, `${dbPath}#hermes-session=gone-session`)
expect(gone.reduce((sum, call) => sum + call.costUSD, 0)).toBe(9.99)
})
it('carries the billing route the session recorded, and stays silent for every other door', async () => {
// billing_provider is the door the call went through; it was SELECTed and
// dropped before #1450. The direct `anthropic` door has no route: its row