mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-25 22:42:30 +00:00
Merge pull request #1303 from getagentseal/fix/per-provider-cache-completeness
fix(cache): record session-cache completeness per provider
This commit is contained in:
commit
5783c6d0af
6 changed files with 371 additions and 97 deletions
|
|
@ -8,7 +8,7 @@ import { FS_SCAN_CONCURRENCY, mapWithConcurrency, readSessionLines } from './fs-
|
|||
import { billableOutputTokens, calculateCost, calculateLocalModelSavings, getShortModelName, isProxiedPath, getProxyPathsConfigHash, getModelAliasesConfigHash, getPriceOverridesConfigHash, getLocalModelSavingsConfigHash } from './models.js'
|
||||
import { resolveSubagentAttribution, sessionIdentity } from './sessions-report.js'
|
||||
import { normalizeContentBlocks, flatSlice, flatString } from './content-utils.js'
|
||||
import { discoverAllSessions, getProvider } from './providers/index.js'
|
||||
import { discoverAllSessions, discoverAllSessionsWithFailures, getProvider } from './providers/index.js'
|
||||
import { flushCodexCache, readCachedCodexResults, withCodexCacheDirectory, writeCachedCodexResults } from './codex-cache.js'
|
||||
import { antigravityCascadeIdFromPath, flushAntigravityCache, shouldReparseAntigravitySource } from './providers/antigravity.js'
|
||||
import { getClaudeConfigDirs, getDesktopSessionsDirs } from './providers/claude.js'
|
||||
|
|
@ -35,6 +35,7 @@ import {
|
|||
isCacheDirty,
|
||||
loadCache,
|
||||
markCacheDirty,
|
||||
markProviderComplete,
|
||||
monthScopeForRange,
|
||||
reconcileFile,
|
||||
saveCache,
|
||||
|
|
@ -3497,7 +3498,10 @@ export async function parseProviderSources(
|
|||
try {
|
||||
for (const { source, fp } of changedSources) {
|
||||
if (dateRange) {
|
||||
if (fp.mtimeMs < dateRange.start.getTime()) continue
|
||||
if (fp.mtimeMs < dateRange.start.getTime()) {
|
||||
dateFloorSkippedProviders.add(providerName)
|
||||
continue
|
||||
}
|
||||
}
|
||||
filesParsedFromSource++
|
||||
|
||||
|
|
@ -5227,6 +5231,13 @@ export async function computeCorpusFingerprint(providerFilter?: string): Promise
|
|||
// new data, so the run must not report hydration complete even in write mode.
|
||||
let deferredRetryableSource = false
|
||||
|
||||
// Providers for which this run left an uncached source unparsed because its
|
||||
// mtime predates the requested range. The scan still reached the end, but only
|
||||
// for sources modified since `dateRange.start` — which is exactly what the
|
||||
// per-provider completeness floor records, so a later WIDER query re-enters
|
||||
// cold hydration instead of trusting a cache that never saw those files.
|
||||
const dateFloorSkippedProviders = new Set<string>()
|
||||
|
||||
// One command invocation that renders a dashboard asks for several ranges that
|
||||
// differ only in where they END — the scan range runs to end-of-day, the
|
||||
// durable headline re-anchors on its own `new Date()`. The exact-key memo needs
|
||||
|
|
@ -5402,8 +5413,8 @@ export function parseAllSessions(dateRange?: DateRange, providerFilter?: string)
|
|||
return withCodexCacheDirectory(codexCacheDir, () => parseAllSessionsInCacheScope(dateRange, providerFilter))
|
||||
}
|
||||
|
||||
function canServeCompleteSnapshot(cache: SessionCache, providerFilter?: string): boolean {
|
||||
if (!isCacheComplete(cache)) return false
|
||||
function canServeCompleteSnapshot(cache: SessionCache, providerFilter?: string, sinceMs?: number): boolean {
|
||||
if (!isCacheComplete(cache, providerFilter, sinceMs)) return false
|
||||
const sections = providerFilter && providerFilter !== 'all'
|
||||
? ([[providerFilter, cache.providers[providerFilter]]] as const).filter((entry): entry is readonly [string, ProviderSection] => entry[1] != null)
|
||||
: Object.entries(cache.providers)
|
||||
|
|
@ -5413,7 +5424,7 @@ function canServeCompleteSnapshot(cache: SessionCache, providerFilter?: string):
|
|||
|
||||
export async function isCompleteSessionSnapshotAvailable(dateRange: DateRange, providerFilter?: string): Promise<boolean> {
|
||||
const diskCache = await loadCache(monthScopeForRange(dateRange.start, dateRange.end))
|
||||
return canServeCompleteSnapshot(diskCache, providerFilter)
|
||||
return canServeCompleteSnapshot(diskCache, providerFilter, dateRange.start.getTime())
|
||||
}
|
||||
|
||||
async function parseAllSessionsInCacheScope(dateRange?: DateRange, providerFilter?: string): Promise<ProjectSummary[]> {
|
||||
|
|
@ -5461,11 +5472,12 @@ async function parseAllSessionsInCacheScope(dateRange?: DateRange, providerFilte
|
|||
// a proxied key emitted under two providers the attribution can land on a
|
||||
// different provider than a full load would pick.
|
||||
const loadScope = dateRange ? monthScopeForRange(dateRange.start, dateRange.end) : undefined
|
||||
const rangeStartMs = dateRange?.start.getTime()
|
||||
const cacheLoadStarted = performance.now()
|
||||
let diskCache = await loadCache(loadScope)
|
||||
await cleanupOrphanedTempFiles()
|
||||
if (process.env['CODEBURN_VERBOSE'] === '1') {
|
||||
process.stderr.write(`codeburn: startup timing cache-load=${(performance.now() - cacheLoadStarted).toFixed(1)}ms complete=${isCacheComplete(diskCache)}\n`)
|
||||
process.stderr.write(`codeburn: startup timing cache-load=${(performance.now() - cacheLoadStarted).toFixed(1)}ms complete=${isCacheComplete(diskCache, providerFilter, rangeStartMs)}\n`)
|
||||
}
|
||||
|
||||
// Cold-hydration coordination (advisory, cross-process). Engages whenever the
|
||||
|
|
@ -5476,10 +5488,10 @@ async function parseAllSessionsInCacheScope(dateRange?: DateRange, providerFilte
|
|||
// If another live process is already hydrating, wait for it, then reload the
|
||||
// now-warm cache instead of double-parsing. Never a correctness gate: on any
|
||||
// doubt it proceeds unlocked.
|
||||
if (!isCacheComplete(diskCache)) {
|
||||
if (!isCacheComplete(diskCache, providerFilter, rangeStartMs)) {
|
||||
const hydration = await beginColdHydration(true)
|
||||
if (hydration.waited) diskCache = await loadCache(loadScope)
|
||||
const isCold = !isCacheComplete(diskCache)
|
||||
const isCold = !isCacheComplete(diskCache, providerFilter, rangeStartMs)
|
||||
try {
|
||||
return await runParse(key, diskCache, dateRange, providerFilter, { isCold, burstSig, parseStartedAt })
|
||||
} finally {
|
||||
|
|
@ -5487,7 +5499,7 @@ async function parseAllSessionsInCacheScope(dateRange?: DateRange, providerFilte
|
|||
}
|
||||
}
|
||||
|
||||
if (firstPaintPrefersCompleteSnapshot && canServeCompleteSnapshot(diskCache, providerFilter)) {
|
||||
if (firstPaintPrefersCompleteSnapshot && canServeCompleteSnapshot(diskCache, providerFilter, rangeStartMs)) {
|
||||
return runParse(key, diskCache, dateRange, providerFilter, {
|
||||
readOnly: true,
|
||||
snapshotOnly: true,
|
||||
|
|
@ -5584,9 +5596,13 @@ async function runParseInner(
|
|||
readOnlyServedStale = false
|
||||
deferredRetryableSource = false
|
||||
firstPaintDeferredThisRun = 0
|
||||
dateFloorSkippedProviders.clear()
|
||||
const seenMsgIds = new Set<string>()
|
||||
const seenKeys = new Set<string>()
|
||||
const allSources = snapshotOnly ? [] : await discoverAllSessions(providerFilter)
|
||||
const discovery = snapshotOnly
|
||||
? { sources: [], failedProviders: [] }
|
||||
: await discoverAllSessionsWithFailures(providerFilter)
|
||||
const allSources = discovery.sources
|
||||
traceTiming('discovery', ` sources=${allSources.length}`)
|
||||
|
||||
const claudeSources = allSources.filter(s => s.provider === 'claude')
|
||||
|
|
@ -5704,27 +5720,34 @@ async function runParseInner(
|
|||
// background fill) has to come back cold and finish the job. A floored run
|
||||
// that deferred NOTHING parsed exactly what an unfloored run would have, so
|
||||
// it keeps the normal stamp.
|
||||
//
|
||||
// What the stamp records is what this run actually WALKED, on both axes a
|
||||
// scan can be scoped on (#912). A `--provider X` run saw X and nothing else,
|
||||
// so it marks X's section and leaves the whole-cache flag — the one that
|
||||
// vouches for providers with no section at all — to an unscoped run. A ranged
|
||||
// run left every uncached source older than the range unparsed, so the
|
||||
// providers that skipped one record the range start as their completeness
|
||||
// floor rather than claiming all of history. And a provider whose discovery
|
||||
// threw contributed an empty source list that means "unknown", not "empty",
|
||||
// so it is not marked at all.
|
||||
const deferredForFirstPaint = firstPaintDeferredThisRun > 0
|
||||
const wasComplete = isCacheComplete(diskCache)
|
||||
// A provider-scoped run walks only its own provider's sessions, so it never
|
||||
// saw whatever the providers it skipped hold on disk. Stamping the WHOLE
|
||||
// cache complete off that partial view writes a wrong "done" to disk (#912):
|
||||
// per the marker's own contract above, a complete cache stops being re-read
|
||||
// as cold, so the unscanned providers are not revisited and the gap stops
|
||||
// looking like a gap. The guard is conditioned on real on-disk data, not on
|
||||
// scoping alone: when every provider the run skipped has NO discoverable
|
||||
// sessions, the scoped run really did see the whole corpus (a claude-only
|
||||
// machine, and exactly what the warm-refresh snapshot tests rely on), so the
|
||||
// stamp is correct and stands. Discovery here is a bounded directory walk,
|
||||
// not a parse — the scoping win (skipping the other providers' PARSE) holds.
|
||||
const rangeStartMs = dateRange?.start.getTime()
|
||||
const scopedRun = !!providerFilter && providerFilter !== 'all'
|
||||
let skippedProviderHasSessions = false
|
||||
if (scopedRun && !readOnly && !wasComplete && !deferredForFirstPaint) {
|
||||
const corpusSources = await discoverAllSessions()
|
||||
skippedProviderHasSessions = corpusSources.some(s => s.provider !== providerFilter)
|
||||
const discoveryFailed = new Set(discovery.failedProviders)
|
||||
let completenessChanged = false
|
||||
if (!readOnly && !deferredForFirstPaint) {
|
||||
const walked = scopedRun ? [providerFilter!] : Object.keys(diskCache.providers)
|
||||
for (const provider of walked) {
|
||||
if (discoveryFailed.has(provider)) continue
|
||||
const floor = dateFloorSkippedProviders.has(provider) ? rangeStartMs : undefined
|
||||
if (markProviderComplete(diskCache, provider, floor)) completenessChanged = true
|
||||
}
|
||||
if (!scopedRun && discoveryFailed.size === 0 && diskCache.complete !== true) {
|
||||
diskCache.complete = true
|
||||
completenessChanged = true
|
||||
}
|
||||
}
|
||||
if (!readOnly && !wasComplete && !deferredForFirstPaint && !skippedProviderHasSessions) diskCache.complete = true
|
||||
if (!readOnly && (isCacheDirty(diskCache) || (!wasComplete && !deferredForFirstPaint))) {
|
||||
if (!readOnly && (isCacheDirty(diskCache) || completenessChanged)) {
|
||||
try {
|
||||
const published = await saveCache(diskCache, refreshLock?.verifyStillOwner)
|
||||
if (!published) throw new RefreshFenceLostError()
|
||||
|
|
|
|||
|
|
@ -261,9 +261,9 @@ export const providers = coreProviders
|
|||
// provider per run, then skip it. Mirrors the parse-failure isolation already
|
||||
// used per-file in parser.ts.
|
||||
const warnedDiscoveryFailures = new Set<string>()
|
||||
export async function safeDiscoverSessions(provider: Provider): Promise<SessionSource[]> {
|
||||
async function discoverOne(provider: Provider): Promise<{ sources: SessionSource[]; failed: boolean }> {
|
||||
try {
|
||||
return await provider.discoverSessions()
|
||||
return { sources: await provider.discoverSessions(), failed: false }
|
||||
} catch (err) {
|
||||
if (!warnedDiscoveryFailures.has(provider.name)) {
|
||||
warnedDiscoveryFailures.add(provider.name)
|
||||
|
|
@ -272,16 +272,26 @@ export async function safeDiscoverSessions(provider: Provider): Promise<SessionS
|
|||
`codeburn: skipped ${provider.name} discovery after an error: ${msg}\n`
|
||||
)
|
||||
}
|
||||
return []
|
||||
return { sources: [], failed: true }
|
||||
}
|
||||
}
|
||||
|
||||
export async function discoverAllSessions(
|
||||
export async function safeDiscoverSessions(provider: Provider): Promise<SessionSource[]> {
|
||||
return (await discoverOne(provider)).sources
|
||||
}
|
||||
|
||||
/** Names of the providers whose discovery threw, alongside the sources the rest
|
||||
* found. The empty list a failed provider contributes is indistinguishable
|
||||
* from "this provider has no sessions", and a caller that reads the first as
|
||||
* the second concludes it has seen a corpus it never saw. */
|
||||
export type SessionDiscovery = { sources: SessionSource[]; failedProviders: string[] }
|
||||
|
||||
export async function discoverAllSessionsWithFailures(
|
||||
providerFilter?: string,
|
||||
// Injectable for tests so the isolation loop itself is exercised, not just
|
||||
// the helper. Defaults to the real registry.
|
||||
providerList?: Provider[],
|
||||
): Promise<SessionSource[]> {
|
||||
): Promise<SessionDiscovery> {
|
||||
const allProviders = providerList ?? await getAllProviders()
|
||||
const filtered = providerFilter && providerFilter !== 'all'
|
||||
? allProviders.filter(p => p.name === providerFilter)
|
||||
|
|
@ -289,8 +299,18 @@ export async function discoverAllSessions(
|
|||
// Each provider's discovery is its own serial directory walk; run them
|
||||
// concurrently and concatenate in registry order so the result stays
|
||||
// byte-identical to the sequential version.
|
||||
const perProvider = await Promise.all(filtered.map(provider => safeDiscoverSessions(provider)))
|
||||
return perProvider.flat()
|
||||
const perProvider = await Promise.all(filtered.map(discoverOne))
|
||||
return {
|
||||
sources: perProvider.flatMap(r => r.sources),
|
||||
failedProviders: filtered.filter((_, i) => perProvider[i]!.failed).map(p => p.name),
|
||||
}
|
||||
}
|
||||
|
||||
export async function discoverAllSessions(
|
||||
providerFilter?: string,
|
||||
providerList?: Provider[],
|
||||
): Promise<SessionSource[]> {
|
||||
return (await discoverAllSessionsWithFailures(providerFilter, providerList)).sources
|
||||
}
|
||||
|
||||
export async function getProvider(name: string): Promise<Provider | undefined> {
|
||||
|
|
|
|||
|
|
@ -154,19 +154,36 @@ export type ProviderSection = {
|
|||
files: Record<string, CachedFile>
|
||||
/** True when the provider's cache entries survive source-file eviction. */
|
||||
durable?: boolean
|
||||
/** True once a scan walked THIS provider end to end. A `--provider X` run
|
||||
* only ever learns about X, so completeness is recorded per provider and the
|
||||
* whole-cache `complete` below is reserved for an unscoped scan. Absent →
|
||||
* fall back to the whole-cache flag (a cache written before this field, or
|
||||
* by an unscoped run that already vouched for every provider). */
|
||||
complete?: boolean
|
||||
/** Epoch ms floor of what `complete` covers: the scan skipped sources whose
|
||||
* mtime predates this (the `dateRange` filter in parseProviderSources), so
|
||||
* the section answers "complete" only for a query starting at or after it.
|
||||
* Absent means complete for any range. */
|
||||
completeFrom?: number
|
||||
}
|
||||
|
||||
export type SessionCache = {
|
||||
version: number
|
||||
providers: Record<string, ProviderSection>
|
||||
/** True only once a full scan has run to completion. The throttled partial
|
||||
* saves during a cold hydration persist `false`; the single end-of-parse save
|
||||
* flips it `true`. A cache that is present-but-incomplete (an interrupted cold
|
||||
* start left a partial behind) must be treated as still cold — otherwise the
|
||||
* emptiness heuristic reads the partial as warm, the cross-process hydration
|
||||
* lock never engages, and totals heal only gradually while a concurrent parse
|
||||
* can freeze a partial daily history. Absent on caches written before this
|
||||
* field existed → read as incomplete (one self-healing re-hydration). */
|
||||
/** True only once a full UNSCOPED scan has run to completion. The throttled
|
||||
* partial saves during a cold hydration persist `false`; the single
|
||||
* end-of-parse save flips it `true`. A cache that is present-but-incomplete
|
||||
* (an interrupted cold start left a partial behind) must be treated as still
|
||||
* cold — otherwise the emptiness heuristic reads the partial as warm, the
|
||||
* cross-process hydration lock never engages, and totals heal only gradually
|
||||
* while a concurrent parse can freeze a partial daily history. Absent on
|
||||
* caches written before this field existed → read as incomplete (one
|
||||
* self-healing re-hydration).
|
||||
*
|
||||
* A provider-scoped run never sets it — it saw one provider — and instead
|
||||
* stamps that provider's own `ProviderSection.complete`. Kept as the
|
||||
* whole-cache answer so a reader that only knows the envelope (and every
|
||||
* cache written before per-provider stamps existed) keeps working. */
|
||||
complete?: boolean
|
||||
}
|
||||
|
||||
|
|
@ -440,6 +457,8 @@ type ShardRef = { name: string; until: string }
|
|||
type EnvelopeProvider = {
|
||||
envFingerprint: string
|
||||
durable?: boolean
|
||||
complete?: boolean
|
||||
completeFrom?: number
|
||||
/** month (`YYYY-MM`, or `0000-00` for turn-less files) -> shard */
|
||||
shards: Record<string, ShardRef>
|
||||
}
|
||||
|
|
@ -579,9 +598,51 @@ export function emptyCache(): SessionCache {
|
|||
|
||||
/** A cache is warm only when a full scan finished against it. Empty-but-marked
|
||||
* (a machine with no sessions) is complete; present-but-unmarked (an interrupted
|
||||
* cold start, or a pre-marker cache) is NOT — it is still cold. */
|
||||
export function isCacheComplete(cache: SessionCache): boolean {
|
||||
return cache.complete === true
|
||||
* cold start, or a pre-marker cache) is NOT — it is still cold.
|
||||
*
|
||||
* The answer is composed from the sections the REQUEST needs, on both axes a
|
||||
* scan can be scoped on:
|
||||
* - provider: a `--provider X` request asks only about X's section; an
|
||||
* unscoped one needs the whole-cache flag (only an unscoped scan can vouch
|
||||
* for the providers that have no section at all) plus every section it holds.
|
||||
* - date: a section stamped with a `completeFrom` floor skipped older sources,
|
||||
* so it answers a query starting at or after that floor and no other.
|
||||
*
|
||||
* `sinceMs` is the requested range start; omitting it asks about ALL of
|
||||
* history, which only a section with no floor can satisfy. A section with no
|
||||
* `complete` of its own inherits the whole-cache flag, which is what keeps a
|
||||
* cache written before per-provider stamps (and one an unscoped scan wrote)
|
||||
* reading exactly as it did. */
|
||||
export function isCacheComplete(cache: SessionCache, providerFilter?: string, sinceMs?: number): boolean {
|
||||
const sectionComplete = (provider: string): boolean => {
|
||||
const section = cache.providers[provider]
|
||||
if ((section?.complete ?? cache.complete) !== true) return false
|
||||
const from = section?.completeFrom
|
||||
return from === undefined || (sinceMs !== undefined && sinceMs >= from)
|
||||
}
|
||||
if (providerFilter && providerFilter !== 'all') return sectionComplete(providerFilter)
|
||||
return cache.complete === true && Object.keys(cache.providers).every(sectionComplete)
|
||||
}
|
||||
|
||||
/** Record that this scan walked `provider` to the end, optionally only back to
|
||||
* `completeFrom` (the range start that filtered older sources out). Coverage
|
||||
* only ever grows — a section already complete for all of history stays that
|
||||
* way — so the stored floor is the lowest of the two. Returns whether anything
|
||||
* changed, which is what makes the caller save a cache that is otherwise
|
||||
* clean. The section is created when absent: a scoped scan of a provider with
|
||||
* no sessions has nothing to cache but still has completeness to record, and
|
||||
* without it every such run would re-enter cold hydration forever. */
|
||||
export function markProviderComplete(cache: SessionCache, provider: string, completeFrom?: number): boolean {
|
||||
const section = cache.providers[provider]
|
||||
?? (cache.providers[provider] = { envFingerprint: computeEnvFingerprint(provider), files: {} })
|
||||
const prior = section.complete === true ? section.completeFrom ?? 0 : undefined
|
||||
const widened = prior === undefined ? completeFrom : Math.min(prior, completeFrom ?? 0)
|
||||
const floor = widened !== undefined && widened > 0 ? widened : undefined
|
||||
const changed = section.complete !== true || section.completeFrom !== floor
|
||||
section.complete = true
|
||||
if (floor === undefined) delete section.completeFrom
|
||||
else section.completeFrom = floor
|
||||
return changed
|
||||
}
|
||||
|
||||
/** Pre-parse probe of the same question `isCacheComplete` answers after a load:
|
||||
|
|
@ -590,7 +651,13 @@ export function isCacheComplete(cache: SessionCache): boolean {
|
|||
* A cache still in a legacy layout has no envelope and reads as cold — the
|
||||
* adoption in `loadCache` may still make it warm, which costs the caller
|
||||
* nothing: a warm cache has an entry for every discovered file, so a
|
||||
* cold-start optimisation keyed on missing entries simply finds no work. */
|
||||
* cold-start optimisation keyed on missing entries simply finds no work.
|
||||
* Deliberately the WHOLE-cache question, matching `isCacheComplete` with no
|
||||
* provider filter: its callers (the serve first-paint floor, the background
|
||||
* fill) answer for every provider at once, so a cache only one scoped run has
|
||||
* vouched for is still cold to them. A `completeFrom` floor does not make it
|
||||
* cold — the floored months are cached, and a wider request re-enters cold
|
||||
* hydration through `isCacheComplete` on its own. */
|
||||
export async function isColdCacheOnDisk(): Promise<boolean> {
|
||||
return (await readEnvelope(sessionCacheDir()))?.complete !== true
|
||||
}
|
||||
|
|
@ -962,6 +1029,8 @@ export async function loadCache(scope?: CacheLoadScope): Promise<SessionCache> {
|
|||
envFingerprint: meta.envFingerprint,
|
||||
files: {},
|
||||
...(meta.durable ? { durable: true } : {}),
|
||||
...(meta.complete === true ? { complete: true } : {}),
|
||||
...(typeof meta.completeFrom === 'number' ? { completeFrom: meta.completeFrom } : {}),
|
||||
}
|
||||
// Recorded even when every shard is skipped or unreadable: the section is
|
||||
// what tells the next save which provider these carried-forward shard refs
|
||||
|
|
@ -1358,6 +1427,8 @@ export async function saveCache(cache: SessionCache, verifyStillOwner?: () => Pr
|
|||
providers[provider] = {
|
||||
envFingerprint: plan.section.envFingerprint,
|
||||
...(plan.section.durable ? { durable: true } : {}),
|
||||
...(plan.section.complete === true ? { complete: true } : {}),
|
||||
...(plan.section.completeFrom !== undefined ? { completeFrom: plan.section.completeFrom } : {}),
|
||||
shards,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,18 +35,24 @@ let _synthOnParse: ((source: SessionSource) => void | Promise<void>) | null = nu
|
|||
vi.mock('../src/providers/index.js', async (importOriginal) => {
|
||||
type Mod = typeof import('../src/providers/index.js')
|
||||
const actual = await importOriginal<Mod>()
|
||||
// Pass through for specific non-synthetic providers; inject synthetic
|
||||
// sources only when filter is undefined/'all'/'test-synthetic'.
|
||||
const discoverAllSessions = async (filter?: string): Promise<SessionSource[]> => {
|
||||
if (filter && filter !== 'all' && filter !== 'test-synthetic') {
|
||||
return actual.discoverAllSessions(filter)
|
||||
}
|
||||
const base = filter === 'test-synthetic'
|
||||
? []
|
||||
: await actual.discoverAllSessions(filter)
|
||||
return [..._synthSources, ...base]
|
||||
}
|
||||
return {
|
||||
...actual,
|
||||
async discoverAllSessions(filter?: string) {
|
||||
// Pass through for specific non-synthetic providers; inject synthetic
|
||||
// sources only when filter is undefined/'all'/'test-synthetic'.
|
||||
if (filter && filter !== 'all' && filter !== 'test-synthetic') {
|
||||
return actual.discoverAllSessions(filter)
|
||||
}
|
||||
const base = filter === 'test-synthetic'
|
||||
? []
|
||||
: await actual.discoverAllSessions(filter)
|
||||
return [..._synthSources, ...base]
|
||||
discoverAllSessions,
|
||||
// What the parse path calls. The synthetic provider never fails discovery,
|
||||
// so it carries the same sources and no failures.
|
||||
async discoverAllSessionsWithFailures(filter?: string) {
|
||||
return { sources: await discoverAllSessions(filter), failedProviders: [] }
|
||||
},
|
||||
async getProvider(name: string) {
|
||||
if (name === 'test-synthetic') {
|
||||
|
|
|
|||
|
|
@ -1,39 +1,77 @@
|
|||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtemp, mkdir, writeFile, rm } from 'fs/promises'
|
||||
// Completeness is recorded for what a run actually WALKED (#912). A scan is
|
||||
// scoped on two axes — `--provider X` and a date range — and a stamp that
|
||||
// ignores either writes a "done" the cache cannot back up.
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mkdtemp, mkdir, writeFile, rm, utimes } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
|
||||
import type { Provider } from '../src/providers/types.js'
|
||||
|
||||
const injected = vi.hoisted(() => ({ throwingProvider: false, coldHydrations: 0 }))
|
||||
|
||||
// The throwing provider goes through the REAL discovery-isolation path (which
|
||||
// swallows the throw into an empty list), so what is under test is the stamp's
|
||||
// reaction to a provider that reported nothing because it failed.
|
||||
vi.mock('../src/providers/index.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../src/providers/index.js')>('../src/providers/index.js')
|
||||
const boom = {
|
||||
name: 'boom-provider',
|
||||
displayName: 'Boom',
|
||||
modelDisplayName: (m: string) => m,
|
||||
toolDisplayName: (t: string) => t,
|
||||
discoverSessions: async () => { throw new Error('discovery exploded') },
|
||||
} as unknown as Provider
|
||||
return {
|
||||
...actual,
|
||||
discoverAllSessionsWithFailures: async (filter?: string, list?: Provider[]) => actual.discoverAllSessionsWithFailures(
|
||||
filter,
|
||||
list ?? (injected.throwingProvider ? [...await actual.getAllProviders(), boom] : undefined),
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../src/session-cache.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../src/session-cache.js')>('../src/session-cache.js')
|
||||
return {
|
||||
...actual,
|
||||
beginColdHydration: async (...args: Parameters<typeof actual.beginColdHydration>) => {
|
||||
injected.coldHydrations++
|
||||
return actual.beginColdHydration(...args)
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import { parseAllSessions, clearSessionCache } from '../src/parser.js'
|
||||
import { readCacheOnDisk } from './fixtures/session-cache-io.js'
|
||||
import { isCacheComplete, type SessionCache } from '../src/session-cache.js'
|
||||
import { readCacheOnDisk, writeCacheOnDisk } from './fixtures/session-cache-io.js'
|
||||
import { setHome } from './setup/home.js'
|
||||
|
||||
let tmpDir: string
|
||||
let savedCodexHome: string | undefined
|
||||
|
||||
beforeEach(async () => {
|
||||
clearSessionCache()
|
||||
injected.throwingProvider = false
|
||||
injected.coldHydrations = 0
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'scoped-complete-'))
|
||||
process.env['CLAUDE_CONFIG_DIR'] = tmpDir
|
||||
// Gemini discovers under the home directory, so the two-provider fixtures
|
||||
// below need home pointed at the temp root as well as CLAUDE_CONFIG_DIR.
|
||||
setHome(tmpDir)
|
||||
process.env['CLAUDE_CONFIG_DIR'] = join(tmpDir, 'claude')
|
||||
process.env['CODEBURN_CACHE_DIR'] = join(tmpDir, 'cache')
|
||||
process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = join(tmpDir, 'desktop-sessions')
|
||||
// Hermetic: Codex discovery defaults to CODEX_HOME / ~/.codex, so without this
|
||||
// the scoped 'codex' run below reads the developer's real local corpus. Point it
|
||||
// at an empty temp root and restore in teardown.
|
||||
savedCodexHome = process.env['CODEX_HOME']
|
||||
process.env['CODEX_HOME'] = join(tmpDir, 'codex-home')
|
||||
await mkdir(join(tmpDir, 'codex-home', 'sessions'), { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
clearSessionCache()
|
||||
if (savedCodexHome === undefined) delete process.env['CODEX_HOME']
|
||||
else process.env['CODEX_HOME'] = savedCodexHome
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function writeClaudeSession(): Promise<void> {
|
||||
const dir = join(tmpDir, 'projects', 'proj')
|
||||
async function writeClaudeSession(): Promise<string> {
|
||||
const dir = join(tmpDir, 'claude', 'projects', 'proj')
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, 'sess.jsonl'), JSON.stringify({
|
||||
const path = join(dir, 'sess.jsonl')
|
||||
await writeFile(path, JSON.stringify({
|
||||
type: 'assistant',
|
||||
sessionId: 'sess',
|
||||
timestamp: '2026-05-15T10:00:00Z',
|
||||
|
|
@ -43,41 +81,157 @@ async function writeClaudeSession(): Promise<void> {
|
|||
content: [], usage: { input_tokens: 100, output_tokens: 50 },
|
||||
},
|
||||
}) + '\n')
|
||||
return path
|
||||
}
|
||||
|
||||
describe('provider-scoped run and the whole-cache completeness marker', () => {
|
||||
// Regression for #912: the stamp now learns about scope. A run scoped to one provider
|
||||
// must not mark the whole cache complete while a provider it skipped still has sessions
|
||||
// on disk it never scanned.
|
||||
it('does not stamp the cache complete when providers were left out of scope', async () => {
|
||||
async function writeGeminiSession(): Promise<string> {
|
||||
const dir = join(tmpDir, '.gemini', 'tmp', 'proj', 'chats')
|
||||
await mkdir(dir, { recursive: true })
|
||||
const path = join(dir, 'session-2026-05-15.json')
|
||||
await writeFile(path, JSON.stringify({
|
||||
sessionId: 'gem-1',
|
||||
startTime: '2026-05-15T10:00:00.000Z',
|
||||
messages: [
|
||||
{ id: 'u1', timestamp: '2026-05-15T10:00:00.000Z', type: 'user', content: 'work' },
|
||||
{
|
||||
id: 'g1', timestamp: '2026-05-15T10:00:05.000Z', type: 'gemini', content: 'done',
|
||||
model: 'gemini-3.1-pro-preview', tokens: { input: 10, output: 5 },
|
||||
},
|
||||
],
|
||||
}))
|
||||
return path
|
||||
}
|
||||
|
||||
function cachedFileCount(cache: SessionCache, provider: string): number {
|
||||
return Object.keys(cache.providers[provider]?.files ?? {}).length
|
||||
}
|
||||
|
||||
describe('provider-scoped runs and the completeness marker', () => {
|
||||
it('marks only the provider it walked, leaving the rest of the cache cold', async () => {
|
||||
await writeClaudeSession()
|
||||
await writeGeminiSession()
|
||||
|
||||
// Scoped to 'codex': discovery is filtered and the cached-provider loop skips every
|
||||
// other name, so the claude session on disk is never read by this run.
|
||||
await parseAllSessions(undefined, 'codex')
|
||||
|
||||
await parseAllSessions(undefined, 'gemini')
|
||||
const raw = await readCacheOnDisk()
|
||||
|
||||
// Premise: claude really was left unscanned. If this fails the scoped run read it
|
||||
// anyway and the rest proves nothing.
|
||||
expect(Object.keys(raw?.providers?.claude?.files ?? {}).length).toBe(0)
|
||||
// Premise: claude really was left unscanned. If this fails the scoped run
|
||||
// read it anyway and the rest proves nothing.
|
||||
expect(cachedFileCount(raw, 'claude')).toBe(0)
|
||||
expect(cachedFileCount(raw, 'gemini')).toBeGreaterThan(0)
|
||||
|
||||
// The guard: the stamp at the end of runParseInner refuses to mark the whole cache
|
||||
// complete when a skipped provider (claude here) still has discoverable sessions.
|
||||
expect(raw?.complete ?? false).toBe(false)
|
||||
// The provider it walked is warm; the one it never looked at is not, and
|
||||
// neither is the whole-cache answer an unscoped request asks for.
|
||||
expect(isCacheComplete(raw, 'gemini')).toBe(true)
|
||||
expect(isCacheComplete(raw, 'claude')).toBe(false)
|
||||
expect(isCacheComplete(raw)).toBe(false)
|
||||
})
|
||||
|
||||
it('a subsequent full run repairs the cache — the mislabel is transient, not persistent', async () => {
|
||||
// Honouring the maintainer review: an ordinary all-provider refresh rediscovers the
|
||||
// omitted provider, so the wrong flag does not strand it forever. Pinning the bound
|
||||
// keeps the claim accurate.
|
||||
it('converges over repeated scoped runs instead of staying permanently cold', async () => {
|
||||
await writeClaudeSession()
|
||||
await writeGeminiSession()
|
||||
|
||||
await parseAllSessions(undefined, 'codex') // scoped: claude unscanned
|
||||
for (let i = 0; i < 3; i++) {
|
||||
clearSessionCache()
|
||||
await parseAllSessions(undefined, 'gemini')
|
||||
}
|
||||
|
||||
// Only the first run found the gemini section cold. A scoped run that can
|
||||
// never stamp anything re-enters cold hydration every time — which is what
|
||||
// an extra unfiltered discovery in the stamp path cost scoped users.
|
||||
expect(injected.coldHydrations).toBe(1)
|
||||
expect(isCacheComplete(await readCacheOnDisk(), 'gemini')).toBe(true)
|
||||
})
|
||||
|
||||
it('repairs the whole-cache answer on the next unscoped run', async () => {
|
||||
await writeClaudeSession()
|
||||
await writeGeminiSession()
|
||||
|
||||
await parseAllSessions(undefined, 'gemini')
|
||||
clearSessionCache()
|
||||
await parseAllSessions() // full refresh: claude rediscovered
|
||||
await parseAllSessions()
|
||||
|
||||
const raw = await readCacheOnDisk()
|
||||
expect(Object.keys(raw?.providers?.claude?.files ?? {}).length).toBeGreaterThan(0)
|
||||
expect(cachedFileCount(raw, 'claude')).toBeGreaterThan(0)
|
||||
expect(isCacheComplete(raw)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not claim all of history when the date range filtered older sources out', async () => {
|
||||
const path = await writeGeminiSession()
|
||||
const old = new Date('2024-01-01T00:00:00Z')
|
||||
await utimes(path, old, old)
|
||||
|
||||
const start = new Date('2026-05-01T00:00:00Z')
|
||||
await parseAllSessions({ start, end: new Date('2026-05-31T23:59:59Z') }, 'gemini')
|
||||
|
||||
const raw = await readCacheOnDisk()
|
||||
// The file's mtime predates the range, so the run never parsed it.
|
||||
expect(cachedFileCount(raw, 'gemini')).toBe(0)
|
||||
// Complete for a query inside the scanned window, cold for anything wider.
|
||||
expect(isCacheComplete(raw, 'gemini', start.getTime())).toBe(true)
|
||||
expect(isCacheComplete(raw, 'gemini', new Date('2023-01-01T00:00:00Z').getTime())).toBe(false)
|
||||
expect(isCacheComplete(raw, 'gemini')).toBe(false)
|
||||
expect(isCacheComplete(raw)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not mark a provider whose discovery threw', async () => {
|
||||
await writeClaudeSession()
|
||||
injected.throwingProvider = true
|
||||
const warn = vi.spyOn(process.stderr, 'write').mockReturnValue(true)
|
||||
try {
|
||||
await parseAllSessions()
|
||||
} finally {
|
||||
warn.mockRestore()
|
||||
}
|
||||
|
||||
const raw = await readCacheOnDisk()
|
||||
expect(isCacheComplete(raw, 'claude')).toBe(true)
|
||||
// An empty source list from a provider that threw means "unknown", not
|
||||
// "nothing to scan", so neither it nor the whole cache is complete.
|
||||
expect(isCacheComplete(raw, 'boom-provider')).toBe(false)
|
||||
expect(isCacheComplete(raw)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('caches written before per-provider completeness', () => {
|
||||
// The whole-cache flag was the only marker. It still answers for every
|
||||
// provider, in both states, so an existing cache neither re-hydrates for no
|
||||
// reason nor reads as warm when it is not.
|
||||
async function writeLegacyCache(complete: boolean): Promise<SessionCache> {
|
||||
await parseAllSessions(undefined, 'claude')
|
||||
const cache = await readCacheOnDisk()
|
||||
for (const section of Object.values(cache.providers)) {
|
||||
delete section.complete
|
||||
delete section.completeFrom
|
||||
}
|
||||
cache.complete = complete
|
||||
await writeCacheOnDisk(cache)
|
||||
clearSessionCache()
|
||||
return readCacheOnDisk()
|
||||
}
|
||||
|
||||
it('reads a stamped legacy cache as complete for every provider', async () => {
|
||||
await writeClaudeSession()
|
||||
const cache = await writeLegacyCache(true)
|
||||
|
||||
expect(cache.providers['claude']?.complete).toBeUndefined()
|
||||
expect(isCacheComplete(cache)).toBe(true)
|
||||
expect(isCacheComplete(cache, 'claude')).toBe(true)
|
||||
expect(isCacheComplete(cache, 'gemini')).toBe(true)
|
||||
|
||||
injected.coldHydrations = 0
|
||||
await parseAllSessions(undefined, 'claude')
|
||||
expect(injected.coldHydrations).toBe(0)
|
||||
})
|
||||
|
||||
it('reads an unstamped legacy cache as complete for none of them', async () => {
|
||||
await writeClaudeSession()
|
||||
const cache = await writeLegacyCache(false)
|
||||
|
||||
expect(isCacheComplete(cache)).toBe(false)
|
||||
expect(isCacheComplete(cache, 'claude')).toBe(false)
|
||||
|
||||
injected.coldHydrations = 0
|
||||
await parseAllSessions(undefined, 'claude')
|
||||
expect(injected.coldHydrations).toBe(1)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -10,9 +10,9 @@ vi.mock('../src/providers/index.js', async (importOriginal) => {
|
|||
const actual = await importOriginal<typeof import('../src/providers/index.js')>()
|
||||
return {
|
||||
...actual,
|
||||
discoverAllSessions: (...args: Parameters<typeof actual.discoverAllSessions>) => {
|
||||
discoverAllSessionsWithFailures: (...args: Parameters<typeof actual.discoverAllSessionsWithFailures>) => {
|
||||
discoveries++
|
||||
return actual.discoverAllSessions(...args)
|
||||
return actual.discoverAllSessionsWithFailures(...args)
|
||||
},
|
||||
}
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue