zcode 0.1.56: the Start Plan goes three at a time and re-asks a cap twice, as ZCode's client does

Users of other agent apps on the ZCode plugin saw "rate limited 5 times
in a minute" (star21321321124 on Discord). That is the plugin's own
3-minute busy hold (0.1.54, #801), which trips after ZCode refuses five
requests in a minute as over its in-flight cap (429 3008/3009). The
plugin drove those refusals itself:

- It sent every request magpie passed it. magpie's lane is 3 per
  account, but nothing in the plugin held the Start Plan to that.
- It re-asked a capped request up to six times over about 10s
  (BUSY_WAITS 250..4000, from #395). That kept slots taken and drew
  more caps.
- It counted every capped request toward the hold, including ones the
  next re-ask got past.

ZCode 3.17.2, read from its bundle: wqo = {3008, 3009, 3010} and
kqo = [1e3, 2e3]. So a busy cap is re-asked at most twice, after 1s and
2s, Start Plan only. There is no hold, and one main turn runs per
session.

What changes:
- BUSY_WAITS is [1000, 2000], with no jitter, and 3010 counts as busy.
  This applies to every plan, since the coding plan goes through the
  same askBusy.
- startGate: on the Start Plan, an account has at most 3 requests in
  flight (#395 measured about 3: 3 of 12 and 4 of 12 served). The
  account is keyed by uid, then accountId, then key. Further requests
  wait in a FIFO queue in the plugin and are not sent. A slot is freed
  when the upstream body ends, the agent cancels, or its signal aborts
  (the body is pumped eagerly so an unread reply cannot hold a slot).
  After 2 minutes of waiting, the plugin answers 429 rate_limit_error
  with Retry-After 5: "ZCode's free Start Plan serves this account 3
  requests at a time; this one waited 120s behind the others and was
  not sent. Run fewer agents or subagents on ZCode at once, or try
  again". The coding plan stays ungated. Its cap follows the tier (the
  #395 review), and magpie's lane covers it.
- Free first skips the gift while its account's gate is full, so the
  plain model goes to the coding plan rather than queueing.
- The hold counts a request only when ZCode refuses it again at the 1s
  re-ask. N=5, the 60s window and the 3-minute hold are unchanged, as
  is the rule that an in-flight or queued request stops once the hold
  is armed. Its message now says what happened and what to do: "ZCode
  turned away 5 requests in the last minute as too many requests at
  once, each again when asked a second later. So that ZCode's firewall
  does not block this network, magpie sends no free Start Plan
  requests for the next Ns. Wait, run fewer agents or subagents on
  ZCode at once, or use a GLM Coding Plan model". The words avoid
  "plan"+"limit" after "exceeded", which magpie's usedUpWords would
  read as spent.

History checked: #395 (0.1.32) added the long waits and had an
in-plugin gate removed in review, because it held Max coding-plan
accounts to 3 and was keyed on the jwt. This gate is Start Plan only
(one tier) and keyed per account. #801 (0.1.54) added the hold from
the logs of 11-05 23:06 and 11-06 06:23: about 16 to 18 req/min, 7 to
10 in flight, and the first 405 after 205 to 517s. The hold still
trips on sustained refusals: the replay below has the account
saturated elsewhere, and the hold arms within the replayed minute with
nothing sent after it.

Run on mote, HOME=$(mktemp -d), at the rebased head, Bun 1.4.2:
- bun test packages/zcode: 235 pass, 0 fail.
- New inflight.test.mjs: 13 pass. It covers re-ask count and timing
  (3 asks, gaps of about 1s and 2s), 3010, at most 3 in flight of 12
  sent at once, per-account slots, a slot held across re-asks, the
  queue wait running out (nothing sent, plain 429), abort while queued,
  a cancelled stream freeing its slot, the coding plan ungated, a cap
  the 1s re-ask got past not counting, and the hold message. It also
  replays #801's two days at 20x speed against a fake that refuses past
  3 in flight: 0 refusals, peak 3, no hold, all served. A second replay
  with the account saturated elsewhere arms the hold within a minute.
- bun scripts/check.mjs zcode: ok (registry.json, zcode). Repo bun test: 6780 pass, 0 fail, 20 skip, 491 files.
Broken by hand: inflight.test.mjs against 0.1.55's index.mjs gives 11
of 13 red. 0.1.55 made 7 asks, had 12 in flight, drew 24 refusals in
the replay, and armed the hold on caps a re-ask got past. Two pass on
both, as expected: the coding plan stays ungated, and the saturated
replay still holds.
Not tried: real ZCode Start Plan accounts, live; the replay is
synthetic from the #801 figures, as the raw logs are not in the repo.
Not copied from ZCode's client: its "no re-ask on a session's first
turn" rule, since the plugin cannot tell a first turn reliably.

Reported-by: star21321321124
This commit is contained in:
yetone
2026-11-07 17:54:55 +08:00
parent 589fb12334
commit a313a00306
7 changed files with 656 additions and 102 deletions
+24 -14
View File
@@ -51,6 +51,8 @@ afterEach(() => {
_internal.busyHold.until = 0
_internal.busyHold.hits.length = 0
_internal.busyHold.now = () => Date.now()
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
})
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16)
@@ -618,7 +620,7 @@ test("a run of busy caps holds the Start Plan off before the IP is blocked, and
expect(Number(r.retryAfter)).toBeLessThanOrEqual(Math.ceil(_internal.BUSY_HOLD / 1000))
const e = JSON.parse(r.text).error
expect(e.type).toBe("rate_limit_error")
expect(e.message).toContain("busy")
expect(e.message).toContain("ZCode turned away 5 requests in the last minute")
}
expect(messages()).toBe(0)
// the coding plan goes on, held or not
@@ -686,10 +688,12 @@ 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 first cap after it. Hold the clock
// still, put 12 Start Plan requests in flight at once, answer them all 3008
// after they have all reached the fake — with the guard gone, those 12 caps
// arm the hold twice and the second arming pushes `until` out.
// 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
// 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.
test("caps that land after the hold armed change neither hits nor until (requests in flight)", async () => {
const waits = _internal.BUSY_WAITS.splice(0)
_internal.BUSY_WAITS.push(1)
@@ -698,7 +702,12 @@ 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 opts = await hooks.auth.loader(async () => start("zai"), { id: "zcode" })
const accounts = [1, 2, 3, 4].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 }
})
const loaders = await Promise.all(accounts.map((a) => hooks.auth.loader(async () => a, { id: "zcode" })))
// the fake parks every /messages request on one gate until the test opens it
let open = () => {}
const gate = new Promise((r) => (open = r))
@@ -706,21 +715,22 @@ test("caps that land after the hold armed change neither hits nor until (request
await gate
return Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 })
}
const all = Array.from({ length: 12 }, () =>
opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText }))
const all = loaders.flatMap((opts) =>
Array.from({ length: 3 }, () =>
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)
expect(got.filter((r) => r.path.endsWith("/messages")).length).toBe(12)
clock += 1_000
open()
const rs = await Promise.all(all)
// all 12 armed the hold on their first caps and were held from then on:
// the caps after arming changed neither hits nor until, no request asked
// again (12 asks, not 24), and each answer is the hold's own 429 with
// its Retry-After, not busyAnswer's bare one
// every request was refused twice; the fifth second refusal armed the
// hold, and the ones after it changed neither hits nor until. Each
// answer is the hold's own 429 with its Retry-After or, for the four
// that armed it, busyAnswer's
expect(rs.every((r) => r.status === 429)).toBe(true)
expect(got.filter((r) => r.path.endsWith("/messages")).length).toBe(12)
expect(rs.every((r) => r.headers.get("retry-after") === String(_internal.BUSY_HOLD / 1000))).toBe(true)
expect(got.filter((r) => r.path.endsWith("/messages")).length).toBe(24)
expect(rs.filter((r) => r.headers.get("retry-after") === String(_internal.BUSY_HOLD / 1000)).length).toBeGreaterThanOrEqual(8)
expect(_internal.busyHold.hits.length).toBe(0)
expect(_internal.busyHold.until).toBe(clock + _internal.BUSY_HOLD)
} finally {