zcode 0.1.58: an account served fewer than three is narrowed, not held; trial entries are free (#438)

takomitkm (plugins#438, 0.1.57, default settings) had the busy hold arm
with one account, one agent and at most two in flight, at about five
asks a minute, and arm again within a minute of its end. A coding plan
model's weekly or monthly limit (1310) also rested the whole account, so
its -Trial models got the cached 1310 without being asked.

Busy hold. ZCode serves that account one Start Plan request at a time,
so every second request was refused again at its 1s re-ask and counted
toward the process-wide hold. A sustained cap with others of the same
account in flight (the gate's lane busy >= 2) now narrows that account's
gate to busy-1, at least one, for NARROW_FOR (5 minutes; startGate.now
is its injectable clock) and counts toward no hold. A lone sustained
cap still counts, so the hold stays process-wide and keeps the firewall
protection: #801's caps came with up to ~10 in flight, which the gate
never sends, and an account whose slots are taken elsewhere narrows
3 -> 2 -> 1 within a few caps and is then refused alone, which arms the
hold as before. The queue answer says the account's current number.

Rest. The models hook marks each -Trial entry free: true, so magpie's
PaidBesideFree makes a coding plan model's quota refusal rest that
model, not the account. Gift-only accounts' plain names stay unmarked.
Side effects: the Free mark in pickers, free-preferring groups pick the
trials first, and they price at 0, which they are.

Run (mote, bun 1.4.2, HOME=$(mktemp -d)): packages/zcode bun test,
240 pass, 0 fail, 17 files, at this head rebased on 60acd62b;
bun scripts/check.mjs exit 0.

Broken by hand:
- narrowing off (if (false && ...)): the three new inflight tests fail;
  the reporter's case shows the hold armed (until=1000000240000).
- lone caps narrow too (busy < 1): seven hold tests fail (the
  saturated-elsewhere replay, refused-even-one-at-a-time, start.test's
  hold tests, dual's hold test).
- free: true removed: the new gift test fails.

Tests: inflight.test's reporter's case (fake caps at >= 2 in flight,
injected clocks), the narrowing's expiry, and a lone refusal still
arming the hold; gift.test's free trial entries. start.test's in-flight
guard now uses twelve accounts of one request each, and dual.test's hold
test a gate of one, so their caps stay lone ones.

Not tried: a real ZCode account served one at a time; the core side
(magpie's TestZCodeCodingPlanLimitLeavesTrials) is in magpie with the
mover min.

Reported-by: takomitkm
This commit is contained in:
yetone
2026-11-11 03:26:57 +08:00
parent 60acd62bee
commit ea3573bfe9
8 changed files with 211 additions and 22 deletions
+22
View File
@@ -144,6 +144,14 @@ plan's own in-flight cap (3008/3009/3010) does not: such a request is asked
again instead (see [A few at once](#a-few-at-once)). A stream's body is
never read or buffered on the way.
Since 0.1.58 the trial entries are marked free in the model list: they
spend the gift, which costs nothing. magpie then reads a coding plan
model's weekly or monthly limit (code 1310) as that model's, not the
account's, so the account's `-Trial` entries are still asked while the
plan's model rests (plugins#438). In magpie's pickers the trial entries
carry the Free mark, and a routing group that prefers free models picks
them first.
**Free first.** Picking `-Trial` by hand keeps the choice the user's,
but an agent that always asks the plain model never sees the gift.
`freeFirst`, on by default since 0.1.42, turns the preference around:
@@ -251,6 +259,20 @@ already refused needs; when both are on, the 405 hold's answer wins.
refuses past three in flight: 0.1.55 drew 24 refusals in it, this version
none.
Some accounts are served fewer than three at a time (plugins#438: one
account, one agent, refused at two in flight). Since 0.1.58 a request
refused again at its 1s re-ask while others of the same account were in
flight beside it narrows that account's gate to one fewer than were in
flight, at least one, for five minutes, after which it is back to three.
Such a refusal is this computer asking too much at once, which the
narrowed gate now stops, so it counts toward no hold; up to 0.1.57 those
refusals armed the hold at about five requests a minute, and armed it
again within a minute of its end. A request refused again alone, nothing
else of its account in flight, still counts as before: someone else holds
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.
## Two accounts at once
Three ZCode accounts used at once from one address can get the address
+2
View File
@@ -55,6 +55,8 @@ afterEach(() => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS)
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
_internal.startGate.narrow.clear()
_internal.startGate.now = () => Date.now()
})
const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
+9 -4
View File
@@ -43,6 +43,8 @@ beforeEach(async () => {
_internal.busyHold.now = () => Date.now()
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
_internal.startGate.narrow.clear()
_internal.startGate.now = () => Date.now()
sent.length = 0
for (const k of Object.keys(answers)) delete answers[k]
globalThis.fetch = async (input, init = {}) => {
@@ -421,12 +423,14 @@ test("a busy hold's answer through a -Trial entry is passed on and arms no quota
caps++
return new Response(JSON.stringify({ code: "3008", msg: "user concurrency limit exceeded" }), { status: 429, headers: { "content-type": "application/json" } })
}
// one at a time, as an account ZCode serves one request at a time is
// narrowed to (plugins#438): each refused again alone is one count
_internal.startGate.inflight = 1
const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" }))
const ask = (model) => opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body(model) })
// five asks in flight: the first ask of each caps once (one signal per
// request), the re-ask of each caps again — the fifth distinct cap hit
// arms the hold, and every ask that wakes after it comes home the
// hold's 429
// five asks, queued behind each other: the first ask of each caps once
// (one signal per request), the re-ask of each caps again — the fifth's
// arms the hold while it is in flight, and it comes home the hold's 429
const all = await Promise.all([1, 2, 3, 4, 5].map(() => ask("GLM-5.3-Flash-Trial")))
expect(all.map((r) => r.status)).toEqual([429, 429, 429, 429, 429])
expect(_internal.busyHold.until).toBeGreaterThan(Date.now())
@@ -450,6 +454,7 @@ test("a busy hold's answer through a -Trial entry is passed on and arms no quota
} finally {
_internal.BUSY_WAITS.length = 0
_internal.BUSY_WAITS.push(...waits)
_internal.startGate.inflight = 3
}
})
+15
View File
@@ -58,6 +58,21 @@ test("real balance data adds a gift model absent from the coding catalog", async
expect(Object.keys(models).filter((id) => id.endsWith("-Trial"))).toEqual([alias])
})
// plugins#438 (takomitkm): a GLM Coding Plan model's weekly limit (1310)
// rested the whole account, -Trial entries too, which the gift's own
// buckets serve. The trial entries are marked free, as they are: magpie
// then rests a refused coding plan model alone and still asks the trial
// entries. The plan's own models are not free, and an account with no gift
// lists nothing free, so its quota refusal rests it as before.
test("a dual account's trial entries are free, its coding plan models are not (plugins#438)", async () => {
const h = await hooks()
const plan = await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })
const models = await h.provider.models({ models: {} }, { auth })
expect(models[alias].free).toBe(true)
for (const [id, m] of Object.entries(models)) expect(m.free === true).toBe(id.endsWith("-Trial"))
expect(Object.values(plan).some((m) => m.free)).toBe(false)
})
test("an exhausted but active limited grant remains discoverable", async () => {
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
const models = await (await hooks()).provider.models({ models: {} }, { auth })
+59 -12
View File
@@ -2004,12 +2004,46 @@ const BUSY_HINT =
// the queue. A wait that runs out is answered startQueueAnswer's 429,
// nothing sent. The gate lives in this process's memory alone, by account
// (gateKey).
const startGate = { inflight: 3, wait: 120_000, lanes: new Map() }
//
// An account ZCode serves fewer than that (plugins#438: one account, one
// agent, never more than two in flight, and refused at two) is narrowed:
// a request refused again at its 1s re-ask while others of this computer
// were in flight beside it (busyCap) tells the cap is below the gate, and
// the account's gate goes down to one fewer than were in flight, at least
// one, for NARROW_FOR. Such a cap is this computer asking too much at once,
// which the narrowed gate now stops, so it counts toward no firewall hold.
// narrow is kept apart from lanes, which go when idle; now is its clock,
// injectable for tests.
const NARROW_FOR = 5 * 60_000
const startGate = { inflight: 3, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() }
// limitOf is how many of the account's Start Plan requests go at once: the
// gate's number, or less while the account is narrowed.
function limitOf(key) {
const n = startGate.narrow.get(key)
if (!n) return startGate.inflight
if (startGate.now() >= n.until) {
startGate.narrow.delete(key)
return startGate.inflight
}
return Math.min(startGate.inflight, n.limit)
}
// narrowed lowers the account's gate below the requests that were in flight
// when one was refused again (busy, its own included), and says whether it
// did: a lone request refused again is not this computer's doing.
function narrowed(key) {
const busy = startGate.lanes.get(key)?.busy ?? 0
if (busy < 2) return false
const limit = Math.max(1, Math.min(limitOf(key), busy - 1))
startGate.narrow.set(key, { limit, until: startGate.now() + NARROW_FOR })
return true
}
// startFull says the account's Start Plan slots are all taken, or others wait.
const startFull = (key) => {
const l = startGate.lanes.get(key)
return !!l && (l.busy >= startGate.inflight || l.queue.length > 0)
return !!l && (l.busy >= limitOf(key) || l.queue.length > 0)
}
// startSlot waits for one of the account's Start Plan slots: { release },
@@ -2019,7 +2053,7 @@ function startSlot(key, signal) {
let l = lanes.get(key)
if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
const next = () => {
while (l.busy < startGate.inflight && l.queue.length) l.queue.shift()()
while (l.busy < limitOf(key) && l.queue.length) l.queue.shift()()
if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key)
}
const take = () => {
@@ -2035,7 +2069,7 @@ function startSlot(key, signal) {
}
}
if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
if (l.busy < startGate.inflight && !l.queue.length) return Promise.resolve(take())
if (l.busy < limitOf(key) && !l.queue.length) return Promise.resolve(take())
return new Promise((resolve, reject) => {
const leave = () => {
clearTimeout(timer)
@@ -2103,10 +2137,11 @@ function released(res, slot, signal) {
// startQueueAnswer is a request that waited its whole turn behind the
// account's others and was never sent: a 429 magpie reads as a rate limit,
// so it tries the next account, and a short Retry-After.
function startQueueAnswer() {
function startQueueAnswer(key) {
const n = limitOf(key)
const error = {
type: "rate_limit_error",
message: `ZCode's free Start Plan serves this account ${startGate.inflight} requests at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`,
message: `ZCode's free Start Plan serves this account ${n} request${n === 1 ? "" : "s"} at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`,
}
return new Response(JSON.stringify({ type: "error", error }), {
status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
@@ -2124,7 +2159,14 @@ function startQueueAnswer() {
// busy or another client on the account; a request refused on its first ask
// and again a second later (busyCap) is that, sustained, and BUSY_N of them
// in one minute hold the Start Plan (zcode.z.ai only, process-wide, every
// account) off BUSY_HOLD. A cap the 1s re-ask got past counts for nothing:
// account) off BUSY_HOLD. A sustained cap of a request with others of the
// same account in flight beside it counts for nothing either: it narrows the
// account's gate (startGate), which then sends no more than ZCode serves
// (plugins#438: an account served one at a time, two in flight from one
// agent, held again and again at ~5 requests/min). #801's caps came with up
// to ~10 in flight, which the gate now never sends, and an account whose
// slots are taken elsewhere is narrowed to one within a few caps and then
// refused alone, which counts as before. A cap the 1s re-ask got past counts for nothing:
// on 0.1.55 every capped request counted, a lone late slot as much as a
// saturated address, and busy afternoons held users for nothing. Replay of
// both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared
@@ -2147,7 +2189,8 @@ const busyHeld = () => busyHold.now() < busyHold.until
// 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.
function busyCap() {
function busyCap(key) {
if (key != null && narrowed(key)) return
if (busyHeld()) return
const now = busyHold.now()
busyHold.hits.push(now)
@@ -2789,7 +2832,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
}
const id = giftID(raw)
if (out[id]) continue
out[id] = model({ ...about(raw), id }, url)
// a trial entry is the gift's, which costs nothing: marked free,
// so magpie reads a GLM Coding Plan model's weekly or monthly
// limit (1310) as that model's, and the account's trial entries,
// spent from the gift's own buckets, are still asked (plugins#438)
out[id] = { ...model({ ...about(raw), id }, url), free: true }
}
// a fallback tells magpie to keep the list it was told last, which
// predates the gift read just made: an account whose gift lists
@@ -2980,7 +3027,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
if (start) {
own.slot = await startSlot(gateKey, opts.signal)
own.signal = opts.signal
if (!own.slot) return kept(startQueueAnswer())
if (!own.slot) return kept(startQueueAnswer(gateKey))
// a hold may have armed while it waited
if (edgeHeld()) return kept(edgeHeldAnswer())
if (busyHeld()) return kept(busyHeldAnswer())
@@ -3029,7 +3076,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// Only Start Plan caps count toward the firewall hold: the
// coding plan is served by another host and was never refused
// with the IP's 405.
res = await askBusy(url, opts, h, start ? busyCap : undefined)
res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
} 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
@@ -3239,4 +3286,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// config sets what zcodeConfig has read, for tests: null is ZCode's config
// out of reach, undefined forgets it
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
export const _internal = { edge, EDGE_HOLD, busyHold, startGate, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
export const _internal = { edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
+95 -1
View File
@@ -11,7 +11,7 @@ import { ZCodeAuthPlugin, _internal } from "./index.mjs"
const { BUSY_WAITS, startGate, busyHold } = _internal
const WAITS = [...BUSY_WAITS]
const GATE = { ...startGate, lanes: undefined }
const GATE = { ...startGate, lanes: undefined, narrow: undefined }
let server
const got = [] // every request the fake took: when, whose
@@ -61,6 +61,8 @@ afterEach(() => {
startGate.inflight = GATE.inflight
startGate.wait = GATE.wait
startGate.lanes.clear()
startGate.narrow.clear()
startGate.now = () => Date.now()
busyHold.until = 0
busyHold.hits.length = 0
busyHold.now = () => Date.now()
@@ -353,3 +355,95 @@ test("replay with the account saturated elsewhere: the hold still trips within a
// and the upstream asks stayed within three per request
expect(messages().length).toBeLessThanOrEqual(3 * rs.length)
}, 30_000)
// plugins#438 (takomitkm, 0.1.57, default settings): one account, one agent,
// never more than two requests in flight, about five a minute — and the
// hold armed, and armed again a minute after it ended. ZCode served that
// account one request at a time: the second of each pair was refused, and
// again at its re-ask, while the first was still in flight. A cap this
// computer brought on itself by sending two at once narrows the account's
// gate to one instead of counting toward the firewall hold; the pairs after
// it go one at a time and are all served.
test("an account ZCode serves one at a time is narrowed to one, and no hold arms (plugins#438)", 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(100)
return OK()
}
const opts = await loader(startAuth())
const pairs = []
for (let i = 0; i < 5; i++) {
clock += 12_000
pairs.push(await Promise.all([one(opts), sleep(10).then(() => one(opts))]))
}
expect(busyHold.until).toBe(0)
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)
expect(Math.max(...after.map((r) => r.flight))).toBe(1)
})
// 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 () => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1)
let clock = 1_000_000_000_000
busyHold.now = () => clock
startGate.now = () => clock
let capAt = 2
answer = async ({ flight }) => {
if (flight >= capAt) return CAP()
await sleep(100)
return OK()
}
const opts = await loader(startAuth())
await Promise.all([one(opts), sleep(10).then(() => one(opts))])
expect(startGate.narrow.size).toBe(1)
const [key] = startGate.narrow.keys()
expect(_internal.limitOf(key)).toBe(1)
clock += _internal.NARROW_FOR - 1
expect(_internal.limitOf(key)).toBe(1)
clock += 1
expect(_internal.limitOf(key)).toBe(3)
expect(startGate.narrow.size).toBe(0)
capAt = 4
got.length = 0
now.peak.clear()
const rs = await Promise.all([one(opts), sleep(10).then(() => one(opts))])
expect(rs.every((r) => r.status === 200)).toBe(true)
expect(Math.max(...now.peak.values())).toBe(2)
expect(busyHold.until).toBe(0)
})
// Narrowed to one and still refused, alone: the account's slots are taken
// elsewhere (the ZCode app, another computer), and those caps count toward
// the hold as before. Three at once first narrow the account down (3 → 2 →
// 1); the lone caps after it arm the hold.
test("an account refused even one at a time still arms the hold", 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 () => {
await sleep(20)
return CAP()
}
const opts = await loader(startAuth())
const rs = []
for (let i = 0; i < 6 && !busyHold.until; i++) {
clock += 1_000
rs.push(...(await Promise.all([one(opts), one(opts), one(opts)])))
}
expect(rs.every((r) => r.status === 429)).toBe(true)
expect(busyHold.until).toBeGreaterThan(clock)
const [key] = startGate.narrow.keys()
expect(_internal.limitOf(key)).toBe(1)
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zcode-auth",
"version": "0.1.57",
"version": "0.1.58",
"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",
+8 -4
View File
@@ -53,6 +53,8 @@ afterEach(() => {
_internal.busyHold.now = () => Date.now()
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
_internal.startGate.narrow.clear()
_internal.startGate.now = () => Date.now()
})
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16)
@@ -689,8 +691,10 @@ test("the busy hold reads its clock: a spread run holds nothing, caps during the
// The hold's guard is the one the serial tests cannot see: requests already
// in flight when the hold arms get their counted cap after it. Hold the
// clock still, put 12 Start Plan requests in flight at once — four accounts,
// three each, as startGate lets them — and answer them all 3008 after they
// clock still, put 12 Start Plan requests in flight at once — twelve
// accounts, one each, so each cap is a lone request's, the kind that counts
// (two or more of one account's narrow its gate instead, plugins#438) — and
// answer them all 3008 after they
// have all reached the fake. No first cap counts; the 1s re-asks are
// refused again and the fifth of those arms the hold. With the guard gone,
// the seven after it count toward a second hold.
@@ -702,7 +706,7 @@ test("caps that land after the hold armed change neither hits nor until (request
let clock = 1_000_000_000_000
_internal.busyHold.now = () => clock
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
const accounts = [1, 2, 3, 4].map((n) => {
const accounts = Array.from({ length: 12 }, (_, i) => i + 1).map((n) => {
const own = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600, n })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
const s = { site: "zai", device: DEVICE, jwt: own, plan: "Start Plan" }
return { type: "oauth", access: own, refresh: JSON.stringify(s), expires: 0 }
@@ -716,7 +720,7 @@ test("caps that land after the hold armed change neither hits nor until (request
return Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 })
}
const all = loaders.flatMap((opts) =>
Array.from({ length: 3 }, () =>
Array.from({ length: 1 }, () =>
opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText })))
// every request is in flight (reached the fake) before any answer comes
while (got.filter((r) => r.path.endsWith("/messages")).length < 12) await Bun.sleep(5)