diff --git a/docs/design/perf-cache-fix.md b/docs/design/perf-cache-fix.md new file mode 100644 index 00000000..9a2b00f9 --- /dev/null +++ b/docs/design/perf-cache-fix.md @@ -0,0 +1,229 @@ +# Spec: fast-path snapshot for `codeburn status --format menubar-json` + +## Problem + +`codeburn status --format menubar-json` was measured taking 25-90+ seconds per +call, with **no speedup on a repeat call against an unchanged, freshly-warmed +cache**. The initial working hypothesis was a missing mtime/size gate ahead of +per-file content hashing. + +Direct re-investigation on the reporter's own machine (live `sample` +profiling of the installed `codeburn status --format menubar-json` binary +against the real ~386MB `session-cache.v7.json`) found: + +- The per-source-file change-detection gate hypothesized as missing + **already exists and is correct**: `reconcileFile`/`fingerprintFile` + in `src/session-cache.ts` compare `dev/ino/mtimeMs/sizeBytes` and skip + re-reading/re-hashing any unchanged source transcript. There is no + content-hashing step anywhere in that gate. +- The actual dominant, reproducible cost on a repeat call is **re-parsing the + entire monolithic on-disk session cache file itself** (`JSON.parse` of the + ~386MB blob showed as ~20% of sampled CPU time in isolation) plus **re-running + the full aggregation pipeline** (`buildMenubarPayloadForRange` in + `src/usage-aggregator.ts`: day-aggregation, optimize scan, PR/branch + attribution, model efficiency) over the entire requested period on every + call. +- Every existing in-memory reuse layer (`parser.ts`'s `sessionCache` Map + + `CACHE_TTL_MS`, `session-cache.ts`'s `cacheMemo`) is process-local. The + menubar app spawns a **fresh CLI process per poll**, so none of those layers + ever pay off for this command — each poll starts cold regardless of how + recently the identical query was answered. + +## Fix + +Add a small, disk-persisted **status snapshot** keyed by (a) a cheap, +content-free **corpus fingerprint** and (b) a serialization of the resolved +query. + +The corpus fingerprint is a stat-only pass (`discoverAllSessions` + +`fingerprintFile` per discovered source — the exact same `dev/ino/mtimeMs/ +sizeBytes` signal `reconcileFile` already uses per source transcript) hashed +into one string, with **no** `session-cache.json` read/parse and no +transcript content read. This is deliberately NOT a fingerprint of the +on-disk `session-cache.v*.json` file itself — that file only gets rewritten +*after* a real parse runs, so gating on its own fingerprint would only ever +change in response to a parse the gate is supposed to be allowed to skip, +permanently masking real source-file changes behind a stale snapshot (caught +by a first implementation attempt's own test: appending new session content +between two identical-query calls did not change the result). Fingerprinting +the discoverable sources directly avoids that trap. + +`codeburn status --format menubar-json` computes this fingerprint before +doing any parse/aggregation work; on a fingerprint+query match (or a +still-settling match, see Debounce below) it serves the persisted payload +directly (a handful of `stat()` calls, no `JSON.parse` of the corpus, no +aggregation). On any real mismatch (settled new session activity, or a +different query) it falls through to today's full computation and then +persists the new result for the next poll. + +One correctness subtlety caught while implementing this: Claude +`SessionSource.path` (from `discoverAllSessions`) is a **project directory**, +not a leaf transcript file — every other provider's `path` IS the leaf +file/DB it parses. A directory's own mtime only moves when an entry is +added/removed, not when an existing file inside it is rewritten in place, so +fingerprinting Claude sources at the directory level would miss real content +changes to files that already existed at discovery time. `computeCorpusFingerprint` +expands each Claude source to its actual `.jsonl` files first (the same +`collectJsonlFiles` walk `scanProjectDirs` already uses) before fingerprinting. + +## Debounce design decision + +Per operator direction: once a real corpus change is detected, don't +recompute/re-hash immediately — coalesce a rapidly-churning file (a streaming +assistant turn can touch its transcript many times a second) into one +recompute once things go quiet, rather than paying the full parse+aggregation +cost on every single poll of a burst. + +**Existing patterns checked first, as directed**, before inventing a new one: +- `parser.ts`'s `PROGRESS_SAVE_THROTTLE_MS` (5s) throttles partial-cache + saves during a cold hydration — a *throttle* (rate-limit repeated writes), + not a settle/debounce (wait for quiet before trusting a value). Different + problem shape. +- `parser.ts`'s `parseBurstWindowMs()` / `CODEBURN_PARSE_BURST_MS` — the + closest match in spirit and the one this fix's `statusSnapshotSettleMs()` + mirrors directly: a small, capped, env-overridable numeric knob computed + fresh from `process.env` on each call. +- `dashboard.tsx` has a UI-input debounce, but it's a `setTimeout`-based + interaction debounce scoped to one long-lived TUI process. `codeburn + status` is a fresh, short-lived CLI process per poll (that's the whole + reason the in-memory caches don't help it) — a `setTimeout` cannot survive + across separate process invocations, so a wall-clock **age** check (`Date.now() + - lastTouchedMs < window`) is the only mechanism that composes with a + stateless CLI. This is also exactly the idiom `cache-refresh-lock.ts` + already uses for lock staleness (`age = wallNow() - mtimeMs`), so it's a + mirror of that pattern, not a new one. + +**Where it was NOT put:** the first implementation attempt added the settle +check directly inside `reconcileFile` (deferring an 'appended'/'modified' +verdict on a fresh mtime by returning 'unchanged'). That combination has a +correctness bug: once the outer status-snapshot layer sees a real corpus +fingerprint change, it recomputes via the full pipeline — but if +`reconcileFile` itself defers and reports 'unchanged' for the still-fresh +file, the recompute produces the SAME (stale) result, which then gets +persisted under the NEW corpus fingerprint. Because the outer snapshot only +ever compares fingerprints (not wall-clock time), that stale result would +then be served **forever** for that fingerprint — the settle window would +never get a chance to expire and trigger a real re-read, since nothing +would make the fingerprint change again without a further write. Caught by +this fix's own test before landing. `reconcileFile` was reverted to its +original, unmodified form. + +**Where it actually lives:** entirely inside the status-snapshot layer this +fix already introduces, which is the one place with the wall-clock context +needed to expire correctly: +- `computeCorpusFingerprint` now also returns `newestMtimeMs` — the newest + mtime observed across every discovered source in that pass (0 when there + are none). +- `session-cache.ts`'s `loadStatusSnapshot(corpusFingerprint, newestMtimeMs, + queryKey)`: on a fingerprint mismatch (real change detected), if + `Date.now() - newestMtimeMs < statusSnapshotSettleMs()` it still returns + the stored (pre-change) payload — deferred, not stale-forever, because the + caller is told NOT to persist a new snapshot in that case (the old + baseline survives on disk). The very next poll after writes actually + stop — once the freshest file's mtime ages past the window — sees the + same fingerprint mismatch with no grace period left, recomputes for real, + and persists the settled result. No update is ever masked permanently, it + is only ever delayed by at most the window. +- **Interval chosen: 2000ms**, env-overridable via + `CODEBURN_STATUS_SNAPSHOT_SETTLE_MS` (capped at 60_000ms, mirroring + `CODEBURN_PARSE_BURST_MS`'s cap). Rationale: long enough to coalesce a + streaming turn's rapid successive appends into one recompute; short enough + that the menubar's displayed numbers don't visibly lag a user's real + activity by more than ~2s. This is a tunable UX judgment call, not hard + science — flagged explicitly for review. + +## Scope + +- `src/parser.ts`: add `computeCorpusFingerprint(providerFilter?)` — reuses + the already-imported `discoverAllSessions` and `fingerprintFile`, plus the + already-defined `collectJsonlFiles` for the Claude directory-expansion + case above. Returns `{ hash, newestMtimeMs }`. +- `src/session-cache.ts`: add `loadStatusSnapshot(corpusFingerprint, + newestMtimeMs, queryKey)` / `saveStatusSnapshot(corpusFingerprint, + newestMtimeMs, queryKey, payload)` and the `statusSnapshotSettleMs()` knob + (one `status-snapshot..json` file per distinct query in the + cache dir — so concurrent callers with different queryKeys never evict + each other — atomic temp+rename write with a CAS re-read guard against a + slower/older write clobbering a newer one, best-effort — a failed read/ + write just falls back to a full recompute). `reconcileFile` is unchanged. +- `src/main.ts`: in the `status` command's `--format menubar-json` branch, + build a query key from the resolved period/day/days range, provider, + project/exclude filters, optimize/timeline flags, and Claude config source; + check the snapshot before calling `buildMenubarPayloadForRange`, and save + after a real (non-deferred) compute. The `--scope combined` device-pull + enrichment stays live (uncached) on every call — it is not the reported + bottleneck and already has its own best-effort fallback. +- Not touched: `buildMenubarPayloadForRange` internals, `reconcileFile`, the + `devices` command (different call site, not the reported symptom), + `--format json`/`terminal` status output (not the menubar's polled path). + +## Acceptance + +- Given an unchanged on-disk session corpus and an identical query, a second + `codeburn status --format menubar-json` call returns byte-identical output + to the first, sourced from the snapshot (no corpus re-parse). +- Given new session activity between two calls, a call made while the change + is still within the settle window is deferred (serves the last settled + snapshot); a call made once the change has aged past the window reflects + the new data. The snapshot never serves stale results indefinitely. +- `--scope combined` vs `--scope local` from the same underlying query still + differ only in the `combined` field; `local` never gains a stray `combined` + key from a prior `combined` call's snapshot (the snapshot never stores the + live device-enrichment result). + +## Secondary finding: dual kqueue watches on `/` + +Scoping call: **out of scope for this fix, filed as a separate follow-up.** +This investigation could not confirm this as a cause of the latency (flat FD +count over an 8s observation window) and it is orthogonal to the cache +read/write path this fix touches — it would live in whichever file-watch +setup code owns the fs-watcher init (not `session-cache.ts`), and needs its +own `fs_usage`/`dtrace` reproduction under `sudo`, which wasn't available in +this session either. No code change made for it here. + +## Reconciliation with the resident `serve --stdio` process + +This fix originally targeted a genuine gap: a fresh CLI spawn per menubar poll +had no cross-process reuse story at all. That premise changed after this was +opened — `src/serve.ts` now keeps a resident query server warm for the +desktop app, with a request-level `outputMemo` (capped at 5 minutes, cleared +on any config-fingerprint change) validated by root filesystem watchers +(`startRootWatchers`/`classifyRootReuse`), and falls back to a fresh CLI spawn +only when that in-process path is unavailable or refuses the command. + +Decision: **keep this disk snapshot**, scoped explicitly to that fallback +spawn path (and any other one-shot invocation of `status --format +menubar-json` outside the desktop app's `serve` connection), rather than drop +it. Reasoning: + +- `serve`'s memo is in-process and per-server-lifetime; it buys nothing for an + actual CLI spawn, which is a brand-new process with no memo to hit. The + disk snapshot is the only thing standing between that spawn and paying the + full parse+aggregation cost — exactly the case `serve.ts`'s own module + comment documents as the fallback it exists to catch. +- The concern that motivated re-examining this at all — "a second, weaker + cache whose invalidation rules lose to `serve`'s whenever it hits first" — + is addressed by the five correctness fixes in this revision (pricing-config + hash parity with `parser.ts`'s `cacheKey`, a synthetic fingerprint for + network providers, generic directory-shaped-source expansion, gating the + save on `isSessionHydrationComplete()`, and anchoring the settle-window + defer on wall-clock first-mismatch time instead of the corpus-wide newest + mtime). With those fixed, the snapshot's own freshness check + (`computeCorpusFingerprint`, an eager stat sweep over every discovered + source on every call) is not weaker than `serve`'s watcher-based heuristic + — if anything it is strictly more precise, since it re-runs discovery and + re-stats rather than trusting `fs.watch` coverage that has documented blind + spots (a root created after the watcher armed, a missed FSEvents + coalescence). `serve`'s 5-minute hard cap exists as defense-in-depth + against exactly those watcher blind spots; the disk snapshot doesn't need + an equivalent hard cap because it isn't exposed to that failure mode in the + first place. +- No commits upstream of this branch's merge base touch the status-snapshot + code path (`loadStatusSnapshot`/`saveStatusSnapshot`/`statusSnapshotSettleMs` + in `src/session-cache.ts`, or the `status --format menubar-json` handler in + `src/main.ts`) — the two upstream cache commits in that range + (`fix(cache): stop republishing month shards a scoped run never read`, + `cache: CODEBURN_CACHE_SCOPE=all forces a full shard read`) are both scoped + to `saveCache`/`loadCache`'s month-shard mechanics, a different layer of + `session-cache.ts` entirely. No further rebase-driven reconciliation is + needed beyond the fixes above. diff --git a/package.json b/package.json index d0bf6970..a4c24c16 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "build:dash": "cd dash && npm install --no-audit --no-fund --silent && npm run build", "dev": "NODE_OPTIONS=--no-deprecation tsx src/cli.ts", "test": "vitest run tests --exclude \"tests/cache-refresh-lock*\"", - "test:locks": "vitest run tests/cache-refresh-lock.test.ts tests/cache-refresh-lock-corrupt-body.test.ts tests/cache-refresh-lock-process.test.ts --poolOptions.forks.singleFork=true", + "test:locks": "vitest run tests/cache-refresh-lock.test.ts tests/cache-refresh-lock-corrupt-body.test.ts tests/cache-refresh-lock-process.test.ts tests/cache-refresh-lock-status-snapshot.test.ts --poolOptions.forks.singleFork=true", "test:watch": "vitest tests --exclude \"tests/cache-refresh-lock*\"", "verify:upgrade": "node scripts/upgrade-path/run.mjs", "prepublishOnly": "npm run build" diff --git a/src/cache-refresh-lock.ts b/src/cache-refresh-lock.ts index da287122..02f3d41d 100644 --- a/src/cache-refresh-lock.ts +++ b/src/cache-refresh-lock.ts @@ -6,7 +6,6 @@ import { join } from 'path' import { getCodeburnCacheDir } from './cache-dir.js' const LOCK_FILE = 'session-refresh.lock' -const TAKEOVER_FILE = `${LOCK_FILE}.takeover` const DEFAULT_HEARTBEAT_MS = 10_000 const DEFAULT_STALE_MS = 90_000 // A waiter that gives up before the stale gate opens can NEVER recover an @@ -28,6 +27,9 @@ export type RefreshLockClock = { export type RefreshLockOptions = { cacheDir?: string + /** Basename only. Lets independent cache transactions reuse this lock + * protocol without unnecessarily serializing each other. */ + lockFile?: string clock?: RefreshLockClock heartbeatMs?: number staleMs?: number @@ -71,18 +73,20 @@ function pidLooksAlive(pid: number): boolean { catch (err) { return (err as NodeJS.ErrnoException).code === 'EPERM' } } -// The path of the lock this process currently owns, for the signal handler. -// Single-flight guarantees at most one owned lock per process at a time. -let ownedLockPath: string | null = null +// Paths of locks this process currently owns, for the signal handler. The +// in-process single-flight is per lock path, so independent cache transactions +// may legitimately hold different locks at the same time. +const ownedLockPaths = new Set() // Synchronous variant for the signal path: a handler can't await, so read + // unlink synchronously. Only unlinks a lock we actually own. function removeOurLockSync(): void { - if (!ownedLockPath) return - try { - const parsed = JSON.parse(readFileSync(ownedLockPath, 'utf-8')) as Partial - if (parsed?.pid === process.pid) unlinkSync(ownedLockPath) - } catch { /* best-effort; nothing to clean or already gone */ } + for (const lockPath of [...ownedLockPaths]) { + try { + const parsed = JSON.parse(readFileSync(lockPath, 'utf-8')) as Partial + if (parsed?.pid === process.pid) unlinkSync(lockPath) + } catch { /* best-effort; nothing to clean or already gone */ } + } } // Arm once, only while we hold the lock: on a catchable termination (Ctrl-C, or @@ -222,14 +226,18 @@ function sameObservation(a: Observation, b: Observation): boolean { return a.record?.token === b.record?.token && a.mtimeMs === b.mtimeMs && a.digest === b.digest } -let singleFlightTail: Promise = Promise.resolve() +const singleFlightTails = new Map>() -async function enterSingleFlight(): Promise<() => void> { - const previous = singleFlightTail +async function enterSingleFlight(lockPath: string): Promise<() => void> { + const previous = singleFlightTails.get(lockPath) ?? Promise.resolve() let leave!: () => void - singleFlightTail = new Promise(resolve => { leave = resolve }) + const current = new Promise(resolve => { leave = resolve }) + singleFlightTails.set(lockPath, current) await previous - return leave + return () => { + leave() + if (singleFlightTails.get(lockPath) === current) singleFlightTails.delete(lockPath) + } } /** @@ -237,7 +245,16 @@ async function enterSingleFlight(): Promise<() => void> { * Lock ordering, when the daily-cache follow-up lands, is daily → session. */ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): Promise { - const leaveSingleFlight = await enterSingleFlight() + const cacheDir = options.cacheDir ?? getCodeburnCacheDir() + const lockFile = options.lockFile ?? LOCK_FILE + // Never allow a caller-controlled path to escape cacheDir or collide with + // the takeover suffix. All current callers use fixed names or a hex digest. + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$/.test(lockFile) || lockFile.endsWith('.takeover')) { + return { outcome: 'unavailable' } + } + const lockPath = join(cacheDir, lockFile) + const takeoverPath = join(cacheDir, `${lockFile}.takeover`) + const leaveSingleFlight = await enterSingleFlight(lockPath) let ownsSingleFlight = true const leave = (): void => { if (!ownsSingleFlight) return @@ -245,15 +262,12 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): leaveSingleFlight() } - const cacheDir = options.cacheDir ?? getCodeburnCacheDir() const clock = options.clock ?? defaultClock const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS const staleMs = options.staleMs ?? DEFAULT_STALE_MS const waitMs = options.waitMs ?? staleMs + DEFAULT_WAIT_MARGIN_MS const pollMs = options.pollMs ?? DEFAULT_POLL_MS const sleep = options.sleep ?? delay - const lockPath = join(cacheDir, LOCK_FILE) - const takeoverPath = join(cacheDir, TAKEOVER_FILE) const token = randomBytes(16).toString('hex') const body = (): string => JSON.stringify({ pid: process.pid, token, at: clock.wallNow() }) @@ -345,7 +359,7 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): const makeHandle = (): RefreshLockHandle => { let released = false let heartbeatRunning = false - ownedLockPath = lockPath + ownedLockPaths.add(lockPath) armSignalCleanup() const heartbeat = setInterval(() => { void serializeOwnerOp(async () => { @@ -390,11 +404,14 @@ export async function acquireCacheRefreshLock(options: RefreshLockOptions = {}): release: async () => { if (released) return released = true - ownedLockPath = null clearInterval(heartbeat) - while (heartbeatRunning) await sleep(1) - await removeIfOwned() - leave() + try { + while (heartbeatRunning) await sleep(1) + await removeIfOwned() + } finally { + ownedLockPaths.delete(lockPath) + leave() + } }, } } diff --git a/src/main.ts b/src/main.ts index eecb834b..105654f5 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,13 +2,14 @@ import { isAbsolute } from 'path' import { Command, Option } from 'commander' import { installMenubarApp } from './menubar-installer.js' import { exportCsv, exportJson, type PeriodExport } from './export.js' -import { findUnpricedModels, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setFlatRateModels, setFlatRateRemoved, setProxyPaths, normalizeProxyPath, unpricedModelHint, isBuiltInFlatRateModel, isSameFlatRateModel } from './models.js' -import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI } from './parser.js' +import { findUnpricedModels, loadPricing, sanitizeModelForDisplay, setModelAliases, setPriceOverrides, setLocalModelSavings, setFlatRateModels, setFlatRateRemoved, setProxyPaths, normalizeProxyPath, unpricedModelHint, isBuiltInFlatRateModel, isSameFlatRateModel, getProxyPathsConfigHash, getModelAliasesConfigHash, getPriceOverridesConfigHash, getLocalModelSavingsConfigHash, getFlatRateModelsConfigHash, getPricingGenerationKey } from './models.js' +import { parseAllSessions, filterProjectsByName, filterProjectsByDateRange, clearSessionCache, setInteractiveScanUI, computeCorpusFingerprint, isSessionHydrationComplete } from './parser.js' import { allProviderNames, getAllProviders } from './providers/index.js' import { getProvider } from './providers/index.js' +import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js' import { convertCost, formatCost } from './currency.js' import { renderStatusBar } from './format.js' -import { toDateString } from './daily-cache.js' +import { DAILY_CACHE_VERSION, toDateString } from './daily-cache.js' import { dateKey } from './day-aggregator.js' import { sessionModelBillableOutputTokens } from './session-output.js' import { isBehavioralCall } from './behavioral-weight.js' @@ -16,6 +17,7 @@ import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory import type { AppliedFix } from './act/types.js' import { aggregateModelEfficiency } from './model-efficiency.js' import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, type DurablePeriod } from './usage-aggregator.js' +import { loadStatusSnapshot, saveStatusSnapshot } from './session-cache.js' import { renderDashboard } from './dashboard.js' import { renderOverview } from './overview.js' import { runWebDashboard } from './web-dashboard.js' @@ -49,6 +51,11 @@ import { createRequire } from 'node:module' const require = createRequire(import.meta.url) const { version } = require('../package.json') +// Bump when the menubar payload's rendering semantics change without a package +// release or daily-cache version change. The envelope version in session-cache +// protects record shape; this protects the meaning of an otherwise valid one. +const STATUS_SNAPSHOT_RENDER_VERSION = 1 +const STATUS_SNAPSHOT_SEMANTIC_KEY = `${version}:render-${STATUS_SNAPSHOT_RENDER_VERSION}:daily-${DAILY_CACHE_VERSION}` import { loadCurrency, getCurrency, isValidCurrencyCode } from './currency.js' import { CodexThroughputReader, newestCodexSession, renderCodexThroughput } from './codex-throughput.js' @@ -1104,15 +1111,98 @@ program : customRange ? { range: customRange, label: formatDateRangeLabel(opts.from, opts.to) } : daySelection ?? getDateRange(opts.period) - const payload = await buildMenubarPayloadForRange(periodInfo, { + // Fast path: the menubar app spawns this exact command fresh on every + // poll tick, so nothing in-process (parser.ts's TTL/burst caches, + // session-cache.ts's cacheMemo) ever survives between polls. A cheap + // stat-only pass (no session-cache.json parse, no transcript content + // read) over the discoverable corpus tells us whether anything changed + // since the last identical query; when it hasn't — or the only thing + // that changed is still within loadStatusSnapshot's settle window and + // may still be mid-write — skip the full parse + aggregation pipeline + // entirely and serve the persisted snapshot instead. + // Single source of truth for the fields that define the query scope, + // shared between the cache key below and the payload builder options + // — a field added to only one of the two would otherwise silently + // desync the cache from what it's supposed to be keying on. + const queryScope = { provider: pf, project: opts.project, exclude: opts.exclude, - daysSelection, optimize: opts.optimize !== false, timeline: opts.timeline !== false, - claudeConfigSourceId: opts.claudeConfigSource, + claudeConfigSourceId: opts.claudeConfigSource ?? null, + } + // The selector renders source labels/options derived from ordered Claude + // roots, including idle sources. Config order can change those labels + // without moving any transcript file, so it belongs to the query key + // (not the debounced corpus mismatch path). + const claudeSourceTopology = { + configDirs: await getClaudeConfigDirs(), + desktopSessionDirs: getDesktopSessionsDirs(), + } + const queryKey = JSON.stringify({ + start: periodInfo.range.start.toISOString(), + end: periodInfo.range.end.toISOString(), + label: periodInfo.label, + ...queryScope, + days: daysSelection ? [...daysSelection.days].sort() : undefined, + claudeSourceTopology, + // Mirrors parser.ts's cacheKey: pricing-affecting config must + // invalidate this snapshot the same way it invalidates the + // parse-level memo, or an edited alias/override/savings config keeps + // serving costs priced under the old config until something + // unrelated moves the corpus fingerprint. + proxyPathsConfigHash: getProxyPathsConfigHash(), + modelAliasesConfigHash: getModelAliasesConfigHash(), + priceOverridesConfigHash: getPriceOverridesConfigHash(), + localModelSavingsConfigHash: getLocalModelSavingsConfigHash(), + flatRateModelsConfigHash: getFlatRateModelsConfigHash(), + // Same reasoning, different config: the rendered payload's costs are + // in the ACTIVE display currency (see `getCurrency`/`loadCurrency`, + // refreshed fresh from config.json by the `preAction` hook ahead of + // this handler), which the corpus fingerprint and the config hashes + // above never touch. Without this, switching currencies keeps + // serving the old currency's numbers until a session file happens to + // change too. + currency: getCurrency(), + // Upstream/bundled pricing DATA and CODE version, as opposed to the + // hashes above (user-editable pricing CONFIG): the live LiteLLM + // cache's freshness, the bundled snapshot's own content, and the + // parser/pricing logic's semantic version. None of these move the + // corpus fingerprint or any config hash, so without this a repricing + // fetch or a pricing-logic fix can keep serving old rendered costs + // indefinitely against an unchanged session corpus. + pricingGenerationKey: getPricingGenerationKey(), }) + // Optimize findings (the default; see --no-optimize) depend on mutable + // project/config/prompt/hook state — ~/.claude and project-level + // settings.json, CLAUDE.md, defined skills/agents/commands, MCP config + // — that computeCorpusFingerprint and queryKey never observe and that + // has no single enumerable fingerprint. Persisting THIS class of output + // would mean editing a hook or removing an unused skill leaves the + // menubar showing stale findings with no session change to ever + // invalidate them. Simplest correct fix: the optimize path never reads + // or writes the disk snapshot at all, it always recomputes fresh. + // (Computing scanAndDetect's findings requires the same parsed project + // data the snapshot exists to avoid recomputing, so skipping the + // snapshot loses no additional work versus fingerprinting these inputs + // — that path would still force a fresh parse to re-scan them.) + const useSnapshot = !queryScope.optimize + const corpus = useSnapshot ? await computeCorpusFingerprint(pf) : null + const snapshot = corpus ? await loadStatusSnapshot(corpus.hash, queryKey, STATUS_SNAPSHOT_SEMANTIC_KEY) : null + const payload = (snapshot ?? await buildMenubarPayloadForRange(periodInfo, { + ...queryScope, + daysSelection, + })) as Awaited> + // A read-only parse that had to serve stale/skip real files + // (isSessionHydrationComplete() === false) is a knowingly-degraded + // result. Persisting it under the CURRENT (already-advanced) corpus + // fingerprint would make that degraded answer look authoritative to + // every future poll that matches this fingerprint — never checkpoint a + // partial hydration as if it were a real, complete parse. + if (useSnapshot && corpus && !snapshot && isSessionHydrationComplete()) { + await saveStatusSnapshot(corpus.hash, corpus.newestMtimeMs, corpus.observedAtMs, queryKey, STATUS_SNAPSHOT_SEMANTIC_KEY, payload) + } if (opts.scope === 'combined') { // Combined multi-device usage is best-effort enrichment on the menubar's // hot path. Never let pulling peers (or a corrupt remotes store) take diff --git a/src/models.ts b/src/models.ts index 775d680e..b7eac224 100644 --- a/src/models.ts +++ b/src/models.ts @@ -1,5 +1,6 @@ import { readFile, writeFile, mkdir } from 'fs/promises' import { join } from 'path' +import { createHash } from 'crypto' import { getCodeburnCacheDir } from './cache-dir.js' import snapshotData from './data/litellm-snapshot.json' with { type: 'json' } @@ -67,7 +68,10 @@ const CACHE_TTL_MS = 24 * 60 * 60 * 1000 // added in #1075/#1078). A cache written under an older/missing version is treated as a // miss instead of read verbatim, so a stale on-disk file can't reintroduce a killed bug // for up to CACHE_TTL_MS after an upgrade. -const CACHE_SCHEMA_VERSION = 2 +// Also folded into getPricingGenerationKey() below: a resident/snapshot-caching +// consumer needs the same "pricing behavior changed" signal this already gives +// the on-disk LiteLLM cache, not just the on-disk cache itself. +export const CACHE_SCHEMA_VERSION = 2 const WEB_SEARCH_COST = 0.01 const ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE = 1.6 @@ -209,6 +213,16 @@ export function parseLiteLLMEntry(entry: LiteLLMEntry): ModelCosts | null { ) } +// Timestamp of whichever live LiteLLM data (freshly fetched or read back from +// the on-disk cache) is currently loaded into pricingCache; null when nothing +// live is loaded and pricing is purely the bundled snapshot (offline/first +// run, CODEBURN_PRICING_SNAPSHOT_ONLY, or a failed fetch with no cache hit). +// Read by getPricingGenerationKey() so a consumer that persists rendered +// costs across process invocations (the menubar's status snapshot) can tell +// "the live pricing data actually changed" apart from "nothing changed" — +// this module has no other way to signal that across a fresh CLI process. +let livePricingTimestamp: number | null = null + async function fetchAndCachePricing(): Promise> { // Bounded: runs on every CLI invocation (the menubar shells out and blocks on // it). Without a timeout a half-open network after wake-from-sleep makes @@ -230,12 +244,14 @@ async function fetchAndCachePricing(): Promise> { if (stripped !== name && !pricing.has(stripped)) pricing.set(stripped, costs) } + const timestamp = Date.now() await mkdir(getCodeburnCacheDir(), { recursive: true }) await writeFile(getCachePath(), JSON.stringify({ version: CACHE_SCHEMA_VERSION, - timestamp: Date.now(), + timestamp, data: Object.fromEntries(pricing), })) + livePricingTimestamp = timestamp return pricing } @@ -246,6 +262,7 @@ async function loadCachedPricing(): Promise | null> { const cached = JSON.parse(raw) as { version?: number; timestamp: number; data: Record } if (cached.version !== CACHE_SCHEMA_VERSION) return null if (Date.now() - cached.timestamp > CACHE_TTL_MS) return null + livePricingTimestamp = cached.timestamp return new Map(Object.entries(cached.data)) } catch { return null @@ -277,6 +294,7 @@ export async function loadPricing(): Promise { // tests/setup/env-isolation.ts: skip the live LiteLLM fetch and price purely // off the bundled snapshot, so an upstream reprice can't turn tests red. if (process.env['CODEBURN_PRICING_SNAPSHOT_ONLY']) { + livePricingTimestamp = null setPricingCache(mergeSnapshotFallbacks(new Map())) return } @@ -285,9 +303,41 @@ export async function loadPricing(): Promise { setPricingCache(mergeSnapshotFallbacks(await fetchAndCachePricing())) } catch { // snapshot already loaded at init; nothing more to do + livePricingTimestamp = null } } +// Content digest of the two bundled pricing files, computed once and memoized +// (they're static imports; nothing in-process can change them). Changes only +// when `scripts/bundle-litellm.mjs` regenerates litellm-snapshot.json / +// pricing-fallback.json and that regeneration ships in a new codeburn build — +// exactly the "bundled data" staleness class getPricingGenerationKey exists +// to catch, distinct from the live cache's own timestamp. +let bundledPricingDigest: string | null = null +function getBundledPricingDigest(): string { + if (bundledPricingDigest === null) { + bundledPricingDigest = createHash('sha256') + .update(JSON.stringify(snapshotData)) + .update(JSON.stringify(fallbackData)) + .digest('hex') + } + return bundledPricingDigest +} + +/// Stable signature of everything that can silently change a session's +/// RENDERED cost with no session file ever changing: the live LiteLLM cache's +/// freshness (a repricing fetch, or its absence), the bundled snapshot's own +/// content (a repriced model shipped in a new build), and this module's +/// pricing-behavior version (CACHE_SCHEMA_VERSION). A caller that persists a +/// fully-rendered payload across process invocations (the menubar's status +/// snapshot) must fold this into its own cache key the same way it already +/// folds the four *ConfigHash getters above — those cover user-editable +/// pricing CONFIG, this covers upstream/bundled pricing DATA and code version, +/// a different staleness gap with no other invalidation path of its own. +export function getPricingGenerationKey(): string { + return `${CACHE_SCHEMA_VERSION}:${livePricingTimestamp ?? 'bundled'}:${getBundledPricingDigest()}` +} + // Known model name variants that providers emit but LiteLLM/fallback don't index under. // OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last). // getCanonicalName strips a KNOWN vendor/router prefix first unless the diff --git a/src/parser.ts b/src/parser.ts index 572b7cdf..98c956a6 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1,5 +1,7 @@ import { existsSync } from 'fs' import { lstat, readFile, readdir, stat } from 'fs/promises' +import { createHash } from 'crypto' +import { performance } from 'node:perf_hooks' import { basename, dirname, join, resolve, sep } from 'path' import { FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from './fs-utils.js' import { billableOutputTokens, calculateCost, calculateLocalModelSavings, getShortModelName, isProxiedPath, getProxyPathsConfigHash, getModelAliasesConfigHash, getPriceOverridesConfigHash, getLocalModelSavingsConfigHash } from './models.js' @@ -41,7 +43,7 @@ import { decideParseWorkers, parseFilesInOrder, ParseWorkerPool, type ClaudeWork import type { CodexFullParse } from './providers/codex.js' import { dateKey } from './day-aggregator.js' import { isBehavioralCall, isBehavioralTurn } from './behavioral-weight.js' -import type { ParsedProviderCall, SessionSource } from './providers/types.js' +import type { ParsedProviderCall, Provider, SessionSource } from './providers/types.js' import type { ApiUsageIteration, AssistantMessageContent, @@ -4761,6 +4763,163 @@ let sessionFirstPaintDeferred = false // chart (gapStart = lastComputedDate + 1 never looks back at them). let readOnlyServedStale = false +export type CorpusFingerprint = { + /** High-resolution epoch time captured before discovery begins. Competing + * snapshot writers use it as an observation-order fence. */ + observedAtMs: number + /** Content-free signature of every discovered source's dev/ino/mtime/size. */ + hash: string + /** Newest mtime observed across all discovered sources, 0 when there are + * none. Lets a caller tell "definitely changed" apart from "may still be + * mid-write" without re-stat'ing anything itself. */ + newestMtimeMs: number +} + +// Generic counterpart to `collectJsonlInto`: every regular file under a +// directory, any extension, recursively. Used to expand a directory-shaped +// SessionSource for fingerprinting purposes only — not for parsing, which +// stays with each provider's own (narrower, extension-aware) file layout +// knowledge. Being over-inclusive here is safe: an extra file in the hash +// can only cause an extra cache miss, never a missed update. +async function collectFilesRecursive(dirPath: string, visitedDirs: Set = new Set()): Promise { + const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []) + const files: string[] = [] + for (const entry of entries) { + const p = join(dirPath, entry.name) + if (entry.isDirectory()) { + files.push(...await collectFilesRecursive(p, visitedDirs)) + continue + } + if (entry.isSymbolicLink()) { + // `Dirent.isDirectory()` is false for a symlink even when its target + // IS a directory — without this check a symlinked subdirectory falls + // into the `else` below and gets pushed as a leaf "file"; a later + // `stat()` (which follows symlinks) then returns the DIRECTORY + // inode's own mtime/size as a bogus stand-in for its contents, with no + // recursion into it at all (review finding C-G2). Resolve it and + // recurse for real. A visited-inode guard bounds the walk against a + // symlink cycle (impossible for real directories, which is why the + // `isDirectory()` branch above needs no such guard). + const target = await stat(p).catch(() => null) + if (target?.isDirectory()) { + const key = `${target.dev}:${target.ino}` + if (visitedDirs.has(key)) continue + visitedDirs.add(key) + files.push(...await collectFilesRecursive(p, visitedDirs)) + continue + } + } + files.push(p) + } + return files +} + +// Cheap, content-free signature of "has anything in the discoverable session +// corpus changed since the last check" — a stat-only pass (readdir + stat per +// discovered source; no session-cache.json read/parse, no transcript content +// read) hashed into one string, plus the newest mtime seen along the way. +// Order-independent (sorted before hashing) so discovery order never causes a +// spurious miss. Lets a fresh, short-lived CLI invocation (e.g. a menubar +// poll) cheaply decide whether it can skip the full parse+aggregation +// pipeline and serve a persisted result instead, without ever needing to +// `JSON.parse` the (potentially hundreds-of-MB) session cache file just to +// answer that question. +// +// Claude `SessionSource.path` is a project DIRECTORY, not a leaf transcript +// (see `scanProjectDirs`/`collectJsonlFiles` above) — every other provider's +// path IS the leaf file/DB it parses, with two exceptions. Fingerprinting a +// directory itself would miss an in-place rewrite of an existing file inside +// it: a directory's own mtime only moves when entries are added or removed, +// not when one of its files' content changes. So: +// - Claude sources are expanded to their actual `.jsonl` files first, exactly +// the way scanProjectDirs discovers them, and each is fingerprinted +// individually. +// - Any OTHER directory-shaped source (e.g. mistral-vibe, whose parser reads +// `join(source.path, 'messages.jsonl')`) gets the same treatment via a +// generic recursive file walk — this is deliberately NOT gated on provider +// name, so it also covers whatever directory-shaped provider shows up +// next instead of repeating the same blind spot one provider at a time. +// - Network providers (e.g. Vercel AI Gateway) have no on-disk file at all — +// see the `provider.network` branch below, mirroring parseAllSessions' +// own treatment of the same sources in `parseProviderSources`. +export async function computeCorpusFingerprint(providerFilter?: string): Promise { + const observedAtMs = performance.timeOrigin + performance.now() + const sources = await discoverAllSessions(providerFilter) + const entries: string[] = [] + let newestMtimeMs = 0 + const record = async (path: string): Promise => { + const fp = await fingerprintFile(path) + if (!fp) return + entries.push(`${path}|${fp.dev}|${fp.ino}|${fp.mtimeMs}|${fp.sizeBytes}`) + if (fp.mtimeMs > newestMtimeMs) newestMtimeMs = fp.mtimeMs + } + // Cache the provider lookup per name — sources routinely repeat a provider + // many times over (one per Claude project dir, one per mistral-vibe + // session dir, ...) and getProvider() can be a dynamic-import round-trip. + const providerByName = new Map() + const resolveProvider = async (name: string): Promise => { + if (!providerByName.has(name)) providerByName.set(name, await getProvider(name)) + return providerByName.get(name) + } + // Non-discovery provider env vars (e.g. CODEBURN_CURSOR_MAX_BUBBLES, + // KIMI_MODEL_NAME — src/doctor.ts's NON_DISCOVERY_ENV_VARS) and a + // provider's parse-version change PARSED OUTPUT without touching any + // source's path/mtime/size, so the stat-only loop below would otherwise + // never see them move. `computeEnvFingerprint` (session-cache.ts) already + // hashes exactly this per provider for the parse-level cache; fold it in + // here too, once per distinct provider actually discovered, so this + // higher-layer snapshot fingerprint can't bypass that same guard (review + // finding A-G1). + const envFingerprinted = new Set() + for (const source of sources) { + // Discovery metadata is itself rendered state. Claude's config selector, + // for example, assigns duplicate-basename labels by configured root order + // and exposes a config as soon as it has even an empty project directory. + // Hashing only transcript files (then sorting them) made those topology + // changes invisible when no file path/mtime/size moved, so a status + // snapshot could retain stale source labels/options indefinitely. + entries.push(`source:${JSON.stringify([ + source.provider, + source.path, + source.project, + source.sourceKind ?? null, + source.sourceId ?? null, + source.sourceLabel ?? null, + source.sourcePath ?? null, + source.retainWhilePresent ?? false, + ])}`) + if (!envFingerprinted.has(source.provider)) { + envFingerprinted.add(source.provider) + entries.push(`env:${source.provider}|${computeEnvFingerprint(source.provider)}`) + } + if (source.provider === 'claude') { + for (const filePath of await collectJsonlFiles(source.path)) await record(filePath) + continue + } + const provider = await resolveProvider(source.provider) + if (provider?.network) { + // No file to fingerprint. Force a miss (and advance newestMtimeMs) + // every call instead of silently contributing nothing to the hash — + // the parser re-fetches network sources unconditionally on every real + // parse, and a snapshot layer sitting in front of that must not be + // able to hide the run that would have done the fetching. + const now = Date.now() + entries.push(`${source.path}|network|${now}`) + if (now > newestMtimeMs) newestMtimeMs = now + continue + } + const info = await stat(source.path).catch(() => null) + if (info?.isDirectory()) { + for (const filePath of await collectFilesRecursive(source.path)) await record(filePath) + continue + } + await record(source.path) + } + entries.sort() + const hash = createHash('sha256').update(entries.join('\n')).digest('hex') + return { hash, newestMtimeMs, observedAtMs } +} + // Set when a changed source's read was deferred on a retryable failure (e.g. // a SQLITE_BUSY store): the parse completed but did not hydrate that source's // new data, so the run must not report hydration complete even in write mode. diff --git a/src/providers/cline-cli.ts b/src/providers/cline-cli.ts index f4db02bc..568d0dfa 100644 --- a/src/providers/cline-cli.ts +++ b/src/providers/cline-cli.ts @@ -242,10 +242,14 @@ async function readJson(path: string): Promise { function createParser(source: SessionSource, seenKeys: Set): SessionParser { return { async *parse(): AsyncGenerator { - const meta = await readJson(source.path) + // `source.path` is the growing `.messages.json` file (see + // `discoverSessions` / review finding C-G1) — the static per-session + // metadata lives in the sibling `.json`, read below. + const metaPath = source.path.replace(/\.messages\.json$/, '.json') + const meta = await readJson(metaPath) if (!isRecord(meta)) return - const sessionId = nonEmptyString(meta['session_id']) ?? basename(source.path).replace(/\.json$/, '') + const sessionId = nonEmptyString(meta['session_id']) ?? basename(metaPath).replace(/\.json$/, '') const metadata = isRecord(meta['metadata']) ? meta['metadata'] : {} const workspace = nonEmptyString(meta['workspace_root']) ?? nonEmptyString(meta['cwd']) const sessionModel = nonEmptyString(meta['model']) ?? 'unknown' @@ -254,10 +258,10 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars // display name, so there is nothing left to default to here. const project = source.project - // Prefer the co-located messages file over the recorded absolute path, - // which is stale once a session directory is copied between machines. - const sibling = join(source.path.replace(/\.json$/, '') + '.messages.json') - let doc = await readJson(sibling) + // Prefer the co-located messages file (source.path itself) over a + // recorded absolute path, which is stale once a session directory is + // copied between machines. + let doc = await readJson(source.path) if (!isRecord(doc)) { const recorded = nonEmptyString(meta['messages_path']) if (recorded) doc = await readJson(recorded) @@ -398,9 +402,16 @@ export function createClineCliProvider(overrideDir?: string): Provider { const meta = await readJson(metaPath) if (!isRecord(meta)) continue + // Fingerprint the sibling that actually accumulates new turns, not + // the metadata file written once at session start — a live session's + // corpus fingerprint must move as new turns append, or a menubar + // poll can serve the pre-activity snapshot forever (review finding + // C-G1). `computeCorpusFingerprint` degrades this to "contributes + // nothing yet" if the messages file doesn't exist (a session with no + // turns), the same as any other missing/not-yet-created file. const workspace = nonEmptyString(meta['workspace_root']) ?? nonEmptyString(meta['cwd']) sources.push({ - path: metaPath, + path: join(dir, sessionId, `${sessionId}.messages.json`), project: projectName(workspace), provider: PROVIDER_NAME, }) diff --git a/src/session-cache.ts b/src/session-cache.ts index 672c46eb..7d2f7e46 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -4,6 +4,7 @@ import { createHash, randomBytes } from 'crypto' import { join } from 'path' import { getCodeburnCacheDir } from './cache-dir.js' +import { acquireCacheRefreshLock } from './cache-refresh-lock.js' import type { ToolCall } from './types.js' // ── Types ────────────────────────────────────────────────────────────── @@ -1515,9 +1516,16 @@ export async function cleanupOrphanedTempFiles(): Promise { // `session-cache.v.json..tmp` from a pre-v8 binary interrupted // mid-write. Age-guarded, so an old binary's in-flight write is left alone. + // `status-snapshot..json..tmp` (see + // writeStatusSnapshotRecord below — one file per queryKey) is swept here + // too: it lives in this same parent dir, orthogonal to the month-shard + // layout below, so the shard-dir sweep further down never sees it. Same + // atomic temp+rename pattern, same narrow crash window between the write + // and the rename as the versioned cache file above. try { for (const entry of await readdir(parent)) { - if (!/^session-cache\.v\d+\.json\..*\.tmp$/.test(entry)) continue + if (!entry.endsWith('.tmp')) continue + if (!/^session-cache\.v\d+\.json\./.test(entry) && !entry.startsWith(`${STATUS_SNAPSHOT_FILE}.`)) continue await unlinkIfOlderThan(join(parent, entry), TEMP_FILE_MAX_AGE_MS, now) } } catch {} @@ -1694,3 +1702,270 @@ export async function beginColdHydration(isCold: boolean): Promise= 0 ? Math.min(raw, 60_000) : 2000 +} + +const STATUS_SNAPSHOT_FILE = 'status-snapshot' + +// Bump on any incompatible change to the *shape* of the payload this snapshot +// persists (i.e. whenever `buildMenubarPayloadForRange`'s return shape +// changes) or to this record's own envelope fields. Without this, an on-disk +// snapshot written by an older binary would be blindly cast and served +// verbatim by a newer one on a corpus-fingerprint+query match — the payload +// shape has no other correctness gate, unlike the main session cache, which +// already guards exactly this class of drift via `CACHE_VERSION`/ +// `validateCache`. A version mismatch is treated as a miss (same as a +// missing/corrupt file): the caller recomputes for real and persists a fresh, +// current-shaped snapshot. +// +// v2 (was v1): the file is now keyed by `queryKey` in its NAME (see +// `statusSnapshotPath` below) instead of being one shared slot — two +// concurrent callers with different queryKeys (a menubar poll for "today" +// racing a manual refresh for "week") used to unconditionally evict each +// other's save. A v1 file at the old fixed path is simply never looked at +// again under v2 (harmless leftover, not actively cleaned). +// +// v3: every record carries the binary/render semantic key and the high- +// resolution time at which its corpus scan began. The latter is the ordering +// fence for competing writers: max(file mtime) is not monotonic because +// deleting the newest file legitimately makes it decrease. +const STATUS_SNAPSHOT_VERSION = 3 + +type StatusSnapshotRecord = { + version: number + semanticKey: string + corpusFingerprint: string + newestMtimeMs: number + observedAtMs: number + // Kept alongside the hash in the filename as a defensive re-check against + // a (vanishingly unlikely) hash collision between two different queries. + queryKey: string + payload: unknown + // Wall-clock time (Date.now()) the FIRST mismatch against this record's + // corpusFingerprint was observed. Absent = not currently mismatched (a + // fresh save, or a record no load has mismatched against yet). This is + // what the settle-window decision anchors on — see `loadStatusSnapshot`. + mismatchFirstSeenAt?: number +} + +// Each distinct queryKey gets its OWN file (`status-snapshot..json`) +// rather than sharing one slot — see the v2 note above / review finding +// B-G1's "amplifier." This means two writers for different queryKeys never +// touch each other's file at all, so there is no read-merge-write race to +// close between them (a shared-map-file design was tried and demonstrably +// races: two concurrent writers for different keys can each read before +// either has written, then each overwrite the whole file with only their +// own key — verified by a failing test before this per-file design replaced +// it). +function statusSnapshotHash(queryKey: string): string { + return createHash('sha256').update(queryKey).digest('hex').slice(0, 16) +} + +function statusSnapshotPath(queryKey: string): string { + const hash = statusSnapshotHash(queryKey) + return join(getCodeburnCacheDir(), `${STATUS_SNAPSHOT_FILE}.${hash}.json`) +} + +function statusSnapshotLockFile(queryKey: string): string { + return `${STATUS_SNAPSHOT_FILE}.${statusSnapshotHash(queryKey)}.write.lock` +} + +async function readStatusSnapshotRecord(queryKey: string): Promise { + try { + const raw = await readFile(statusSnapshotPath(queryKey), 'utf-8') + const parsed = JSON.parse(raw) as Partial + if ( + parsed.version !== STATUS_SNAPSHOT_VERSION || + typeof parsed.semanticKey !== 'string' || + typeof parsed.corpusFingerprint !== 'string' || + typeof parsed.newestMtimeMs !== 'number' || !Number.isFinite(parsed.newestMtimeMs) || + typeof parsed.observedAtMs !== 'number' || !Number.isFinite(parsed.observedAtMs) || + parsed.queryKey !== queryKey + ) return null + return parsed as StatusSnapshotRecord + } catch { + return null + } +} + +/** Shared best-effort atomic writer for both `saveStatusSnapshot` (a fresh, + * settled recompute) and `loadStatusSnapshot`'s own bookkeeping write (a + * first-observed-mismatch timestamp, so the settle clock survives across + * the one-shot processes that call this — each CLI poll is a fresh process + * with no in-memory state to carry it). A failed write just means the next + * poll recomputes, or re-observes the mismatch as if it were first, instead + * of reusing/deferring — never stale or corrupt data either way. + * + * The guard/read/write/rename transaction runs under a per-query cross- + * process lock. A pre-rename re-read alone is not a CAS: two processes can + * both pass it before either renames, after which the older writer is free to + * land last. The lock makes that decision and publication one atomic critical + * section while distinct query keys remain independent. */ +async function writeStatusSnapshotRecord( + queryKey: string, + record: StatusSnapshotRecord, + guard: (existing: StatusSnapshotRecord | null) => boolean, +): Promise { + const dir = getCodeburnCacheDir() + try { + if (!existsSync(dir)) await mkdir(dir, { recursive: true }) + } catch { + return false + } + + // A waiter reports `completed-by-other` when the owner releases cleanly. + // Writers still need their own critical section to evaluate their guard, so + // retry acquisition a bounded number of times instead of treating another + // writer's completion as ours. + for (let attempt = 0; attempt < 3; attempt++) { + const lock = await acquireCacheRefreshLock({ + cacheDir: dir, + lockFile: statusSnapshotLockFile(queryKey), + waitMs: 2_000, + pollMs: 10, + }) + if (lock.outcome === 'completed-by-other') continue + if (lock.outcome !== 'acquired') return false + + let tempPath: string | null = null + try { + const finalPath = statusSnapshotPath(queryKey) + const existing = await readStatusSnapshotRecord(queryKey) + if (!guard(existing)) return false + tempPath = `${finalPath}.${randomBytes(8).toString('hex')}.tmp` + const handle = await open(tempPath, 'w', 0o600) + try { + await handle.writeFile(JSON.stringify(record), { encoding: 'utf-8' }) + await handle.sync() + } finally { + await handle.close() + } + // Fail closed if takeover or an I/O fault displaced us before publish. + if (!await lock.handle.verifyStillOwner()) return false + await rename(tempPath, finalPath) + tempPath = null + return true + } catch { + return false + } finally { + if (tempPath) await unlink(tempPath).catch(() => {}) + await lock.handle.release().catch(() => {}) + } + } + return false +} + +/** Returns the previously-saved payload when the query still matches AND + * either the corpus fingerprint is an exact match (nothing changed) or this + * mismatch was first observed less than `statusSnapshotSettleMs()` of + * wall-clock time ago (likely still being written). Null otherwise, so the + * caller recomputes for real and should persist a fresh snapshot with the + * new fingerprint. + * + * Deliberately does NOT use `newestMtimeMs` (the corpus-wide max mtime) to + * decide how long a mismatch has been "recent": that value is the max + * across every discovered source, so churn in a file the current query + * never reads (a different project, or a network-provider source that + * `computeCorpusFingerprint` deliberately re-stamps to "now" every call so + * it never drops out of the hash) can keep it perpetually fresh, deferring + * forever instead of "at most the window." Anchoring on the wall-clock time + * THIS record's fingerprint first stopped matching makes the settle window + * a true bound regardless of what else in the corpus is busy. */ +export async function loadStatusSnapshot(corpusFingerprint: string, queryKey: string, semanticKey: string): Promise { + const stored = await readStatusSnapshotRecord(queryKey) + if (!stored) return null + if (stored.semanticKey !== semanticKey) return null + if (stored.corpusFingerprint === corpusFingerprint) return stored.payload ?? null + + const now = Date.now() + const firstSeenAt = stored.mismatchFirstSeenAt ?? now + if (now - firstSeenAt >= statusSnapshotSettleMs()) return null + if (stored.mismatchFirstSeenAt === undefined) { + // Bookkeeping-only write: only proceed if the on-disk record is exactly + // what we just read (same corpusFingerprint, still no + // mismatchFirstSeenAt). If a concurrent real recompute already replaced + // it, this stale payload must not be reintroduced under a + // freshly-stamped timestamp. + const basisFingerprint = stored.corpusFingerprint + const persisted = await writeStatusSnapshotRecord( + queryKey, + { ...stored, mismatchFirstSeenAt: firstSeenAt }, + existing => existing !== null + && existing.semanticKey === semanticKey + && existing.corpusFingerprint === basisFingerprint + && existing.observedAtMs === stored.observedAtMs + && existing.mismatchFirstSeenAt === undefined, + ) + // Serving stale is safe only when the first-observed timestamp is durable. + // Otherwise each short-lived CLI process starts a fresh grace window and a + // read-only or broken cache can serve the old payload forever. + if (!persisted) return null + } + return stored.payload ?? null +} + +/** Best-effort: a failed write just means the next poll recomputes instead + * of reusing. Only ever called by the caller when `loadStatusSnapshot` + * missed, so a settled recompute's result should supersede whatever was + * there before — UNLESS a concurrent recompute already published one based + * on a strictly fresher corpus observation (`observedAtMs`), in which case + * this (slower, now-stale) write is refused rather than clobbering it. Ties + * proceed: both reflect a correct recompute of the same corpus state. Always + * writes a fresh record with no `mismatchFirstSeenAt`, which is exactly what + * clears the settle-window clock once a real recompute lands. */ +export async function saveStatusSnapshot( + corpusFingerprint: string, + newestMtimeMs: number, + observedAtMs: number, + queryKey: string, + semanticKey: string, + payload: unknown, +): Promise { + return writeStatusSnapshotRecord( + queryKey, + { version: STATUS_SNAPSHOT_VERSION, semanticKey, corpusFingerprint, newestMtimeMs, observedAtMs, queryKey, payload }, + existing => !existing + || existing.semanticKey !== semanticKey + || existing.observedAtMs < observedAtMs + || (existing.observedAtMs === observedAtMs && existing.corpusFingerprint === corpusFingerprint), + ) +} diff --git a/tests/cache-refresh-lock-status-snapshot.test.ts b/tests/cache-refresh-lock-status-snapshot.test.ts new file mode 100644 index 00000000..d36eef79 --- /dev/null +++ b/tests/cache-refresh-lock-status-snapshot.test.ts @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { spawn, type ChildProcess } from 'child_process' +import { createHash } from 'crypto' +import { existsSync } from 'fs' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' + +import { saveStatusSnapshot } from '../src/session-cache.js' + +const roots: string[] = [] + +async function waitFor(path: string, timeoutMs = 10_000): Promise { + const deadline = Date.now() + timeoutMs + while (!existsSync(path)) { + if (Date.now() >= deadline) throw new Error(`timed out waiting for ${path}`) + await new Promise(resolve => { setTimeout(resolve, 5) }) + } +} + +function waitForExit(child: ChildProcess): Promise { + if (child.exitCode !== null) { + return child.exitCode === 0 ? Promise.resolve() : Promise.reject(new Error(`worker exited ${child.exitCode}`)) + } + return new Promise((resolve, reject) => { + let stderr = '' + child.stderr?.on('data', chunk => { stderr += String(chunk) }) + child.once('error', reject) + child.once('exit', code => code === 0 ? resolve() : reject(new Error(`worker exited ${code}: ${stderr}`))) + }) +} + +function worker(cacheDir: string, barriers: string, role: 'fresh' | 'stale', rounds: number): ChildProcess { + return spawn(process.execPath, [ + '--import', + 'tsx', + join(process.cwd(), 'tests/fixtures/status-snapshot-writer.ts'), + cacheDir, + barriers, + role, + String(rounds), + ], { cwd: process.cwd(), stdio: ['ignore', 'ignore', 'pipe'] }) +} + +function recordPath(cacheDir: string, queryKey: string): string { + const hash = createHash('sha256').update(queryKey).digest('hex').slice(0, 16) + return join(cacheDir, `status-snapshot.${hash}.json`) +} + +afterEach(async () => { + delete process.env['CODEBURN_CACHE_DIR'] + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) +}) + +describe('status snapshot child-process write lock', () => { + it('never lets the older observation win a same-query publication race', async () => { + const rounds = 20 + const root = await mkdtemp(join(tmpdir(), 'cb-status-snapshot-lock-')) + roots.push(root) + const cacheDir = join(root, 'cache') + const barriers = join(root, 'barriers') + await mkdir(cacheDir, { recursive: true }) + await mkdir(barriers, { recursive: true }) + process.env['CODEBURN_CACHE_DIR'] = cacheDir + + for (let round = 0; round < rounds; round++) { + await saveStatusSnapshot( + `baseline-${round}`, + 1_000, + 1_000, + `child-query-${round}`, + 'child-process-render-v1', + { role: 'baseline', round }, + ) + } + + const fresh = worker(cacheDir, barriers, 'fresh', rounds) + const stale = worker(cacheDir, barriers, 'stale', rounds) + for (let round = 0; round < rounds; round++) { + await Promise.all([ + waitFor(join(barriers, `fresh.${round}.ready`)), + waitFor(join(barriers, `stale.${round}.ready`)), + ]) + await writeFile(join(barriers, `${round}.go`), '') + await Promise.all([ + waitFor(join(barriers, `fresh.${round}.done`)), + waitFor(join(barriers, `stale.${round}.done`)), + ]) + } + await Promise.all([waitForExit(fresh), waitForExit(stale)]) + + for (let round = 0; round < rounds; round++) { + const record = JSON.parse(await readFile(recordPath(cacheDir, `child-query-${round}`), 'utf-8')) as { + corpusFingerprint: string + payload: { role: string; round: number } + } + expect(record).toMatchObject({ + corpusFingerprint: `fresh-${round}`, + payload: { role: 'fresh', round }, + }) + } + expect((await readdir(cacheDir)).filter(name => name.endsWith('.tmp') || name.endsWith('.lock'))).toEqual([]) + }) +}) diff --git a/tests/cache-refresh-lock.test.ts b/tests/cache-refresh-lock.test.ts index c452afe7..4cf2235a 100644 --- a/tests/cache-refresh-lock.test.ts +++ b/tests/cache-refresh-lock.test.ts @@ -127,6 +127,25 @@ describe('warm session-cache refresh lock', () => { } }) + it('allows independent custom lock names to proceed concurrently', async () => { + const dir = await tempDir() + const first = await acquireCacheRefreshLock({ cacheDir: dir, lockFile: 'status-snapshot.aaaa.write.lock' }) + expect(first.outcome).toBe('acquired') + if (first.outcome !== 'acquired') return + + const second = await acquireCacheRefreshLock({ cacheDir: dir, lockFile: 'status-snapshot.bbbb.write.lock' }) + expect(second.outcome).toBe('acquired') + if (second.outcome === 'acquired') await second.handle.release() + await first.handle.release() + }) + + it('rejects custom lock paths that could escape the cache directory', async () => { + const dir = await tempDir() + for (const lockFile of ['../outside.lock', '/tmp/outside.lock', 'nested/lock', 'x.takeover']) { + expect(await acquireCacheRefreshLock({ cacheDir: dir, lockFile })).toEqual({ outcome: 'unavailable' }) + } + }) + it('does not take over a heartbeating owner', async () => { const dir = await tempDir() const path = lockPath(dir) diff --git a/tests/cli-status-menubar.test.ts b/tests/cli-status-menubar.test.ts index 292385da..85a5bb03 100644 --- a/tests/cli-status-menubar.test.ts +++ b/tests/cli-status-menubar.test.ts @@ -1,9 +1,20 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { existsSync, readdirSync, statSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter as pathDelimiter, join } from 'node:path' import { spawnSync } from 'node:child_process' import { describe, expect, it, vi } from 'vitest' +import { CACHE_SCHEMA_VERSION } from '../src/models.js' + +// Each distinct query gets its own `status-snapshot..json` file +// (review finding B-G1) rather than one shared fixed path — these tests +// don't know the hash up front, so they locate whatever landed by pattern. +const SNAPSHOT_FILE_RE = /^status-snapshot\.[0-9a-f]+\.json$/ +function findSnapshotFiles(cacheDir: string): string[] { + if (!existsSync(cacheDir)) return [] + return readdirSync(cacheDir).filter(f => SNAPSHOT_FILE_RE.test(f)).map(f => join(cacheDir, f)) +} // Every case here spawns the real CLI and does genuine multi-provider parse // work; the 5s default is fine on a dev laptop and not on a shared 2-core @@ -35,7 +46,7 @@ function userLine(sessionId: string, timestamp: string): string { }) } -function assistantLine(sessionId: string, timestamp: string, messageId: string): string { +function assistantLine(sessionId: string, timestamp: string, messageId: string, model = 'claude-sonnet-4-5'): string { return JSON.stringify({ type: 'assistant', sessionId, @@ -44,7 +55,7 @@ function assistantLine(sessionId: string, timestamp: string, messageId: string): id: messageId, type: 'message', role: 'assistant', - model: 'claude-sonnet-4-5', + model, content: [ { type: 'text', text: 'done' }, { type: 'tool_use', id: 'tu-1', name: 'Edit', input: { file_path: '/tmp/x', old_string: 'a', new_string: 'b' } }, @@ -345,6 +356,66 @@ describe('codeburn status --format menubar-json', () => { } }) + it('invalidates the snapshot when ordered Claude config topology changes', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-claude-topology-')) + + try { + // The two roots deliberately share a basename. Their user-visible labels + // are disambiguated by configured order ("profile 1" / "profile 2"), + // while their transcript paths and contents stay unchanged. + const firstRoot = join(home, 'account-a', 'profile') + const secondRoot = join(home, 'account-b', 'profile') + await mkdir(join(firstRoot, 'projects', 'first'), { recursive: true }) + await mkdir(join(secondRoot, 'projects', 'second'), { recursive: true }) + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000)) + const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z') + await writeFile( + join(firstRoot, 'projects', 'first', 'first.jsonl'), + [userLine('first', ts(0)), assistantLine('first', ts(60_000), 'msg-first')].join('\n'), + ) + await writeFile( + join(secondRoot, 'projects', 'second', 'second.jsonl'), + [userLine('second', ts(120_000)), assistantLine('second', ts(180_000), 'msg-second')].join('\n'), + ) + + const configDir = join(home, '.config', 'codeburn') + const configPath = join(configDir, 'config.json') + await mkdir(configDir, { recursive: true }) + await writeFile(configPath, JSON.stringify({ claudeConfigDirs: [firstRoot, secondRoot] })) + const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'all', '--no-optimize'] + // Empty env values select config.json instead of runCli's default single + // CLAUDE_CONFIG_DIR, and remain identical across both invocations. + const env = { CLAUDE_CONFIG_DIR: '', CLAUDE_CONFIG_DIRS: '' } + + const before = runCli(args, home, env) + expect(before.status, `stderr: ${before.stderr}`).toBe(0) + const beforePayload = JSON.parse(before.stdout) as { + claudeConfigs?: { options: Array<{ label: string; path: string }> } + } + expect(Object.fromEntries(beforePayload.claudeConfigs!.options.map(option => [option.path, option.label]))).toEqual({ + [firstRoot]: 'profile 1', + [secondRoot]: 'profile 2', + }) + + // Only config order changes. The broken fingerprint sorted transcript + // paths and ignored source labels, so it served the first snapshot. + await writeFile(configPath, JSON.stringify({ claudeConfigDirs: [secondRoot, firstRoot] })) + const after = runCli(args, home, env) + expect(after.status, `stderr: ${after.stderr}`).toBe(0) + const afterPayload = JSON.parse(after.stdout) as { + claudeConfigs?: { options: Array<{ label: string; path: string }> } + } + expect(Object.fromEntries(afterPayload.claudeConfigs!.options.map(option => [option.path, option.label]))).toEqual({ + [firstRoot]: 'profile 2', + [secondRoot]: 'profile 1', + }) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + it('rejects --claude-config-source combined with a non-Claude --provider', async () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-cfg-provider-')) try { @@ -649,6 +720,196 @@ describe('codeburn status --format menubar-json', () => { } }) + it('serves a repeat identical query from the status snapshot, debounces a fresh change, then reflects it once settled', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-snapshot-')) + + try { + const projectDir = join(home, '.claude', 'projects', 'myapp') + await mkdir(projectDir, { recursive: true }) + + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000)) + const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z') + + await writeFile( + join(projectDir, 'session.jsonl'), + [userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1')].join('\n'), + ) + + const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'all', '--no-optimize'] + + const first = runCli(args, home) + expect(first.status, `stderr: ${first.stderr}`).toBe(0) + const firstPayload = JSON.parse(first.stdout) as { current: { calls: number } } + expect(firstPayload.current.calls).toBe(1) + + // The persisted snapshot carries cost/usage aggregates and project + // paths, so it must land group/world-unreadable regardless of umask. + const snapshotFiles = findSnapshotFiles(join(home, '.cache', 'codeburn')) + expect(snapshotFiles).toHaveLength(1) + expect(statSync(snapshotFiles[0]!).mode & 0o777).toBe(0o600) + + // Identical query against an unchanged corpus: served from the + // snapshot, byte-identical to the first call. + const second = runCli(args, home) + expect(second.status, `stderr: ${second.stderr}`).toBe(0) + expect(second.stdout).toBe(first.stdout) + + // New session activity moves the corpus fingerprint. A call made right + // after — still well inside the (large, forced) settle window — must + // debounce: the freshly-touched file may still be mid-write, so it + // keeps serving the last SETTLED snapshot rather than recomputing on + // every tick of a burst. + await writeFile( + join(projectDir, 'session.jsonl'), + [ + userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1'), + userLine('s1', ts(120_000)), assistantLine('s1', ts(180_000), 'msg-2'), + ].join('\n'), + ) + const debounced = runCli(args, home, { CODEBURN_STATUS_SNAPSHOT_SETTLE_MS: '60000' }) + expect(debounced.status, `stderr: ${debounced.stderr}`).toBe(0) + expect(debounced.stdout).toBe(first.stdout) + + // Once the change is treated as settled (forcing the window to 0), the + // very next call must reflect it — the debounce only ever delays + // picking up a real update, it never masks one permanently. + const settled = runCli(args, home, { CODEBURN_STATUS_SNAPSHOT_SETTLE_MS: '0' }) + expect(settled.status, `stderr: ${settled.stderr}`).toBe(0) + const settledPayload = JSON.parse(settled.stdout) as { current: { calls: number } } + expect(settledPayload.current.calls).toBe(2) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('reprices from an updated live LiteLLM cache instead of serving a stale snapshot', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-pricing-gen-')) + + try { + const projectDir = join(home, '.claude', 'projects', 'myapp') + await mkdir(projectDir, { recursive: true }) + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000)) + const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z') + await writeFile( + join(projectDir, 'session.jsonl'), + [userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1')].join('\n'), + ) + + const cacheDir = join(home, '.cache', 'codeburn') + await mkdir(cacheDir, { recursive: true }) + const liveCachePath = join(cacheDir, 'litellm-pricing.json') + const writeLivePricing = (timestamp: number, inputCost: number, outputCost: number) => + writeFile(liveCachePath, JSON.stringify({ + version: CACHE_SCHEMA_VERSION, + timestamp, + data: { 'claude-sonnet-4-5': { inputCostPerToken: inputCost, outputCostPerToken: outputCost, cacheWriteCostPerToken: inputCost * 1.25, cacheReadCostPerToken: inputCost * 0.1, webSearchCostPerRequest: 0.01, fastMultiplier: 1 } }, + })) + + const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'claude', '--no-optimize'] + + await writeLivePricing(Date.now(), 1e-6, 5e-6) + const first = runCli(args, home) + expect(first.status, `stderr: ${first.stderr}`).toBe(0) + const firstCost = (JSON.parse(first.stdout) as { current: { cost: number } }).current.cost + + // Same session corpus, no config/currency change — only the live + // LiteLLM cache's price and timestamp move. Before the fix, the + // persisted status snapshot has no way to observe this and would keep + // serving `firstCost` indefinitely. + await writeLivePricing(Date.now() + 1000, 2e-6, 10e-6) + const second = runCli(args, home) + expect(second.status, `stderr: ${second.stderr}`).toBe(0) + const secondCost = (JSON.parse(second.stdout) as { current: { cost: number } }).current.cost + + expect(secondCost).toBeCloseTo(firstCost * 2, 5) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('invalidates the snapshot when a model is newly marked flat-rate', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-flat-rate-gen-')) + + try { + const projectDir = join(home, '.claude', 'projects', 'myapp') + await mkdir(projectDir, { recursive: true }) + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000)) + const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z') + const model = 'zz-status-snapshot-flat-rate' + await writeFile( + join(projectDir, 'session.jsonl'), + [userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1', model)].join('\n'), + ) + + const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'claude', '--no-optimize'] + const before = runCli(args, home) + expect(before.status, `stderr: ${before.stderr}`).toBe(0) + const beforePayload = JSON.parse(before.stdout) as { current: { unpricedModels: Array<{ model: string }> } } + expect(beforePayload.current.unpricedModels.map(row => row.model)).toContain(model) + + // This is render/daily-cache config, not a session-file change. It must + // still invalidate the fully-rendered status snapshot. + const configDir = join(home, '.config', 'codeburn') + await mkdir(configDir, { recursive: true }) + await writeFile(join(configDir, 'config.json'), JSON.stringify({ flatRateModels: [model] })) + + const after = runCli(args, home) + expect(after.status, `stderr: ${after.stderr}`).toBe(0) + const afterPayload = JSON.parse(after.stdout) as { current: { unpricedModels: Array<{ model: string }> } } + expect(afterPayload.current.unpricedModels.map(row => row.model)).not.toContain(model) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('never persists or serves the default optimize-enabled payload from the status snapshot', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-optimize-cache-')) + + try { + const projectDir = join(home, '.claude', 'projects', 'myapp') + await mkdir(projectDir, { recursive: true }) + const now = new Date() + const todayUtcMidnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + const base = new Date(Math.max(todayUtcMidnight, now.getTime() - 2 * 3600_000)) + const ts = (offset: number) => new Date(base.getTime() + offset).toISOString().replace(/\.\d+Z$/, 'Z') + await writeFile( + join(projectDir, 'session.jsonl'), + [userLine('s1', ts(0)), assistantLine('s1', ts(60_000), 'msg-1')].join('\n'), + ) + + const args = ['status', '--format', 'menubar-json', '--period', 'today', '--provider', 'claude'] + + const before = runCli(args, home) + expect(before.status, `stderr: ${before.stderr}`).toBe(0) + const findingsBefore = (JSON.parse(before.stdout) as { optimize: { findingCount: number } }).optimize.findingCount + + const cacheDir = join(home, '.cache', 'codeburn') + expect(findSnapshotFiles(cacheDir)).toEqual([]) + + // Mutable, non-fingerprinted optimize input: an unused custom agent + // definition. The session corpus is untouched, so a corpus-fingerprint- + // keyed snapshot would never notice this changed. + const agentsDir = join(home, '.claude', 'agents') + await mkdir(agentsDir, { recursive: true }) + await writeFile(join(agentsDir, 'ghost-agent.md'), '# never invoked this period') + + const after = runCli(args, home) + expect(after.status, `stderr: ${after.stderr}`).toBe(0) + const findingsAfter = (JSON.parse(after.stdout) as { optimize: { findingCount: number } }).optimize.findingCount + + expect(findingsAfter).toBe(findingsBefore + 1) + expect(findSnapshotFiles(cacheDir)).toEqual([]) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + it('still emits a valid combined menubar payload when the remotes store is corrupt', async () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-menubar-corrupt-remotes-')) diff --git a/tests/fixtures/status-snapshot-writer.ts b/tests/fixtures/status-snapshot-writer.ts new file mode 100644 index 00000000..58224aa6 --- /dev/null +++ b/tests/fixtures/status-snapshot-writer.ts @@ -0,0 +1,33 @@ +import { existsSync } from 'fs' +import { writeFile } from 'fs/promises' +import { join } from 'path' + +import { saveStatusSnapshot } from '../../src/session-cache.js' + +const [cacheDir, barriers, role, roundsRaw] = process.argv.slice(2) +if (!cacheDir || !barriers || (role !== 'fresh' && role !== 'stale')) { + throw new Error('usage: status-snapshot-writer ') +} +const rounds = Number(roundsRaw) +if (!Number.isInteger(rounds) || rounds < 1) throw new Error('rounds must be a positive integer') + +process.env['CODEBURN_CACHE_DIR'] = cacheDir +const semanticKey = 'child-process-render-v1' +const delay = (ms: number): Promise => new Promise(resolve => { setTimeout(resolve, ms) }) + +for (let round = 0; round < rounds; round++) { + await writeFile(join(barriers, `${role}.${round}.ready`), '') + const go = join(barriers, `${round}.go`) + while (!existsSync(go)) await delay(2) + + const fresh = role === 'fresh' + const published = await saveStatusSnapshot( + `${role}-${round}`, + fresh ? 3_000 : 2_000, + fresh ? 3_000 : 2_000, + `child-query-${round}`, + semanticKey, + { role, round }, + ) + await writeFile(join(barriers, `${role}.${round}.done`), String(published)) +} diff --git a/tests/parse-workers.test.ts b/tests/parse-workers.test.ts index c182b1ff..395430fb 100644 --- a/tests/parse-workers.test.ts +++ b/tests/parse-workers.test.ts @@ -366,7 +366,15 @@ describe('parallel cold parse', () => { expect(cold.stderr).toContain('codeburn: codex parse workers=3') await appendFile(path, codexTaskLines([{ n: 4, at: '2026-05-04T09:40:00.000Z' }]).join('\n') + '\n') - const warm = runCli(args, home, { CODEBURN_PARSE_WORKERS: '3', CODEBURN_CACHE_DIR: cache, CODEBURN_VERBOSE: '1' }) + // `status --format menubar-json` now persists a corpus-fingerprint-keyed + // snapshot of its rendered payload (see src/session-cache.ts's + // loadStatusSnapshot/saveStatusSnapshot) and defers a fingerprint + // mismatch for up to CODEBURN_STATUS_SNAPSHOT_SETTLE_MS before doing a + // real recompute, so the appended line above would otherwise just be + // served from the (correctly!) settling snapshot with no parse at all. + // Force the window to 0 so this "warm" run actually reaches the parse + // pipeline this test is exercising. + const warm = runCli(args, home, { CODEBURN_PARSE_WORKERS: '3', CODEBURN_CACHE_DIR: cache, CODEBURN_VERBOSE: '1', CODEBURN_STATUS_SNAPSHOT_SETTLE_MS: '0' }) expect(warm.status, warm.stderr).toBe(0) expect(warm.stderr).toContain('codeburn: codex parse workers=0 (no full parses pending)') }) diff --git a/tests/providers/cline-cli.test.ts b/tests/providers/cline-cli.test.ts index a32bef17..42a59aae 100644 --- a/tests/providers/cline-cli.test.ts +++ b/tests/providers/cline-cli.test.ts @@ -161,7 +161,10 @@ describe('cline-cli provider - discovery', () => { expect(sources).toHaveLength(2) expect(sources.map(s => s.provider)).toEqual(['cline-cli', 'cline-cli']) - expect(sources[0]?.path).toBe(join(tmpDir, 'sess-a', 'sess-a.json')) + // The growing messages file is fingerprinted, not the static metadata + // file written once at session start (review finding C-G1) — otherwise + // a live session's new turns are invisible to computeCorpusFingerprint. + expect(sources[0]?.path).toBe(join(tmpDir, 'sess-a', 'sess-a.messages.json')) }) it('names the project from the workspace root', async () => { diff --git a/tests/session-cache-status-snapshot.test.ts b/tests/session-cache-status-snapshot.test.ts new file mode 100644 index 00000000..ee18aa37 --- /dev/null +++ b/tests/session-cache-status-snapshot.test.ts @@ -0,0 +1,167 @@ +// The status-snapshot file (one `status-snapshot..json` per +// distinct query) is written by the same one-shot-CLI-process-per-poll model +// as the main session cache — a menubar poll and a manual refresh are two +// independent processes that can both be mid-write against the same cache +// dir at once. `session-cache-shards.test.ts` has a dedicated +// `describe('concurrent writers', ...)` block for the main cache's +// structurally identical tmp+rename atomic-write pattern; this file is the +// analogous coverage for the snapshot file (review finding D-G9), and +// exercises the locked publication fix for finding B-G1 directly: a slower, +// older-corpus write must not clobber a faster, newer one, and two distinct queryKeys +// must not evict each other. +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { chmod, mkdir, readdir, readFile, rm } from 'fs/promises' +import { existsSync } from 'fs' +import { createHash } from 'crypto' +import { tmpdir } from 'os' +import { join } from 'path' + +import { loadStatusSnapshot, saveStatusSnapshot } from '../src/session-cache.js' + +let TMP_DIR: string +const SEMANTIC_KEY = 'test-render-v1' + +beforeEach(async () => { + TMP_DIR = join(tmpdir(), `codeburn-snapshot-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`) + process.env['CODEBURN_CACHE_DIR'] = TMP_DIR + await mkdir(TMP_DIR, { recursive: true }) +}) + +afterEach(async () => { + if (existsSync(TMP_DIR)) await rm(TMP_DIR, { recursive: true }) +}) + +async function readRawRecord(queryKey: string): Promise | null> { + const hash = createHash('sha256').update(queryKey).digest('hex').slice(0, 16) + try { + const raw = await readFile(join(TMP_DIR, `status-snapshot.${hash}.json`), 'utf-8') + return JSON.parse(raw) as Record + } catch { + return null + } +} + +describe('concurrent writers (status snapshot)', () => { + it('serializes genuinely concurrent same-query saves so an older observation cannot win', async () => { + let staleWins = 0 + + for (let round = 0; round < 50; round++) { + const queryKey = `same-query-${round}` + await saveStatusSnapshot('baseline', 1_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'baseline' }) + + // Both writes start from the same baseline. On the broken read/guard then + // rename protocol they both pass the guard, and the slower older write is + // free to rename over the fresh result. + await Promise.all([ + saveStatusSnapshot('fresh', 3_000, 3_000, queryKey, SEMANTIC_KEY, { p: 'fresh' }), + saveStatusSnapshot('stale', 2_000, 2_000, queryKey, SEMANTIC_KEY, { p: 'stale' }), + ]) + + const record = await readRawRecord(queryKey) + if (record?.['corpusFingerprint'] === 'stale') staleWins++ + } + + expect(staleWins).toBe(0) + }) + + it('never lets a slower recompute against an older corpus clobber a faster, newer one', async () => { + const queryKey = 'q1' + // Baseline: both processes started from this on-disk state. + await saveStatusSnapshot('f1', 1_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'baseline' }) + + // Process A observed the corpus at m=2_000 and is slow to finish. + // Process B observed it LATER, at m=3_000, and finishes first. + await saveStatusSnapshot('f3', 3_000, 3_000, queryKey, SEMANTIC_KEY, { p: 'B-fresh' }) + // A's write lands after B's despite being based on an older observation. + await saveStatusSnapshot('f2', 2_000, 2_000, queryKey, SEMANTIC_KEY, { p: 'A-stale' }) + + const record = await readRawRecord(queryKey) + expect(record).toMatchObject({ corpusFingerprint: 'f3', newestMtimeMs: 3_000, payload: { p: 'B-fresh' } }) + + // Confirmed via the public read path too. + const served = await loadStatusSnapshot('f3', queryKey, SEMANTIC_KEY) + expect(served).toEqual({ p: 'B-fresh' }) + }) + + it('does not let a delayed mismatch-bookkeeping write reintroduce a payload a real recompute already superseded', async () => { + const queryKey = 'q1' + await saveStatusSnapshot('f1', 1_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'v1' }) + + // A load observes the corpus moved to f2 (within the settle window) and + // would normally persist a bookkeeping mismatchFirstSeenAt timestamp — + // but a real recompute for f2 lands first. + const stale = await loadStatusSnapshot('f2', queryKey, SEMANTIC_KEY) + expect(stale).toEqual({ p: 'v1' }) // served from the settle window + + await saveStatusSnapshot('f2', 1_500, 2_000, queryKey, SEMANTIC_KEY, { p: 'v2-real' }) + + const record = await readRawRecord(queryKey) + // The real recompute's record must be exactly what's on disk — no + // mismatchFirstSeenAt bookkeeping should have overwritten it with the + // stale v1 payload. + expect(record).toMatchObject({ corpusFingerprint: 'f2', payload: { p: 'v2-real' } }) + expect((record as { mismatchFirstSeenAt?: number }).mismatchFirstSeenAt).toBeUndefined() + }) + + it('recomputes instead of extending stale forever when mismatch bookkeeping cannot be persisted', async () => { + const queryKey = 'read-only-cache' + process.env['CODEBURN_STATUS_SNAPSHOT_SETTLE_MS'] = '20' + await saveStatusSnapshot('before', 1_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'stale' }) + + await chmod(TMP_DIR, 0o500) + try { + expect(await loadStatusSnapshot('after', queryKey, SEMANTIC_KEY)).toBeNull() + await new Promise(resolve => { setTimeout(resolve, 40) }) + // The first mismatch timestamp could not land. Treat that as a miss; + // resetting the settle clock on every poll serves stale indefinitely. + expect(await loadStatusSnapshot('after', queryKey, SEMANTIC_KEY)).toBeNull() + } finally { + await chmod(TMP_DIR, 0o700) + delete process.env['CODEBURN_STATUS_SNAPSHOT_SETTLE_MS'] + } + }) + + it('publishes a later corpus observation even when deleting the newest file lowers max mtime', async () => { + const queryKey = 'deletion-lowers-max-mtime' + process.env['CODEBURN_STATUS_SNAPSHOT_SETTLE_MS'] = '0' + try { + await saveStatusSnapshot('before-delete', 3_000, 1_000, queryKey, SEMANTIC_KEY, { p: 'old' }) + expect(await loadStatusSnapshot('after-delete', queryKey, SEMANTIC_KEY)).toBeNull() + + // max(mtime) is not an ordering relation: deleting the former maximum + // legitimately makes it go backwards even though this observation is + // newer and must replace the old snapshot. + await saveStatusSnapshot('after-delete', 2_000, 2_000, queryKey, SEMANTIC_KEY, { p: 'new' }) + expect(await loadStatusSnapshot('after-delete', queryKey, SEMANTIC_KEY)).toEqual({ p: 'new' }) + } finally { + delete process.env['CODEBURN_STATUS_SNAPSHOT_SETTLE_MS'] + } + }) + + it('never publishes a torn write and always leaves a subsequent read intact, even racing two distinct queryKeys', async () => { + for (let round = 0; round < 15; round++) { + await Promise.allSettled([ + saveStatusSnapshot(`a${round}`, round, round, 'query-a', SEMANTIC_KEY, { round, who: 'a' }), + saveStatusSnapshot(`b${round}`, round, round, 'query-b', SEMANTIC_KEY, { round, who: 'b' }), + ]) + // Whichever landed, EACH queryKey's own file must be valid JSON and + // present — a shared single-slot file would have one evict the other + // every round; distinct per-queryKey files never touch each other. + expect(await readRawRecord('query-a')).toBeTruthy() + expect(await readRawRecord('query-b')).toBeTruthy() + // A subsequent read must not throw on whatever landed. + await loadStatusSnapshot(`a${round}`, 'query-a', SEMANTIC_KEY) + await loadStatusSnapshot(`b${round}`, 'query-b', SEMANTIC_KEY) + } + // No stray .tmp files left mid-directory after the last round settles. + const leftoverTemps = (await readdir(TMP_DIR)).filter(f => f.endsWith('.tmp')) + expect(leftoverTemps).toEqual([]) + }) + + it('rejects an exact-corpus snapshot written under different render semantics', async () => { + const queryKey = 'semantic-fence' + await saveStatusSnapshot('same-corpus', 1_000, 1_000, queryKey, 'render-v1', { p: 'old-shape' }) + + expect(await loadStatusSnapshot('same-corpus', queryKey, 'render-v2')).toBeNull() + }) +})