From b0a42172fbfff681845d0b756d1883b21b058ece Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Mon, 24 Aug 2026 06:41:47 -0700 Subject: [PATCH] fix(daily-cache): never-lose guards for degraded parses and residue-only days MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Diagnosed via #1127. Three guards: - The gap-fill path no longer overwrites cached days wholesale: a complete parse wins per (date, provider) through the same guarded merge the re-derive path uses; a partial parse only fills days and slices the baseline lacks. Previously a parse degraded by the refresh lock (menubar running) could replace a good day with its undercount permanently. The gap path also stops dropping pendingRederive. - A day whose only content is turn-anchored residue (a midnight- straddling turn's category counts with zero cost/calls/tokens) is never sealed: the watermark pulls back so the next launch re-derives it — self-healing for every broken cache in the wild, no version bump. Bounded to the settle window and never for the oldest cached day. - codeburn doctor gains a read-only Cache health section listing residue-only dates and failed/empty session-cache entries, so the next report like #1127 is diagnosable in one command. Tests: residue-shape pin (day-aggregator), partial-gap cannot shrink a populated day (fails on the old code), complete-gap parity, watermark pull-back re-derive. --- src/daily-cache.ts | 51 ++++++++++- src/doctor.ts | 81 +++++++++++++++++ .../daily-cache-degraded-completeness.test.ts | 90 +++++++++++++++++++ tests/day-aggregator.test.ts | 60 +++++++++++++ 4 files changed, 280 insertions(+), 2 deletions(-) diff --git a/src/daily-cache.ts b/src/daily-cache.ts index 400806bc..5111e6b1 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -1179,6 +1179,15 @@ export function toDateString(date: Date): string { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` } +/// A day whose ONLY content is turn-anchored residue (one straddling turn's +/// category/edit counts, no calls) is not a derived day — it is a day the parse +/// under-read. Re-derive it instead of serving it. +export function isTurnResidueOnly(day: DailyEntry): boolean { + if (day.cost > 0 || day.calls > 0 || day.sessions > 0) return false + if (day.inputTokens + day.outputTokens + day.cacheReadTokens + day.cacheWriteTokens > 0) return false + return Object.values(day.categories).some(c => c.turns > 0) +} + export async function ensureCacheHydrated( parseSessions: (range: DateRange) => Promise, aggregateDays: (projects: ProjectSummary[]) => DailyEntry[], @@ -1241,6 +1250,34 @@ export async function ensureCacheHydrated( c = { ...c, lastComputedDate: newestCachedDate } } + // Never seal a residue-only day (issue #1127): a day whose only content is + // turn-anchored residue was under-read by the parse that produced it, so + // trust the DATA over the marker again — pull the watermark back to just + // before the oldest such day and let the ordinary gap parse re-derive it. + // This is what heals every already-broken cache on the next launch, with + // no version bump. + // + // Caveat: a day that GENUINELY held only one straddling turn and no other + // activity re-derives to the same residue shape and would be re-parsed on + // every launch. Bound that cost: skip the pull-back when the residue day + // is the oldest day in the cache, and only pull back inside the settle + // window — outside it the source files are gone and re-deriving cannot + // recover the day anyway. + const oldestCachedDate = c.days.reduce((min, d) => (min === null || d.date < min ? d.date : min), null) + const residueSettleCutoff = settleCutoffDate(now) + const oldestResidueDate = c.days.reduce( + (min, d) => (d.date >= residueSettleCutoff && d.date !== oldestCachedDate && isTurnResidueOnly(d) && (min === null || d.date < min) ? d.date : min), + null, + ) + if (oldestResidueDate !== null && c.lastComputedDate !== null && c.lastComputedDate >= oldestResidueDate) { + const pulledBack = new Date( + parseInt(oldestResidueDate.slice(0, 4)), + parseInt(oldestResidueDate.slice(5, 7)) - 1, + parseInt(oldestResidueDate.slice(8, 10)) - 1 + ) + c = { ...c, lastComputedDate: toDateString(pulledBack) } + } + // Three reasons to re-derive the whole retention window: // 1. Savings config changed — cached `savingsUSD` totals are stale. // 2. The cache was never finalized against a COMPLETE session parse (an old @@ -1354,7 +1391,17 @@ export async function ensureCacheHydrated( const gapDays = aggregateDays(gapProjects) const parseWasComplete = sessionComplete() const priorWatermark = c.lastComputedDate - c = addNewDays(c, gapDays, yesterdayStr) + // Gate the merge on parse completeness (issue #1127): replacing cached + // days wholesale with the gap parse's days let a PARTIAL parse overwrite + // a populated baseline day with its under-read version — and if the + // day's sources die before the next complete parse, the undercount is + // what survives. A complete parse still wins per (date, provider) + // exactly as the re-derive path does (partial-survival guarded); a + // partial one only fills days and slices the baseline lacks, so the gap + // merge is strictly additive and no cached data can shrink. + const merged = parseWasComplete + ? mergeDayEntries(gapDays, c.days, false, undefined, true) + : mergeDayEntries(c.days, gapDays, false) // Finalize as complete ONLY when the session parse that produced these days // was itself complete. If it was partial, leave `complete: false` so the // next launch (once the session cache is whole) re-backfills instead of @@ -1362,7 +1409,7 @@ export async function ensureCacheHydrated( // the same reason as the re-derive path above: a partial parse cannot // vouch for the days it never read, and gapStart is the only thing that // will ever bring them back. - c = { ...c, lastComputedDate: parseWasComplete ? c.lastComputedDate : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } + c = { ...c, days: applyRetention(merged, yesterdayStr), lastComputedDate: parseWasComplete ? yesterdayStr : priorWatermark, complete: parseWasComplete, watermarkTrusted: parseWasComplete } await saveDailyCache(c) } else if (c.complete !== true && sessionComplete()) { // No gap to fill (already current through yesterday) but not yet marked — diff --git a/src/doctor.ts b/src/doctor.ts index 95a3d44d..0f13a949 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -7,6 +7,7 @@ import { Chalk } from 'chalk' import { getClaudeConfigDirs } from './providers/claude.js' import { getAllProviders } from './providers/index.js' import type { Provider } from './providers/types.js' +import { dailyCachePath, isTurnResidueOnly, type DailyEntry } from './daily-cache.js' import { PROVIDER_ENV_VARS, PROVIDER_PARSE_VERSIONS, @@ -68,6 +69,24 @@ export type ClaudeRetentionNote = { settingsPath: string } +export type DoctorSessionCacheIssue = { + provider: string + /// Session-cache file key (the source path, including any virtual suffix). + path: string + reason: 'failed' | 'no-turns' +} + +export type DoctorCacheHealth = { + /// Daily-cache dates whose only content is turn-anchored residue — a day the + /// parse under-read (isTurnResidueOnly, issue #1127). ensureCacheHydrated + /// re-derives them on the next launch; they are listed here so the state is + /// visible without an archaeology dig. + residueOnlyDays: string[] + /// Session-cache entries flagged as parse failures or cached with zero + /// turns — the under-read entries residue days come from. + sessionCacheIssues: DoctorSessionCacheIssue[] +} + export type DoctorReport = { generatedAt: string providers: DoctorProviderReport[] @@ -75,6 +94,8 @@ export type DoctorReport = { /// found. Surfaced because deleted transcripts are unrecoverable: daily /// totals survive in CodeBurn's cache, but per-session detail does not. claudeRetention?: ClaudeRetentionNote + /// Present only when there is something to list. + cacheHealth?: DoctorCacheHealth } export type CollectDoctorOptions = { @@ -82,6 +103,8 @@ export type CollectDoctorOptions = { providers?: Provider[] /** Injectable cache snapshot (defaults to reading session-cache.json). */ cache?: SessionCache + /** Injectable daily-cache days (defaults to reading the daily cache file). */ + dailyCacheDays?: DailyEntry[] /** Max discovered sources to parse-sample per provider. */ sampleLimit?: number } @@ -334,6 +357,11 @@ export async function collectDoctorReport( const retention = await collectClaudeRetention() if (retention) report.claudeRetention = retention } + const residueOnlyDays = collectResidueOnlyDays(opts.dailyCacheDays ?? await readDailyCacheDays()) + const sessionCacheIssues = collectSessionCacheIssues(cache) + if (residueOnlyDays.length > 0 || sessionCacheIssues.length > 0) { + report.cacheHealth = { residueOnlyDays, sessionCacheIssues } + } return report } finally { if (prevSuppress === undefined) delete process.env['CODEBURN_SUPPRESS_CACHE_WRITES'] @@ -347,6 +375,45 @@ const CLAUDE_DEFAULT_CLEANUP_DAYS = 30 // the doctor line turns into a warning. const CLAUDE_RETENTION_WARN_DAYS = 365 +/// Read-only peek at the daily cache's days: loadDailyCache can WRITE +/// (adoption / migration), which doctor's read-only promise forbids, so the +/// file is read and parsed directly. Anything unreadable or foreign simply +/// yields no days — doctor must never crash on a corrupt cache. +async function readDailyCacheDays(): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(dailyCachePath(), 'utf-8')) + const days = (parsed as { days?: unknown } | null)?.days + if (!Array.isArray(days)) return [] + return days.filter((d): d is DailyEntry => !!d && typeof d === 'object' && typeof (d as DailyEntry).date === 'string') + } catch { + return [] + } +} + +function collectResidueOnlyDays(days: DailyEntry[]): string[] { + const out: string[] = [] + for (const d of days) { + try { + if (isTurnResidueOnly(d)) out.push(d.date) + } catch { + // Foreign junk in a hand-edited cache: skip the day, keep diagnosing. + } + } + return out.sort() +} + +function collectSessionCacheIssues(cache: SessionCache): DoctorSessionCacheIssue[] { + const out: DoctorSessionCacheIssue[] = [] + for (const [provider, section] of Object.entries(cache.providers)) { + for (const [path, f] of Object.entries(section.files)) { + // A failed entry carries no turns by construction; report it once, as failed. + if (f.failed) out.push({ provider, path, reason: 'failed' }) + else if (Array.isArray(f.turns) && f.turns.length === 0) out.push({ provider, path, reason: 'no-turns' }) + } + } + return out +} + async function collectClaudeRetention(): Promise { for (const dir of await getClaudeConfigDirs()) { const settingsPath = join(dir, 'settings.json') @@ -445,6 +512,20 @@ export function renderDoctorTable( } } + if (report.cacheHealth) { + out.push('') + out.push(c.bold('Cache health') + c.dim(' (issue #1127 diagnostics — under-read cache entries)')) + for (const date of report.cacheHealth.residueOnlyDays) { + out.push(' ' + c.yellow(date) + c.dim(' residue-only day (turn counts but no calls/cost); re-derived on next launch')) + } + for (const issue of report.cacheHealth.sessionCacheIssues) { + out.push( + ' ' + c.dim(`${issue.provider} `) + issue.path + + c.dim(issue.reason === 'failed' ? ' (cached parse failure)' : ' (cached with 0 turns)'), + ) + } + } + if (report.claudeRetention) { const r = report.claudeRetention const source = r.configured ? 'cleanupPeriodDays' : 'cleanupPeriodDays not set; Claude Code default' diff --git a/tests/daily-cache-degraded-completeness.test.ts b/tests/daily-cache-degraded-completeness.test.ts index d3df6cce..af7f2573 100644 --- a/tests/daily-cache-degraded-completeness.test.ts +++ b/tests/daily-cache-degraded-completeness.test.ts @@ -14,6 +14,7 @@ import { currentTzKey, ensureCacheHydrated, saveDailyCache, + toDateString, } from '../src/daily-cache.js' const TMP_CACHE_ROOT = join(tmpdir(), `codeburn-degraded-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`) @@ -185,3 +186,92 @@ describe('daily cache: a complete cache that outruns its own data is not trusted expect(out.complete).toBe(true) }) }) + +/// A day whose only content is turn-anchored residue: one straddling turn's +/// category counts, zero cost/calls/sessions/tokens (isTurnResidueOnly). +function residueDay(date: string): DailyEntry { + return day(date, {}, { + categories: { conversation: { turns: 1, cost: 0, savingsUSD: 0, editTurns: 0, oneShotTurns: 0 } }, + }) +} + +describe('daily cache: the gap path never shrinks a populated baseline day', () => { + // A populated baseline day inside the gap window (carried there by an older + // cache generation while the watermark sat behind it). The gap parse + // under-reads it: 5 calls / $5 where the baseline holds 500 / $50. + async function seedGapDay(): Promise { + await seed({ + days: [ + VANISHED, + day(daysAgoStr(4), { claude: slice(120, 900) }), + day(daysAgoStr(2), { claude: slice(50, 500), grok: slice(9, 60) }), + ], + }) + } + + it('a partial gap parse only fills what the baseline lacks', async () => { + await seedGapDay() + const underRead = [day(daysAgoStr(2), { claude: slice(5, 10) })] + const out = await ensureCacheHydrated(noSessions, () => underRead, 'cfg-A', () => false) + const kept = out.days.find(d => d.date === daysAgoStr(2))! + // Baseline wins wholesale: the partial parse's undercount must not replace it. + expect(kept.cost).toBe(59) + expect(kept.calls).toBe(560) + expect(kept.providers['claude']).toMatchObject({ cost: 50, calls: 500 }) + expect(kept.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + // Watermark held and not finalized, so a later complete parse re-covers the gap. + expect(out.lastComputedDate).toBe(daysAgoStr(4)) + expect(out.complete).toBe(false) + expectPreserved(out) + }) + + it('a complete gap parse still wins per (date, provider)', async () => { + await seedGapDay() + const fresh = [day(daysAgoStr(2), { claude: slice(75, 620) })] + const out = await ensureCacheHydrated(noSessions, () => fresh, 'cfg-A', () => true) + const rederived = out.days.find(d => d.date === daysAgoStr(2))! + // The fresh claude slice replaces the baseline one; the grok slice the + // parse did not produce is carried, not wiped. + expect(rederived.providers['claude']).toMatchObject({ cost: 75, calls: 620 }) + expect(rederived.providers['grok']).toMatchObject({ cost: 9, calls: 60 }) + expect(rederived.cost).toBe(84) + expect(rederived.calls).toBe(680) + expect(out.days.map(d => d.date)).toEqual([daysAgoStr(40), daysAgoStr(4), daysAgoStr(2)]) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + expectPreserved(out) + }) +}) + +describe('daily cache: a residue-only day is re-derived, not served', () => { + it('pulls the watermark back to just before the residue day so the gap parse re-derives it', async () => { + // The broken-cache shape issue #1127 leaves behind: complete and stamped, + // watermark at yesterday, and a residue-only day sealed behind it. The + // oldest-day exemption does not apply (an older populated day exists) and + // the residue day is inside the settle window. + await seed({ + lastComputedDate: daysAgoStr(1), + watermarkTrusted: true, + days: [day(daysAgoStr(10), { claude: slice(80, 700) }), residueDay(daysAgoStr(3))], + }) + const ranges: DateRange[] = [] + const rederived = [day(daysAgoStr(3), { claude: slice(33, 210) })] + const out = await ensureCacheHydrated( + async (range) => { ranges.push(range); return [] }, + () => rederived, + 'cfg-A', + () => true, + ) + // The watermark moved back to daysAgoStr(4), so the gap parse started on + // the residue day itself instead of skipping it forever. + expect(ranges).toHaveLength(1) + expect(toDateString(ranges[0]!.start)).toBe(daysAgoStr(3)) + const healed = out.days.find(d => d.date === daysAgoStr(3))! + expect(healed.providers['claude']).toMatchObject({ cost: 33, calls: 210 }) + expect(healed.cost).toBe(33) + expect(healed.calls).toBe(210) + expect(out.days.find(d => d.date === daysAgoStr(10))).toMatchObject({ cost: 80, calls: 700 }) + expect(out.lastComputedDate).toBe(daysAgoStr(1)) + expect(out.complete).toBe(true) + }) +}) diff --git a/tests/day-aggregator.test.ts b/tests/day-aggregator.test.ts index f561a877..874dee97 100644 --- a/tests/day-aggregator.test.ts +++ b/tests/day-aggregator.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { aggregateProjectsIntoDays, buildPeriodDataFromDays, dateKey } from '../src/day-aggregator.js' +import { isTurnResidueOnly } from '../src/daily-cache.js' import type { ProjectSummary } from '../src/types.js' function makeProject(overrides: Partial & { sessions: ProjectSummary['sessions'] }): ProjectSummary { @@ -220,6 +221,65 @@ describe('aggregateProjectsIntoDays', () => { expect(days[0]!.providers).toEqual({}) }) + it("pins the residue shape: a sliced straddling turn leaves turn counts but zero cost/calls on the anchor day", () => { + // The contract isTurnResidueOnly keys off (issue #1127). A history parse + // that ends at midnight slices a straddling turn to its in-range calls; + // when the surviving half carries the turn-level judgments (category, + // editTurns) onto day A but every call landed on day B, day A is left + // holding ONLY residue: categories.conversation.turns === 1 with + // cost/calls/sessions all 0. Construct in LOCAL time so the turn + // genuinely straddles local midnight on any machine TZ. + const iso = (y: number, mo: number, d: number, h: number, mi: number) => + new Date(y, mo, d, h, mi, 0).toISOString() + const turnTs = iso(2026, 3, 16, 23, 58) // day A, just before midnight + const callTs = iso(2026, 3, 17, 0, 5) // day B: every call past midnight + const dayA = dateKey(turnTs) + const dayB = dateKey(callTs) + expect(dayA).not.toBe(dayB) // sanity: the fixture really straddles local midnight + + const projects: ProjectSummary[] = [ + makeProject({ + sessions: [{ + sessionId: 's1', + project: 'p', + firstTimestamp: callTs, + lastTimestamp: callTs, + totalCostUSD: 6, + totalInputTokens: 0, totalOutputTokens: 0, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, + apiCalls: 1, + turns: [ + { + userMessage: 'one more thing before bed', timestamp: turnTs, sessionId: 's1', + category: 'conversation', retries: 0, hasEdits: false, + assistantCalls: [makeCall(callTs, 6)], + }, + ], + modelBreakdown: {}, toolBreakdown: {}, mcpBreakdown: {}, bashBreakdown: {}, + categoryBreakdown: {} as never, + skillBreakdown: {} as never, + }], + }), + ] + + const days = aggregateProjectsIntoDays(projects) + const anchor = days.find(d => d.date === dayA)! + const next = days.find(d => d.date === dayB)! + + // Anchor day: ONLY turn-anchored residue — no cost, calls, sessions, or tokens. + expect(anchor.cost).toBe(0) + expect(anchor.calls).toBe(0) + expect(anchor.sessions).toBe(0) + expect(anchor.inputTokens + anchor.outputTokens + anchor.cacheReadTokens + anchor.cacheWriteTokens).toBe(0) + expect(anchor.categories['conversation']!.turns).toBe(1) + expect(isTurnResidueOnly(anchor)).toBe(true) + + // Next day: the full cost/calls of the same turn. + expect(next.cost).toBe(6) + expect(next.calls).toBe(1) + expect(next.sessions).toBe(1) + expect(isTurnResidueOnly(next)).toBe(false) + }) + it('counts a session under its firstTimestamp date', () => { const projects: ProjectSummary[] = [ makeProject({