fix(vercel-gateway): stop retrying a gateway that keeps failing every refresh

A permanently unreachable gateway (DNS failure, persistent 5xx) deferred
every refresh forever: stale rows served, the run never fully hydrated. A
network source now counts consecutive retryable failures on its cache entry;
the third marks it failed with its rows kept, so it serves those rows without
fetching until the next day (a credential change still invalidates it) and
shows in doctor as a cached failure. A successful fetch resets the count.
This commit is contained in:
Resham Joshi 2026-11-06 05:50:38 -08:00
parent 7e67d64c73
commit 924fba8679
3 changed files with 57 additions and 0 deletions

View file

@ -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<string>()
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

View file

@ -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']))

View file

@ -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