diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 6e1fe51be..bb91ba36c 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -340,7 +340,7 @@ function forgetAccount(key) { const sessions = new Map() // oauth sign-in in progress → its authorize result const inflight = new Map() // fetch id → its lifecycle and owned resources const renewing = new Map() // account → its sign-in's renewal under way -const unrenewed = new Map() // account → its last renewal that failed: {at, secret, gone, error} +const unrenewed = new Map() // account → its last renewal that failed: {at, secret, gone, error, n} let config = { provider: {} } // what the plugins' config hooks made of it // loadWait bounds one plugin's load (its import and its plugin function) @@ -2814,12 +2814,33 @@ async function apiKey({ provider, method, inputs, key, account, proxy }, signal) // requests that find it due wait for the one renewal (a vendor that spends // a refresh token once turns a second away). A renewal that fails leaves // the sign-in as it was, for the vendor's answer to tell, and isn't tried -// again for RENEW_RETRY, or, turned away for good, till it is signed in -// again. +// again for RENEW_RETRY, doubled for each failure in a row up to +// RENEW_RETRY_MOST (retryAfter), or, turned away for good, till it is +// signed in again. A refresh that gives nothing back while the sign-in is +// due failed too: magpie-ima-auth's swallows ima's "sign in again" and +// returns undefined, and every request, models listing and usage read +// asked ima again, ~80 times a minute for two dead accounts +// (JZGiVvkSOA75376 on X). const RENEW_LEAD = 5 * 60 * 1000 const RENEW_WAIT = 15 * 1000 const RENEW_RETRY = 30 * 1000 +const RENEW_RETRY_MOST = 30 * 60 * 1000 + +// retryAfter is how long a sign-in whose renewal failed n times in a row +// waits before it is tried again. +function retryAfter(n) { + return Math.min(RENEW_RETRY * 2 ** Math.max(0, Math.min(n, 20) - 1), RENEW_RETRY_MOST) +} + +// failedRenewal notes that the sign-in was's renewal at key failed, one +// more in a row when the last one was of the same sign-in. +function failedRenewal(key, was, gone, error) { + const f = unrenewed.get(key) + const secret = secretOf(was) + const n = f && f.secret === secret ? (f.n ?? 1) + 1 : 1 + unrenewed.set(key, { at: Date.now(), secret, gone, error, n }) +} function leadOf(a) { const v = a?.refreshLead @@ -2836,7 +2857,7 @@ function renewAt(a, stored) { // renewal is the renewal of the sign-in at key under way, started now if // it is due and none is: null when it isn't due, or its last renewal -// failed less than RENEW_RETRY ago (or for good). A request and the +// failed less than retryAfter ago (or for good). A request and the // background keep-alive (keepSignedIn) share it, so an account is renewed // once at a time whoever asks. function renewal(provider, key) { @@ -2847,7 +2868,7 @@ function renewal(provider, key) { let r = renewing.get(key) if (r) return r const f = unrenewed.get(key) - if (f && f.secret === secretOf(stored) && (f.gone || Date.now() - f.at < RENEW_RETRY)) return null + if (f && f.secret === secretOf(stored) && (f.gone || Date.now() - f.at < retryAfter(f.n ?? 1))) return null pending++ // the host doesn't leave in the middle of it r = renew(provider, key, a).finally(() => { renewing.delete(key) @@ -3005,12 +3026,17 @@ async function renewLocked(provider, key, a, was) { forgetAccount(key) return } - unrenewed.set(key, { at: Date.now(), secret: secretOf(was), gone: e?.signIn === "expired", error: String(e?.message ?? e) }) + failedRenewal(key, was, e?.signIn === "expired", String(e?.message ?? e)) if (e?.signIn === "expired") send({ event: "signIn", provider, account: key, said: "expired" }) send({ event: "log", level: "error", message: `${auths().get(provider)?.spec ?? provider}: auth.refresh: ${e?.message ?? e}` }) return } - if (!got || typeof got !== "object") return + if (!got || typeof got !== "object") { + // nothing to keep while it is due: not renewed, and not asked again + // at once (failedRenewal) + failedRenewal(key, was, false, "") + return + } // signed out, signed in again or renewed by another host while it ran: // that one stands. Checked under the lock the save is made under, so // nothing comes between the two. diff --git a/internal/plugin/plugin_renew_test.go b/internal/plugin/plugin_renew_test.go index 22e3a25ec..3da276110 100644 --- a/internal/plugin/plugin_renew_test.go +++ b/internal/plugin/plugin_renew_test.go @@ -20,7 +20,8 @@ import ( // so, each of them sent with the new one; one with time left, or no // expiry, isn't renewed; one the vendor turns away is marked expired and // not tried again, and one that can't be renewed goes with the old token -// and isn't tried again at once. +// and isn't tried again at once, nor is one whose refresh gives nothing +// back while it is due (magpie-ima-auth's, JZGiVvkSOA75376 on X). func TestPluginRenewsSignIns(t *testing.T) { sandbox(t) var mu sync.Mutex @@ -59,6 +60,7 @@ func TestPluginRenewsSignIns(t *testing.T) { never := account("never@renew", "r-ok-never", 0) gone := account("gone@renew", "r-gone", soon) down := account("down@renew", "r-down", soon) + none := account("none@renew", "r-none", time.Now().Add(-time.Minute).UnixMilli()) send := func(account string) string { t.Helper() res, err := Fetch(ctx, FetchRequest{Provider: "renewco", Account: account, Model: "renew-1", NPM: "@ai-sdk/openai-compatible", @@ -135,7 +137,14 @@ func TestPluginRenewsSignIns(t *testing.T) { t.Fatalf("an account that couldn't renew went with %q", h) } send(down) - if got := renewals(); strings.Join(got, " ") != "r-ok r-gone r-down" { + // renewed nothing, its token past its end: sent as it is, and the + // next request doesn't ask the plugin again + if h := send(none); h != "Bearer old-none@renew" { + t.Fatalf("an account its plugin renewed nothing for went with %q", h) + } + send(none) + send(none) + if got := renewals(); strings.Join(got, " ") != "r-ok r-gone r-down r-none" { t.Fatalf("renewals = %v", got) } if a := stored(gone); a["access"] != "old-gone@renew" { diff --git a/internal/plugin/renew_backoff_test.go b/internal/plugin/renew_backoff_test.go new file mode 100644 index 000000000..5cff0ac12 --- /dev/null +++ b/internal/plugin/renew_backoff_test.go @@ -0,0 +1,58 @@ +package plugin + +import ( + "bytes" + "context" + "os/exec" + "testing" + "time" +) + +// TestRenewRetryBacksOff: a sign-in whose renewal keeps failing is tried +// again later and later, from RENEW_RETRY to RENEW_RETRY_MOST, counted +// per sign-in: a new one (signed in again) starts afresh. Two dead ima +// accounts were renewed ~80 times a minute for hours (JZGiVvkSOA75376 on +// X). +func TestRenewRetryBacksOff(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("no node on PATH") + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, node, "-e", renewBackoffJS) + cmd.Stdin = bytes.NewReader(hostJS) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, out) + } +} + +const renewBackoffJS = ` +const assert = require('node:assert/strict') +const vm = require('node:vm') +const source = require('node:fs').readFileSync(0, 'utf8') +const start = source.indexOf('const RENEW_LEAD =') +const end = source.indexOf('function leadOf(', start) +assert.ok(start >= 0 && end > start, 'the renewal section exists') +const unrenewed = new Map() +const context = vm.createContext({ unrenewed, secretOf: (a) => a.refresh, Date, Math }) +vm.runInContext(source.slice(start, end), context) +const run = (code) => vm.runInContext(code, context) + +const s = 1000, m = 60 * s +assert.deepEqual([1, 2, 3, 4, 5, 6, 7, 8, 50].map((n) => run('retryAfter(' + n + ')')), + [30 * s, 1 * m, 2 * m, 4 * m, 8 * m, 16 * m, 30 * m, 30 * m, 30 * m]) + +const was = { refresh: 'r1' } +context.was = was +for (let i = 1; i <= 3; i++) { + run('failedRenewal("k", was, false, "no")') + assert.equal(unrenewed.get('k').n, i, 'failures of one sign-in are counted in a row') +} +context.again = { refresh: 'r2' } +run('failedRenewal("k", again, false, "")') +assert.equal(unrenewed.get('k').n, 1, 'a sign-in made again starts afresh') +assert.equal(unrenewed.get('k').secret, 'r2') +run('failedRenewal("k", again, true, "gone")') +assert.equal(unrenewed.get('k').gone, true) +` diff --git a/internal/plugin/testdata/renew/index.js b/internal/plugin/testdata/renew/index.js index e14560951..fbc0d30a4 100644 --- a/internal/plugin/testdata/renew/index.js +++ b/internal/plugin/testdata/renew/index.js @@ -3,8 +3,9 @@ // $RENEW_LOG as a line naming the refresh token it spent. The refresh // token says how the vendor takes it: "r-ok…" renews (slowly, as a // vendor does, so requests arriving meanwhile find it under way), -// "r-gone…" is turned away for good, "r-down…" can't be reached, and -// "r-slow…" renews after 4 seconds. +// "r-gone…" is turned away for good, "r-down…" can't be reached, +// "r-none…" gives nothing back (as magpie-ima-auth's does when its vendor +// refuses), and "r-slow…" renews after 4 seconds. import fs from "node:fs" export const RenewPlugin = async () => ({ @@ -25,6 +26,7 @@ export const RenewPlugin = async () => ({ await new Promise((ok) => setTimeout(ok, auth.refresh.startsWith("r-slow") ? 4000 : 300)) if (auth.refresh.startsWith("r-gone")) throw Object.assign(new Error("RenewCo turned the refresh token away"), { signIn: "expired" }) if (auth.refresh.startsWith("r-down")) throw new Error("RenewCo can't be reached") + if (auth.refresh.startsWith("r-none")) return undefined const n = fs.readFileSync(process.env.RENEW_LOG, "utf8").trim().split("\n").length // a vendor that spends a refresh token once gives a new one return { access: "a-" + n, refresh: auth.refresh + "+", expires: Date.now() + 3600e3 }