diff --git a/packages/core/src/shared-cache.ts b/packages/core/src/shared-cache.ts index db636da7e56..96e7dab00ff 100644 --- a/packages/core/src/shared-cache.ts +++ b/packages/core/src/shared-cache.ts @@ -8,6 +8,8 @@ import { makeGlobalNode } from "@opencode/util/effect/app-node" /** How long a result stays fresh, and how often callers refresh, unless a caller passes its own. */ export const interval = Duration.minutes(10) +const MAX_BACKOFF = Duration.toMillis(Duration.minutes(30)) +const MAX_RETRY_AFTER = Duration.toMillis(Duration.minutes(15)) const retrySchedule = Schedule.exponential("1 second").pipe(Schedule.jittered) export interface Input { @@ -23,10 +25,11 @@ export interface Input { export interface Interface { /** * Returns the last result for `key` while it is fresh, otherwise joins the running load or starts one, so loads - * never overlap per key. A cold load retries `transient` failures twice with jittered backoff; a refresh with a - * cached value does not retry in-flight. A failure keeps the last good value, or without one is returned, until - * the next interval. Interrupts and defects are never kept. Entries nobody asked for in 24 hours, or in two of - * their intervals if longer, are dropped. + * never overlap per key. A cold load retries `transient` failures twice with jittered backoff unless the server + * sends `Retry-After`; a refresh with a cached value does not retry in-flight. A failure keeps the last good + * value, or without one is returned, backing off across consecutive transient failures and honoring `Retry-After`. + * Interrupts and defects are never kept. Entries nobody asked for in 24 hours, or in two of their intervals if + * longer, are dropped. */ readonly get: (input: Input) => Effect.Effect } @@ -47,6 +50,8 @@ export const transient = (error: unknown) => interface Entry { last?: { readonly exit: Exit.Exit; readonly time: number } loading?: Fiber.Fiber + failures: number + retryAfter: number read: number unread: number } @@ -60,20 +65,36 @@ const layer = Layer.effect( const entries = new Map() const start = Effect.fnUntraced(function* (key: string, entry: Entry, load: Effect.Effect) { - const time = yield* Clock.currentTimeMillis + const started = yield* Clock.currentTimeMillis const previous = entry.last?.exit const hasValue = previous !== undefined && Exit.isSuccess(previous) - // Only retry cold loads: warm refreshes keep the last good value, and retrying inside a refresh multiplies - // load on a stalled upstream. - const attempt = !hasValue - ? Effect.retry(load, { schedule: retrySchedule, times: 2, while: transient }) - : load + // Only retry a cold load that has not already failed transiently: warm refreshes keep the last good value, + // and retrying inside a refresh multiplies load on a stalled upstream. + const attempt = + !hasValue && entry.failures === 0 + ? Effect.retry(load, { + schedule: retrySchedule, + times: 2, + while: (error) => transient(error) && (retryAfterMs(error, started) ?? 0) === 0, + }) + : load const exit = yield* Effect.exit(attempt) - entry.read = yield* Clock.currentTimeMillis + const completed = yield* Clock.currentTimeMillis + entry.read = completed if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* exit if (Exit.isFailure(exit)) yield* Effect.logWarning("failed to load shared value", { key, cause: exit.cause }) if (Exit.isFailure(exit) && Cause.hasDies(exit.cause)) return yield* exit - entry.last = { exit: Exit.isFailure(exit) && hasValue ? previous : exit, time } + if (Exit.isSuccess(exit)) { + entry.failures = 0 + entry.retryAfter = 0 + entry.last = { exit, time: started } + return exit.value + } + const error = Cause.squash(exit.cause) + const delay = retryAfterMs(error, completed) + entry.retryAfter = delay === undefined ? 0 : completed + delay + entry.failures = transient(error) ? entry.failures + 1 : 0 + entry.last = { exit: hasValue ? previous : exit, time: completed } return yield* entry.last.exit }) @@ -81,14 +102,15 @@ const layer = Layer.effect( const now = yield* Clock.currentTimeMillis const age = Duration.toMillis(input.interval ?? interval) for (const [key, item] of entries) if (!item.loading && now - item.read > item.unread) entries.delete(key) - const entry = entries.get(input.key) ?? { read: now, unread } + const entry = entries.get(input.key) ?? { failures: 0, retryAfter: 0, read: now, unread } entries.set(input.key, entry) entry.read = now // A caller refreshing less often than daily must never find its entry dropped between two of its refreshes. if (Number.isFinite(age)) entry.unread = Math.max(entry.unread, 2 * age) const last = entry.last // The key decides the value's type, so a stored or joined result under the same key has this caller's types. - if (!input.force && last && now - last.time < age) return yield* last.exit as Exit.Exit + if (!input.force && last && (now < entry.retryAfter || now - last.time < cooldown(age, entry.failures))) + return yield* last.exit as Exit.Exit // Yield first so `entry.loading` is set before a synchronous load can finish and clear it. entry.loading ??= run( Effect.yieldNow.pipe( @@ -107,4 +129,20 @@ const layer = Layer.effect( }), ) +function cooldown(age: number, failures: number) { + if (failures <= 1 || !Number.isFinite(age) || age <= 0) return age + return Math.min(age * 2 ** (failures - 1), Math.max(age, MAX_BACKOFF)) +} + +function retryAfterMs(error: unknown, now: number) { + if (!HttpClientError.isHttpClientError(error) || error.reason._tag !== "StatusCodeError") return undefined + const value = error.reason.response.headers["retry-after"]?.trim() + if (!value) return undefined + const seconds = Number(value) + if (Number.isFinite(seconds)) return Math.min(MAX_RETRY_AFTER, Math.max(0, Math.ceil(seconds * 1000))) + const date = Date.parse(value) + if (!Number.isNaN(date)) return Math.min(MAX_RETRY_AFTER, Math.max(0, Math.ceil(date - now))) + return undefined +} + export const node = makeGlobalNode({ service: Service, layer, deps: [] }) diff --git a/packages/core/test/plugin/provider-opencode.test.ts b/packages/core/test/plugin/provider-opencode.test.ts index b483ce83cdb..9ed2e5311ca 100644 --- a/packages/core/test/plugin/provider-opencode.test.ts +++ b/packages/core/test/plugin/provider-opencode.test.ts @@ -1256,7 +1256,7 @@ describe("OpencodePlugin", () => { ), ) - it.effect("does not amplify requests during a Console stall after startup", () => + it.effect("does not amplify requests during a Console stall after startup and backs off sustained outages", () => Effect.gen(function* () { const credentials = yield* Credential.Service const config = yield* Config.Service @@ -1286,6 +1286,24 @@ describe("OpencodePlugin", () => { yield* drain expect(state.requests).toBe(2) expect(yield* consolePolicies(config)).toEqual([sudo]) + + // A second consecutive stall sends one probe, then SharedCache backs off to 2 minutes. + yield* TestClock.adjust("1 minute") + yield* TestClock.adjust("10 seconds") + yield* drain + expect(state.requests).toBe(3) + + // Inside the 2-minute backoff window, the next tick reuses the cached config with no network request. + yield* TestClock.adjust("1 minute") + yield* drain + expect(state.requests).toBe(3) + + // Once the stall clears and backoff elapses, polling recovers. + state.stalled = false + yield* TestClock.adjust("1 minute") + yield* drain + expect(state.requests).toBe(4) + expect(yield* consolePolicies(config)).toEqual([sudo]) }), ) diff --git a/packages/core/test/shared-cache.test.ts b/packages/core/test/shared-cache.test.ts index 05dd9de38e8..545d17414ee 100644 --- a/packages/core/test/shared-cache.test.ts +++ b/packages/core/test/shared-cache.test.ts @@ -9,10 +9,10 @@ import { testEffect } from "./lib/effect" const it = testEffect(AppNodeBuilder.build(SharedCache.node)) const request = HttpClientRequest.get("https://models.example/v1") -const status = (code: number) => +const status = (code: number, headers?: Record) => HttpClient.filterStatusOk( HttpClient.make((request) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: code }))), + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status: code, headers }))), ), ) .execute(request) @@ -95,6 +95,100 @@ describe("SharedCache", () => { }), ) + it.effect("backs off across consecutive transient failures, resets on success, and measures from completion", () => + Effect.gen(function* () { + const cache = yield* SharedCache.Service + const remote = { outcome: "ok" as "ok" | "slow-timeout", loads: 0 } + const get = () => + cache.get({ + key: "config", + interval: "5 minutes", + load: Effect.suspend(() => { + remote.loads++ + if (remote.outcome === "ok") return Effect.succeed(`v${remote.loads}`) + return Effect.sleep("5 seconds").pipe(Effect.andThen(Effect.fail(new Cause.TimeoutError()))) + }), + }) + + expect(yield* get()).toBe("v1") + remote.outcome = "slow-timeout" + + // 1st transient failure on warm refresh: 1 attempt, cooldown 5 minutes from completion. + yield* TestClock.adjust("5 minutes") + const fail1 = yield* get().pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow.pipe(Effect.andThen(TestClock.adjust("5 seconds"))) + expect(yield* Fiber.join(fail1)).toBe("v1") + expect(remote.loads).toBe(2) + + // Still inside 5-minute cooldown measured from completion (not start). + yield* TestClock.adjust("298 seconds") + expect(yield* get()).toBe("v1") + expect(remote.loads).toBe(2) + + // 2nd consecutive transient failure: backs off to 10 minutes. + yield* TestClock.adjust("2 seconds") + const fail2 = yield* get().pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow.pipe(Effect.andThen(TestClock.adjust("5 seconds"))) + expect(yield* Fiber.join(fail2)).toBe("v1") + expect(remote.loads).toBe(3) + + yield* TestClock.adjust("9 minutes") + expect(yield* get()).toBe("v1") + expect(remote.loads).toBe(3) + + // 3rd consecutive transient failure: backs off to 20 minutes. + yield* TestClock.adjust("1 minute") + const fail3 = yield* get().pipe(Effect.forkChild({ startImmediately: true })) + yield* Effect.yieldNow.pipe(Effect.andThen(TestClock.adjust("5 seconds"))) + expect(yield* Fiber.join(fail3)).toBe("v1") + expect(remote.loads).toBe(4) + + yield* TestClock.adjust("19 minutes") + expect(yield* get()).toBe("v1") + expect(remote.loads).toBe(4) + + // Recovery resets backoff back to the normal 5-minute interval. + remote.outcome = "ok" + yield* TestClock.adjust("1 minute") + expect(yield* get()).toBe("v5") + expect(remote.loads).toBe(5) + yield* TestClock.adjust("5 minutes") + expect(yield* get()).toBe("v6") + expect(remote.loads).toBe(6) + }), + ) + + it.effect("honors Retry-After without fast-retrying, even for callers with a shorter interval", () => + Effect.gen(function* () { + const cache = yield* SharedCache.Service + const limited = yield* status(429, { "retry-after": "60" }) + const remote = { fail: true, loads: 0 } + const get = (interval: Duration.Input) => + cache.get({ + key: "rate-limited", + interval, + load: Effect.suspend(() => { + remote.loads++ + return remote.fail ? Effect.fail(limited) : Effect.succeed("ok") + }), + }) + + // Cold 429 with Retry-After does not immediately retry 1s later. + expect(yield* Effect.flip(get("30 seconds"))).toBe(limited) + expect(remote.loads).toBe(1) + + // Even after the caller's 30s interval passes, Retry-After (60s) still holds. + yield* TestClock.adjust("45 seconds") + expect(yield* Effect.flip(get("30 seconds"))).toBe(limited) + expect(remote.loads).toBe(1) + + remote.fail = false + yield* TestClock.adjust("15 seconds") + expect(yield* get("30 seconds")).toBe("ok") + expect(remote.loads).toBe(2) + }), + ) + it.effect("never keeps interrupts or defects, and an interrupted caller leaves the load to the others", () => Effect.gen(function* () { const cache = yield* SharedCache.Service