diff --git a/src/parser.ts b/src/parser.ts index 80c397fc..641ce79e 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -3513,6 +3513,10 @@ async function resolveProviderLineage( return kimicodeLineageForSource(source.path, agentId) } +// Consecutive retryable fetch failures after which a network source stops +// deferring the run and is held as failed (its cached rows kept) for the day. +const RETRYABLE_FAILURE_LIMIT = 3 + const warnedProviderReadFailures = new Set() function warnProviderReadFailureOnce(providerName: string, err: unknown): void { @@ -3816,6 +3820,13 @@ export async function parseProviderSources( // fingerprint or incrementally cache, so re-fetch every run with a synthetic // fingerprint (mtime=now so the date-range filter below never excludes it). if (skipFingerprint) { + // Held as failed after repeated fetch failures: serve the kept rows and + // try the fetch again on the next day, not on every refresh. + const held = section.files[source.path] + if (held?.failed && dateKey(new Date(held.fingerprint.mtimeMs).toISOString()) === dateKey(new Date().toISOString())) { + unchangedSources.push({ source, cached: held }) + continue + } changedSources.push({ source, fp: { dev: 0, ino: 0, mtimeMs: Date.now(), sizeBytes: 0 } }) continue } @@ -4113,6 +4124,20 @@ export async function parseProviderSources( // partial hydration — the daily backfill must not finalize history // built on it (the same fence a stale read-only serve raises). if (priorEntry) section.files[source.path] = priorEntry + if (err instanceof RetryableSourceError && provider.network) { + const retryableFailures = (priorEntry?.retryableFailures ?? 0) + 1 + const failed = retryableFailures >= RETRYABLE_FAILURE_LIMIT + section.files[source.path] = { + ...(priorEntry ?? { fingerprint: fp, mcpInventory: [], turns: [] }), + retryableFailures, + ...(failed ? { failed: true, fingerprint: fp } : {}), + } + markCacheDirty(diskCache, providerName, source.path) + if (failed) { + warnProviderParseFailure(providerName, source.path, err) + continue + } + } deferredRetryableSource = true warnProviderReadFailureOnce(providerName, err) continue diff --git a/src/session-cache.ts b/src/session-cache.ts index 9fc3caaa..03ce269a 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -142,6 +142,10 @@ export type CachedFile = { // is re-parsed only when the file changes (fingerprint differs). Carries no // turns, so it contributes no usage. (issue #441 follow-up) failed?: boolean + // Network sources: consecutive refreshes whose fetch failed retryably. At + // RETRYABLE_FAILURE_LIMIT the entry is marked failed, keeps its rows, and is + // not re-fetched again until the next day. + retryableFailures?: number // Rich-session-capture, Claude session-level. // `title` is the LAST `ai-title` entry's text; `prLinks` accumulates every // `pr-link` entry's URL. `isSidechain` is true when any entry is a sidechain: @@ -1281,6 +1285,7 @@ function validateCachedFile(f: unknown): f is CachedFile { && isOptionalString(o['agentName']) && isOptionalString(o['agentStartedAt']) && isOptionalBool(o['failed']) + && isOptionalNum(o['retryableFailures']) && isOptionalString(o['parentSessionId']) && isOptionalStringRecord(o['agentSpawnLinks']) && (o['ambiguousSpawnAgentIds'] === undefined || isStringArray(o['ambiguousSpawnAgentIds'])) diff --git a/tests/providers/vercel-gateway.test.ts b/tests/providers/vercel-gateway.test.ts index 28edd2ba..ffc67ff4 100644 --- a/tests/providers/vercel-gateway.test.ts +++ b/tests/providers/vercel-gateway.test.ts @@ -158,6 +158,33 @@ describe('vercel-gateway end-to-end (parseAllSessions network path)', () => { } }) + it('holds a gateway that keeps failing as failed for the day, keeping its rows', async () => { + const day = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10) + globalThis.fetch = vi.fn(async () => ({ + ok: true, + json: async () => ({ results: [{ day, model: 'openai/gpt-4o', total_cost: 12.34, input_tokens: 1000, output_tokens: 500 }] }), + })) as typeof fetch + const range = getDashboardScanRange('week', null, null) + const total = async () => { + clearSessionCache() + return (await parseAllSessions(range, 'vercel-gateway')).reduce((sum, p) => sum + p.totalCostUSD, 0) + } + expect(await total()).toBeCloseTo(12.34, 2) + + vi.spyOn(process.stderr, 'write').mockImplementation(() => true) + const failing = vi.fn(async () => ({ ok: false, status: 500, text: async () => '' })) + globalThis.fetch = failing as unknown as typeof fetch + for (let run = 1; run <= 4; run++) expect(await total()).toBeCloseTo(12.34, 2) + // Three failures mark it failed; the fourth refresh serves the kept rows + // without fetching again. + expect(failing).toHaveBeenCalledTimes(3) + + const { loadCache } = await import('../../src/session-cache.js') + const entry = (await loadCache()).providers['vercel-gateway']?.files['vercel-ai-gateway:report'] + expect(entry?.failed).toBe(true) + expect(entry?.retryableFailures).toBe(3) + }) + it('emits no gateway rows at all without a credential', async () => { delete process.env.AI_GATEWAY_API_KEY delete process.env.VERCEL_OIDC_TOKEN