diff --git a/packages/zcode/README.md b/packages/zcode/README.md index f2348cb..869ac43 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -275,6 +275,19 @@ the slots. An account whose slots are taken elsewhere is narrowed to one within a few refusals and then refused alone, so the firewall hold still comes before the 405. +Since 0.1.64 the request that brought about such a narrowing is not +failed either. Up to 0.1.63 it went back to magpie as a 429 after its +re-asks, so two sessions on an account served one at a time showed a 429 +every time the narrowing ran out (JJLIN070414 on X), and with one account +the agent was told it. Now it gives its slot back at once, without the 2s +re-ask, and waits at the head of the queue until one of the account's +other requests has ended, then is sent again, as ZCode's own client +(its dynamic-workflow governor) cuts its cap and queues a capped request +rather than failing it. The waits share the gate's two minutes, after +which it is answered here with the queue's 429. A request refused alone, +or free first's gift (which goes to the coding plan), is answered as +before. + ## Two accounts at once Three ZCode accounts used at once from one address can get the address diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 29063cc..d63511a 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -2044,7 +2044,11 @@ function kept(res, text) { // this computer through this one process, so the plugin does what that // client does: the Start Plan gets a few requests of an account in flight at // once (startGate), the rest wait their turn here instead of being sent to be -// refused, and a refusal anyway is asked again twice (BUSY_WAITS). +// refused, and a refusal anyway is asked again twice (BUSY_WAITS). A refusal +// of a request sent beside others of the same account lowers that account's +// gate and waits its turn again (askBusy's requeue), as ZCode's own +// dynamic-workflow governor cuts its cap and queues a capped subagent +// request rather than failing it. // // The coding plan keeps no gate of the plugin's: its cap depends on its tier // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher @@ -2068,6 +2072,10 @@ const BUSY_CODES = new Set(["3008", "3009", "3010"]) // requests a capped account could serve on the wire, and the agents' own // retries came on top. const BUSY_WAITS = [1000, 2000] +// REQUEUE_MAX bounds how often one request is handed back to the gate by a +// narrowing (askBusy): each narrowing lowers the gate, three to one at most +// takes two, so more is a fault of the count, not ZCode. +const REQUEUE_MAX = 4 // The hint names neither "plan" nor "limit": after the vendor's "…limit // exceeded" either would read to magpie as a plan used up. const BUSY_HINT = @@ -2129,8 +2137,10 @@ const startFull = (key) => { } // startSlot waits for one of the account's Start Plan slots: { release }, -// null when startGate.wait ran out first, or the agent's abort thrown. -function startSlot(key, signal) { +// null when the wait (startGate.wait unless given) ran out first, or the +// agent's abort thrown. A request handed back by a narrowing (requeued) was +// first in line already, so it waits at the head of the queue. +function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) { const lanes = startGate.lanes let l = lanes.get(key) if (!l) lanes.set(key, (l = { busy: 0, queue: [] })) @@ -2172,9 +2182,10 @@ function startSlot(key, signal) { leave() next() resolve(null) - }, startGate.wait) + }, Math.max(0, wait)) signal?.addEventListener?.("abort", aborted, { once: true }) - l.queue.push(go) + if (front) l.queue.unshift(go) + else l.queue.push(go) }) } @@ -2270,10 +2281,12 @@ const busyHeld = () => busyHold.now() < busyHold.until // busyCap records one sustained concurrency cap of a Start Plan request. // Only a run arms a hold; the window is cleared on arming, and a cap that // lands while the hold is on counts toward nothing — the hold's own 429s and -// the first caps after it cannot keep re-arming it. +// the first caps after it cannot keep re-arming it. It says true when the +// cap narrowed the account instead: the request is then requeued, not +// failed (see askBusy). function busyCap(key) { - if (key != null && narrowed(key)) return - if (busyHeld()) return + if (key != null && narrowed(key)) return true + if (busyHeld()) return false const now = busyHold.now() busyHold.hits.push(now) while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift() @@ -2281,6 +2294,7 @@ function busyCap(key) { busyHold.until = now + BUSY_HOLD busyHold.hits.length = 0 } + return false } // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the @@ -2349,8 +2363,13 @@ function busyAnswer(res, text) { // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained // cap, told to onCap once (the firewall hold's count); one the re-ask got -// past is not. The plan path's patience, shared with free first's replay, -// whose plan has a cap of its own. +// past is not. When onCap says the cap narrowed the account (others of this +// computer were in flight on it), asking again in 2s would only be refused +// beside them again: the busyAnswer goes back at once marked `requeue`, and +// the Start Plan path waits for one of those others to end and sends it +// again (JJLIN070414 on X: two sessions on one account, each pair's second +// request failed 429 where ZCode's own client queues it). The plan path's +// patience, shared with free first's replay, whose plan has a cap of its own. async function askBusy(u, o, hs, onCap) { let res = await fetch(u, { ...o, headers: hs }) let caps = 0 @@ -2358,7 +2377,11 @@ async function askBusy(u, o, hs, onCap) { const text = await res.text() const cap = busy(429, text) // one request's refusals are one saturation signal, not one per ask - if (cap && ++caps === 2) onCap?.() + if (cap && ++caps === 2 && onCap?.() === true) { + res = busyAnswer(res, text) + res.requeue = true + break + } // the hold armed: a request already in flight stops asking too. The // second check catches the asks that capped before the hold armed and // woke from their wait after it. Keying on onCap keeps the coding plan @@ -3250,6 +3273,25 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // coding plan is served by another host and was never refused // with the IP's 405. res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined) + // a cap this computer brought on itself, with others of the + // account in flight beside it, narrowed the account's gate: + // the request gives its slot back and waits, first in line, + // until one of those others has ended, then is sent again — + // queued, as ZCode's own client queues its subagents' caps, + // not failed. Free first's gift goes to the plan instead, + // which serves it now. The waits share one startGate.wait; + // each turn the gate is lower or the request is alone, where + // a cap is ZCode's or another client's and goes back as it + // did. + const until = Date.now() + startGate.wait + for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) { + own.slot?.release() + own.slot = await startSlot(gateKey, opts.signal, { wait: until - Date.now(), front: true }) + if (!own.slot) return kept(startQueueAnswer(gateKey)) + if (edgeHeld()) return kept(edgeHeldAnswer()) + if (busyHeld()) return kept(busyHeldAnswer()) + res = await askBusy(url, opts, h, () => busyCap(gateKey)) + } } catch (e) { // free first moved the request onto the gift, so a gift that // cannot be asked at all — the network, the host — is answered diff --git a/packages/zcode/inflight.test.mjs b/packages/zcode/inflight.test.mjs index 2ecb0fe..d58ed90 100644 --- a/packages/zcode/inflight.test.mjs +++ b/packages/zcode/inflight.test.mjs @@ -384,13 +384,77 @@ test("an account ZCode serves one at a time is narrowed to one, and no hold arms expect(busyHold.hits.length).toBe(0) const [key] = startGate.narrow.keys() expect(_internal.limitOf(key)).toBe(1) - // the first pair's second request was refused through its re-asks; every - // pair after it went one at a time and was served - expect(pairs.slice(1).flat().every((r) => r.status === 200)).toBe(true) - const after = got.filter((r) => r.path.endsWith("/messages")).slice(4) + // the first pair's second request was refused once and at its re-ask, + // then waited for the first and was served; every pair went to the end + // (before 0.1.64 that second request failed 429) + expect(pairs.flat().every((r) => r.status === 200)).toBe(true) + const after = got.filter((r) => r.path.endsWith("/messages")).slice(3) expect(Math.max(...after.map((r) => r.flight))).toBe(1) }) +// JJLIN070414 on X (0.1.63): "two or more sessions on ZCode's Start Plan +// through magpie always show 429". Two agents' sessions keep a request each +// in flight on one account, which ZCode serves one at a time. The request +// refused beside the other's is not failed: the account's gate narrows to +// one, and it waits for the other to end and is sent again — what ZCode's +// own client does with a capped subagent request. Nothing reaches the agent +// as an error, nothing is sent while the other is in flight after the +// refusal, and no hold arms. +test("two sessions on an account served one at a time: every request is served, none fails (JJLIN070414)", async () => { + BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1) + let clock = 1_000_000_000_000 + busyHold.now = () => clock + startGate.now = () => clock + answer = async ({ flight }) => { + if (flight >= 2) return CAP() + await sleep(80) + return OK() + } + const opts = await loader(startAuth()) + // each session sends its next request when its last is answered + const session = async () => { + const out = [] + for (let i = 0; i < 4; i++) { + clock += 1_000 + out.push(await one(opts)) + } + return out + } + const rs = (await Promise.all([session(), sleep(10).then(session)])).flat() + expect(rs.map((r) => r.status)).toEqual(Array(8).fill(200)) + expect(busyHold.until).toBe(0) + // one refused pair (the first ask and its 1s re-ask), then one at a time + const asks = messages() + expect(asks.filter((r) => r.flight >= 2).length).toBeLessThanOrEqual(2) + expect(asks.length).toBe(10) +}) + +// The requeued request waits no longer than the gate's own wait, counted +// from the refusal: an account whose other request runs past it answers the +// queue's 429, nothing more sent. +test("a requeued request whose turn doesn't come within the wait is answered here", async () => { + BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1) + startGate.wait = 150 + let release + const long = new Promise((r) => (release = r)) + answer = async ({ flight }) => { + if (flight >= 2) return CAP() + await long + return OK() + } + const opts = await loader(startAuth()) + const first = one(opts) + await sleep(20) + const second = await one(opts) + expect(second.status).toBe(429) + expect(second.retryAfter).toBe("5") + expect(JSON.parse(second.text).error.message).toContain("1 request at a time") + // the first ask and its re-ask; nothing after the wait ran out + expect(messages().length).toBe(3) + release() + expect((await first).status).toBe(200) +}) + // The narrowing ends by its own clock: NARROW_FOR on, the account's gate is // back to three, and two go at once again. test("a narrowed account's gate is back to three after NARROW_FOR", async () => { diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 7edc2cd..e0e80d8 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.63", + "version": "0.1.64", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan, and claims its gift plans daily", "type": "module", "main": "./opencode.mjs",