diff --git a/packages/gumloop/README.md b/packages/gumloop/README.md index 9103bf1..a139daa 100644 --- a/packages/gumloop/README.md +++ b/packages/gumloop/README.md @@ -118,12 +118,16 @@ requires a coherent local filesystem; network filesystems and simultaneous hosts using the old lock protocol are not supported. Acquisition waits up to 250 ms in 5 ms intervals. Windows sharing errors -on reads, renames and cleanup are retried within bounded 250 ms deadlines; -the mutation callback itself is never retried. Waiting blocks the plugin host's -JavaScript thread. A timeout or unrecoverable filesystem error skips that -estimate update without failing the chat, so the estimate may be too high. -A host killed before its ledger rename may likewise lose its final update; -the previous complete ledger remains available and later requests recover. +on reads, renames and cleanup are retried within bounded 250 ms deadlines. +Waiting blocks the plugin host's JavaScript thread. When the wait runs out +(another host holds the lock), or the ledger can't be read or acquired, the +change hasn't run: the host keeps it in memory, without failing the chat, and +runs it once, in order, the next time it holds the lock and can read the +ledger: on its next update, from a retry timer (25 ms, doubling to 5 s, each +waiting 25 ms), or on normal exit, which waits up to 2 s. A busy peer delays a +charge; it doesn't lose it. A host killed (not exited) with changes kept, or +before its ledger rename, loses them; the previous complete ledger remains +available and later requests recover. Short-lived hosts may terminate immediately after receiving a completion. The plugin therefore finishes accounting before releasing terminal SSE frames diff --git a/packages/gumloop/gumloop.mjs b/packages/gumloop/gumloop.mjs index a1e2344..5c4a1ee 100644 --- a/packages/gumloop/gumloop.mjs +++ b/packages/gumloop/gumloop.mjs @@ -1,7 +1,7 @@ // Gumloop's API: what an account can use, what a call costs, and what this // plugin has spent. Nothing here signs in or holds a key; index.mjs does. import { randomUUID } from "node:crypto" -import { mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs" +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs" import { basename, dirname, join } from "node:path" export const API = "https://api.gumloop.com/api/v1" @@ -225,8 +225,19 @@ export function monthKey(t) { let seq = 0 export const LOCK_WAIT_MS = 250 export const LOCK_STALE_MS = 30_000 +// A change that waited LOCK_WAIT_MS for a peer, or found the ledger +// unreadable, hasn't run: it is kept and tried again from a timer, and once +// more, waiting up to EXIT_WAIT_MS, when the process exits. +export const EXIT_WAIT_MS = 2000 +// A retry runs on the event loop, so it waits for a peer only briefly; the +// next change this store makes, at full LOCK_WAIT_MS, takes the kept ones too. +const RETRY_WAIT_MS = 25 +const RETRY_FIRST_MS = 25 +const RETRY_MAX_MS = 5000 +const PENDING_MAX = 1000 const lockWait = new Int32Array(new SharedArrayBuffer(4)) const ownedLocks = new Set() +const waitingStores = new Set() // Windows can temporarily reject opening/deleting a name being renamed or // replacing a file another process is reading. Retry the filesystem operation, // never the caller's mutation, within a monotonic deadline. @@ -249,6 +260,9 @@ const remove = (path, deadline) => { } } process.once("exit", () => { + for (const store of waitingStores) { + try { store.flush(EXIT_WAIT_MS) } catch {} + } for (const path of ownedLocks) { try { remove(path) } catch {} } @@ -264,7 +278,7 @@ process.once("exit", () => { // unique files can be removed by any number of recoverers without touching a // later acquisition. ESRCH from kill(pid, 0) recovers immediately; otherwise a // record older than LOCK_STALE_MS recovers even when the OS reused its PID. -function ledgerLock(file, onChoosing = undefined) { +function ledgerLock(file, onChoosing = undefined, waitMs = LOCK_WAIT_MS) { const directory = dirname(file) const base = basename(file) const prefix = `${base}.lock.` @@ -272,7 +286,7 @@ function ledgerLock(file, onChoosing = undefined) { const name = `${process.pid}.${randomUUID()}` const participant = join(directory, `${prefix}${name}.json`) const temporary = join(directory, `${prefix}${name}.tmp`) - const deadline = performance.now() + LOCK_WAIT_MS + const deadline = performance.now() + waitMs const release = () => { for (const path of [participant, temporary]) { try { @@ -373,6 +387,10 @@ export class Store { this.onChoosing = onChoosing this.mem = { accounts: {} } this.readable = true + // Changes that haven't run yet, oldest first (see EXIT_WAIT_MS). + this.pending = [] + this.timer = undefined + this.retryMs = RETRY_FIRST_MS } withLock(fn) { @@ -387,6 +405,101 @@ export class Store { } } + // update runs fn(d) on a fresh read under the lock and writes d. When the + // lock or the read fails, fn hasn't run: it is kept, and runs once, after + // the changes kept before it, the next time this store holds the lock and + // can read the ledger. A busy peer delays a change; it never loses it. + update(fn) { + if (!this.file) { + const d = this.read() + const result = fn(d) + this.write(d) + return result + } + const release = ledgerLock(this.file, this.onChoosing) + if (!release) { + this.keep(fn) + return undefined + } + try { + const d = this.read() + if (!this.readable) { + this.keep(fn) + return undefined + } + const kept = this.runPending(d) + const before = kept ? structuredClone(d) : undefined + let result + try { + result = fn(d) + } catch (e) { + // A throwing callback leaves the disk as it was, but not the kept + // changes that ran before it. + if (before) this.write(before) + throw e + } + this.write(d) + return result + } finally { + release() + } + } + + keep(fn) { + this.pending.push(fn) + // An unreadable ledger that never heals must not grow without bound. + if (this.pending.length > PENDING_MAX) this.pending.shift() + waitingStores.add(this) + this.schedule() + } + + schedule() { + if (this.timer || this.pending.length === 0) return + this.timer = setTimeout(() => { + this.timer = undefined + this.flush(RETRY_WAIT_MS) + }, this.retryMs) + this.timer.unref?.() + this.retryMs = Math.min(RETRY_MAX_MS, this.retryMs * 2) + } + + runPending(d) { + const fns = this.pending.splice(0) + waitingStores.delete(this) + if (this.timer) clearTimeout(this.timer) + this.timer = undefined + this.retryMs = RETRY_FIRST_MS + for (const fn of fns) { + try { fn(d) } catch {} // ran once, as it would have the first time + } + return fns.length > 0 + } + + // flush writes the kept changes; it returns false when they're still kept. + flush(waitMs = LOCK_WAIT_MS) { + if (this.pending.length === 0) return true + if (!existsSync(dirname(this.file))) { + // The config directory is gone: there is no ledger to keep them for. + this.runPending({ accounts: {} }) + return true + } + const release = ledgerLock(this.file, undefined, waitMs) + if (release) { + try { + const d = this.read() + if (this.readable) { + this.runPending(d) + this.write(d) + return true + } + } finally { + release() + } + } + this.schedule() + return false + } + read() { if (!this.file) { if (!isObj(this.mem)) this.mem = {} @@ -444,14 +557,7 @@ export class Store { } change(uid, fn) { - return this.withLock(() => { - const d = this.read() - if (this.file && !this.readable) return undefined - const a = Store.account(d, uid, this.now()) - const result = fn(a, d) - this.write(d) - return result - }) + return this.update((d) => fn(Store.account(d, uid, this.now()), d)) } account(uid) { @@ -465,9 +571,7 @@ export class Store { anchor(uid, balance, source, at = this.now()) { const b = Number(balance) if (!Number.isFinite(b) || b < 0) return false - return this.withLock(() => { - const d = this.read() - if (this.file && !this.readable) return false + return this.update((d) => { const a = Store.account(d, uid, this.now()) if (a.applied.includes(source)) return false a.anchor = { balance: Math.round(b), at } @@ -477,7 +581,6 @@ export class Store { if (!(a.exhaustedAt > at)) delete a.exhaustedAt delete a.unbilledStops a.applied = [...a.applied, source].slice(-20) - this.write(d) return true }) } @@ -499,11 +602,9 @@ export class Store { } setPrices(table, ids = Object.keys(table)) { - this.withLock(() => { - const d = this.read() - if (this.file && !this.readable) return - d.prices = { at: this.now(), table, ids, version: 2 } - this.write(d) + const at = this.now() + this.update((d) => { + d.prices = { at, table, ids, version: 2 } }) } diff --git a/packages/gumloop/index.mjs b/packages/gumloop/index.mjs index 2c84fd7..c58a378 100644 --- a/packages/gumloop/index.mjs +++ b/packages/gumloop/index.mjs @@ -340,6 +340,8 @@ function createPlugin({ directory, magpie, options = {}, fetchImpl = globalThis. } function charge(uid, model, usage, cut) { + // A change can wait for a busy peer: the call is dated when it ended. + const at = now() store.change(uid, (a) => { if (!usage) { // Gumloop bills the tokens a stopped stream produced, but its usage @@ -348,7 +350,7 @@ function createPlugin({ directory, magpie, options = {}, fetchImpl = globalThis. return } const entry = store.price(model) - const rec = { at: now(), model } + const rec = { at, model } if (entry) { const c = usageCost(entry, usage) rec.credits = creditsFor(c.usd) @@ -412,8 +414,9 @@ function createPlugin({ directory, magpie, options = {}, fetchImpl = globalThis. if (!res.ok) { const text = await res.clone().text().catch(() => "") if (isCreditRefusal(res.status, text)) { + const at = now() store.change(cred.userId, (a) => { - a.exhaustedAt = now() + a.exhaustedAt = at }) await res.body?.cancel().catch(() => {}) // 429 so magpie moves the request to the next account; the sign-in is fine. diff --git a/packages/gumloop/package.json b/packages/gumloop/package.json index 2e4c526..77377af 100644 --- a/packages/gumloop/package.json +++ b/packages/gumloop/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-gumloop-auth", - "version": "0.1.0", + "version": "0.1.1", "description": "Gumloop (gumloop.com) with your API key and user id in OpenCode and magpie: per-account models, and a credit estimate Gumloop's API doesn't give", "homepage": "https://www.gumloop.com/", "type": "module", diff --git a/packages/gumloop/regression.test.mjs b/packages/gumloop/regression.test.mjs index 470e326..dc3a679 100644 --- a/packages/gumloop/regression.test.mjs +++ b/packages/gumloop/regression.test.mjs @@ -5,6 +5,7 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, import { tmpdir } from "node:os" import { join } from "node:path" import { createInterface } from "node:readline" +import { pathToFileURL } from "node:url" import { GumloopPlugin, _internal } from "./index.mjs" import { LOCK_STALE_MS, LOCK_WAIT_MS, Store } from "./gumloop.mjs" @@ -49,8 +50,13 @@ async function holdLock(directory, runtime = process.execPath, phase = "held") { } else if (phase === "choosing") { source = source.replace("publish(0)", `publish(0); ${pause}`) } - const module = phase === "held" ? new URL("./gumloop.mjs", import.meta.url).href - : `data:text/javascript;base64,${Buffer.from(source).toString("base64")}` + // A file, not a data: URL on the command line: Windows caps that at 32K. + let module = new URL("./gumloop.mjs", import.meta.url).href + if (phase !== "held") { + const copy = join(tempDir(), "gumloop.mjs") + writeFileSync(copy, source) + module = pathToFileURL(copy).href + } const script = ` const { Store } = await import(${JSON.stringify(module)}); new Store(${JSON.stringify(join(directory, "gumloop-ledger.json"))}).withLock(() => { ${pause} }); @@ -79,7 +85,7 @@ async function holdLock(directory, runtime = process.execPath, phase = "held") { } describe("exclusive ledger updates", () => { - test("a live old owner bounds waiting; after forced death the next chat recovers", async () => { + test("a live old owner bounds waiting; after its forced death every waiting change lands once", async () => { const directory = tempDir() const file = join(directory, "gumloop-ledger.json") const store = new Store(file) @@ -91,7 +97,7 @@ describe("exclusive ledger updates", () => { const start = performance.now() try { expect(store.change(auth.metadata.userId, () => callbacks++)).toBeUndefined() - expect(store.anchor(auth.metadata.userId, 1, "blocked")).toBeUndefined() + expect(store.anchor(auth.metadata.userId, 6000, "blocked")).toBeUndefined() store.setPrices({ "gpt-6-sol": { p: [99, 99] } }) const p = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) expect((await chat(p)).res.status).toBe(200) @@ -104,10 +110,21 @@ describe("exclusive ledger updates", () => { await owner.stop() } expect(() => process.kill(owner.child.pid, 0)).toThrow() + // The changes that waited past LOCK_WAIT_MS haven't run; they land from + // their stores' retry timers once the owner is gone, without a new call. + const landed = () => callbacks === 1 && store.account(auth.metadata.userId).month.calls === 1 + && store.account(auth.metadata.userId).applied.includes("blocked") && store.prices().table["gpt-6-sol"]?.p?.[0] === 99 + for (const until = performance.now() + 10_000; !landed() && performance.now() < until;) await new Promise((r) => setTimeout(r, 10)) + expect(callbacks).toBe(1) + expect(store.account(auth.metadata.userId).month.calls).toBe(1) + expect(store.account(auth.metadata.userId).applied).toEqual(["initial", "blocked"]) + expect(store.prices().table).toEqual({ "gpt-6-sol": { p: [99, 99] } }) const recovered = _internal.createPlugin({ directory, magpie: true, fetchImpl: fake }) expect((await chat(recovered)).res.status).toBe(200) - expect(store.remaining(auth.metadata.userId)).toBe(4999) - expect(store.account(auth.metadata.userId).month).toMatchObject({ calls: 1, credits: 1 }) + const account = store.account(auth.metadata.userId) + expect(account.month.calls).toBe(2) + expect(account.charges).toHaveLength(2) + expect(store.remaining(auth.metadata.userId)).toBe(6000 - account.spent) expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) }, 15000) @@ -134,7 +151,9 @@ describe("exclusive ledger updates", () => { expect((await chat(p)).res.status).toBe(200) expect(performance.now() - t1).toBeLessThan(200) expect(existsSync(lockPath)).toBe(false) - expect(store.remaining(auth.metadata.userId)).toBe(4999) + // The charge that waited out the fresh record was kept, not dropped. + expect(store.remaining(auth.metadata.userId)).toBe(4998) + expect(store.account(auth.metadata.userId).month.calls).toBe(2) expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) }) @@ -191,7 +210,9 @@ describe("exclusive ledger updates", () => { let ran = false expect(futureStore.change("u", () => { ran = true })).toBeUndefined() expect(ran).toBe(false) + expect(futureStore.pending).toHaveLength(1) expect(existsSync(lockPath)).toBe(true) + futureStore.pending.length = 0 }) test("waits for a peer in ticket 0 (choosing) state before entering critical section", () => { @@ -221,6 +242,12 @@ describe("exclusive ledger updates", () => { expect(enteredA).toBe(true) expect(enteredB).toBe(false) expect(storeB.remaining("u")).toBe(99) + // storeB's change waited, and runs once A is done. + expect(storeB.flush()).toBe(true) + expect(enteredB).toBe(true) + expect(storeB.remaining("u")).toBe(89) + expect(storeB.flush()).toBe(true) + expect(storeB.remaining("u")).toBe(89) }) for (const runtime of [node, process.execPath]) { @@ -278,6 +305,54 @@ describe("exclusive ledger updates", () => { }) for (const [name, runtime] of [["Node", node], ["Bun", process.execPath]]) { + test(`${name}: a host that exits while its charge waits for a busy peer still writes it`, async () => { + const directory = tempDir() + const file = join(directory, "gumloop-ledger.json") + new Store(file).anchor(auth.metadata.userId, 5000, "initial", 1) + const owner = await holdLock(directory, runtime) + const source = ` + const { _internal } = await import(${JSON.stringify(new URL("./index.mjs", import.meta.url).href)}); + const p = _internal.createPlugin({ + directory: ${JSON.stringify(directory)}, magpie: true, + fetchImpl: async (url) => url.includes("openrouter.ai") ? new Response('{"data":[]}') + : url.includes("/models") ? new Response('{"model_groups":[]}') + : new Response(JSON.stringify({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5 } })) + }); + const loaded = await p.auth.loader(async () => (${JSON.stringify(auth)})); + const res = await loaded.fetch(loaded.baseURL + "/chat/completions", { + method: "POST", body: JSON.stringify({ model: "gpt-6-sol", messages: [] }) + }); + await res.text(); + console.log(JSON.stringify({ status: res.status })); + // Exit at once: no retry timer gets to run, only the exit hook. + process.stdin.once("data", () => process.exit(0)); + ` + const child = spawn(runtime, ["--input-type=module", "--eval", source], { stdio: ["pipe", "pipe", "pipe"] }) + const lines = createInterface({ input: child.stdout }) + const done = once(child, "exit") + let stderr = "" + child.stderr.on("data", (chunk) => { stderr += chunk }) + try { + expect(JSON.parse((await once(lines, "line"))[0])).toEqual({ status: 200 }) + expect(new Store(file).account(auth.metadata.userId).month.calls).toBe(0) + await owner.stop() + child.stdin.end("go\n") + expect((await done)[0]).toBe(0) + expect(stderr).toBe("") + const account = new Store(file).account(auth.metadata.userId) + expect(account.month).toMatchObject({ calls: 1, credits: 1 }) + expect(account.charges).toHaveLength(1) + expect(readdirSync(directory)).toEqual(["gumloop-ledger.json"]) + } finally { + if (child.exitCode === null) { + child.kill() + await done + } + lines.close() + await owner.stop() + } + }, 15000) + test(`${name}: two independent overlapping processes preserve all 200 chat charges`, async () => { const directory = tempDir() const file = join(directory, "gumloop-ledger.json")