Files
plugins/packages/kiro/errors.test.mjs
T
yetone 966cf71764 kiro: a 429 throttle is waited out and tried again, as the Kiro IDE does (0.1.32)
onemezao on Discord: a "hi" answered, and the next message straight
after was Kiro's 429 USER_REQUEST_RATE_EXCEEDED, while the Kiro IDE on
the same Builder ID account and model (claude-haiku-5.5) took two
messages in a row (plugins#842, plugins#848).

The IDE gets the same throttles; it rides them out. Its chat client
(kiro.kiro-agent 1.1.787, dist/extension.js) classifies a
ThrottlingException with reason USER_REQUEST_RATE_EXCEEDED or
CREDIT_CONSUMPTION_RATE_EXCEEDED (ClientThrottleError) or any other
throttle (ServiceThrottleError) as retryErrorType THROTTLING, and its
QClientRetryStrategy tries 3 times: Kiro's retryAfterMilliseconds when
said, else 1s doubling (20% jitter, 20s max), counting each try in
amz-sdk-request and x-amzn-kiro-attempt. It shows "Retrying in N
seconds" over 2s. The plugin sent the first 429 back at once, and
since 0.1.30 with Retry-After 30s, so magpie didn't retry either.

Now paced() sends a chat call the same way: a 429 throttle (those three
reasons, or a reasonless "too many requests"/throttling) is waited out
and sent again, up to 3 tries, one invocation id, attempt=N; max=3. A
wait Kiro says is over 20s isn't held: the 429 goes back with it as
before. Usage limits (MONTHLY/DAILY/..., USAGE_LIMIT), model capacity
and other statuses aren't retried. A cancelled request ends during the
pause and isn't sent again. The last try's 429 keeps 0.1.30's words and
Retry-After.

The 47.3K input tokens of a "hi" are Kiro's own contextUsagePercentage
times the model's window: the agent's system prompt and tools, not
something the plugin adds.

Run (mote, HOME and TMPDIR inside the run dir):
- packages/kiro: bun test, 157 pass 0 fail.
- repo root: bun test; bun scripts/check.mjs kiro.
  Root: 6867 pass, 0 fail, 6887 tests across 499 files; check ok.

Broken by hand: paced() returning the first answer (n >= 1) turns 5
tests red (the four new throttle tests in errors.test.mjs and
region.test.mjs's rate-limit case).

Not tried: a real throttled Kiro account. No Builder ID account that
Kiro throttles was at hand, so the retry is checked against the IDE's
code and mocked answers only, not against Kiro.

Reported-by: onemezao (Discord)
2026-11-08 04:52:34 +08:00

411 lines
19 KiB
JavaScript

// A reply that fails before any of its answer fails as magpie's built-in
// Kiro relay failed it (internal/gateway/claude_subscription.go relay): a
// status, not a stream — a 429 when the error reads as a quota or rate limit
// (quotaWords), else a 502 — so magpie's gateway moves on to the next account.
import { test, expect } from "bun:test"
import { _internal } from "./index.mjs"
const { events, reply } = _internal
// frame is one AWS event-stream message with string headers.
function frame(headers, payload) {
const enc = new TextEncoder()
const hs = []
for (const [k, v] of Object.entries(headers)) {
const name = enc.encode(k)
const val = enc.encode(v)
const h = new Uint8Array(1 + name.length + 1 + 2 + val.length)
h[0] = name.length
h.set(name, 1)
h[1 + name.length] = 7
new DataView(h.buffer).setUint16(2 + name.length, val.length)
h.set(val, 4 + name.length)
hs.push(h)
}
const hlen = hs.reduce((n, h) => n + h.length, 0)
const body = enc.encode(JSON.stringify(payload))
const total = 12 + hlen + body.length + 4
const out = new Uint8Array(total)
const v = new DataView(out.buffer)
v.setUint32(0, total)
v.setUint32(4, hlen)
let i = 12
for (const h of hs) {
out.set(h, i)
i += h.length
}
out.set(body, i)
return out
}
const stream = (...fs) =>
new ReadableStream({
start(c) {
for (const f of fs) c.enqueue(f)
c.close()
},
})
const exception = (type, message) => frame({ ":message-type": "exception", ":exception-type": type }, { message })
const text = (content) => frame({ ":message-type": "event", ":event-type": "assistantResponseEvent" }, { content })
const ask = (body, streaming) => reply(events(body, "claude-sonnet-4.5", 0), "claude-sonnet-4.5", streaming)
test("a throttling exception before the answer is a 429, streamed or not", async () => {
for (const s of [true, false]) {
const res = await ask(stream(exception("ThrottlingException", "Too many requests")), s)
expect(res.status).toBe(429)
const b = await res.json()
expect(b.error.message).toBe("rate limited: Too many requests")
}
})
test("a quota exception before the answer is a 429", async () => {
const res = await ask(stream(exception("ServiceQuotaExceededException", "You have reached the limit")), true)
expect(res.status).toBe(429)
})
test("another exception before the answer is a 502, not a stream", async () => {
const res = await ask(stream(exception("InternalServerException", "Encountered an unexpected error")), true)
expect(res.status).toBe(502)
expect((await res.json()).error.message).toBe("InternalServerException: Encountered an unexpected error")
})
// magpie's gateway (tooLong) takes a 400 with these words for a conversation
// past the model's window: another member with room is asked, no account
// rests, and a lone agent is told to compact. As a 502 the Kiro account
// rested, was asked again, and the agent got a vendor error it never
// compacted for (ergou0954_54426 on Discord: "kiro 那边报错说超出上下文").
const saysTooLong = (m) => /^input is too long for the model's context: /.test(m)
test("Kiro's too-long exception in the stream is a 400 that says too long, streamed or not", async () => {
for (const [kind, msg] of [
["ValidationException", "Input is too long."],
["ValidationException", "Improperly formed request. (CONTENT_LENGTH_EXCEEDS_THRESHOLD)"],
]) {
for (const s of [true, false]) {
const res = await ask(stream(exception(kind, msg)), s)
expect(res.status).toBe(400)
const b = await res.json()
expect(b.error.type).toBe("invalid_request_error")
expect(saysTooLong(b.error.message)).toBe(true)
expect(b.error.message).toContain(msg)
}
}
})
test("a reply Kiro stops for a full window before a word is a 400 that says too long", async () => {
const full = () => stream(frame({ ":message-type": "event", ":event-type": "metadataEvent" }, { stopReason: "MODEL_CONTEXT_WINDOW_EXCEEDED" }))
for (const s of [true, false]) {
const res = await ask(full(), s)
expect(res.status).toBe(400)
expect(saysTooLong((await res.json()).error.message)).toBe(true)
}
})
test("a reply Kiro stops for a full window after some of it says it was cut short", async () => {
const cut = () =>
stream(text("Half an ans"), frame({ ":message-type": "event", ":event-type": "metadataEvent" }, { stopReason: "MODEL_CONTEXT_WINDOW_EXCEEDED" }))
const res = await ask(cut(), false)
expect(res.status).toBe(200)
expect((await res.json()).stop_reason).toBe("model_context_window_exceeded")
const sse = await (await ask(cut(), true)).text()
expect(sse).toContain('"stop_reason":"model_context_window_exceeded"')
})
test("Kiro's HTTP 400 for a too-long input stays a 400 that says too long", () => {
const f = failure(400, JSON.stringify({ message: "Input is too long.", reason: "CONTENT_LENGTH_EXCEEDS_THRESHOLD" }))
expect(f.status).toBe(400)
expect(saysTooLong(f.message)).toBe(true)
})
test("a quota or throttle still isn't taken for too long", async () => {
expect((await ask(stream(exception("ServiceQuotaExceededException", "You have reached the limit")), true)).status).toBe(429)
expect((await ask(stream(exception("ThrottlingException", "Too many requests")), true)).status).toBe(429)
})
test("an exception after the answer began ends the stream with an error event", async () => {
const res = await ask(stream(text("Hello"), exception("ThrottlingException", "slow down")), true)
expect(res.status).toBe(200)
const sse = await res.text()
expect(sse).toContain("Hello")
expect(sse).toContain("event: error")
})
test("unstreamed, what was said before an exception is the answer", async () => {
const res = await ask(stream(text("Hello"), exception("InternalServerException", "boom")), false)
expect(res.status).toBe(200)
expect((await res.json()).content).toEqual([{ type: "text", text: "Hello" }])
})
// Failing before any of the answer, a request is answered with the built-in's
// status (internal/gateway/kiro.go askKiro), and X-Magpie-Sign-In: kept,
// as the built-in marked no Kiro account lapsed, even one Kiro refused.
const { generate, refresh, failure, timing, TRIES } = _internal
// a throttle's pauses (paced) are counted here, not waited
const pauses = []
const realSleep = timing.sleep
timing.sleep = async (ms) => void pauses.push(ms)
const msgReq = { model: "claude-sonnet-4.5", messages: [{ role: "user", content: "hi" }] }
const gone = (msg) => Object.assign(new Error(msg), { gone: true })
test("credentials that can't be had are a 401, the account kept even when the sign-in is gone", async () => {
let res = await generate(async () => { throw new Error("refreshing Kiro's sign-in: fetch failed") }, {}, msgReq)
expect(res.status).toBe(401)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
expect((await res.json()).error.message).toBe("refreshing Kiro's sign-in: fetch failed")
res = await generate(async () => { throw gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE") }, {}, msgReq)
expect(res.status).toBe(401)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
})
const withFetch = async (answer, fn) => {
const was = globalThis.fetch
globalThis.fetch = async (...a) => answer(...a)
try {
return await fn()
} finally {
globalThis.fetch = was
}
}
const creds = (fail) => {
let n = 0
return async () => {
if (n++ && fail) throw fail
return { token: "t", tokenType: "", profile: "arn:aws:codewhisperer:us-east-1:1:profile/x", region: "us-east-1" }
}
}
test("a refresh failing after Kiro's 403 is a 502, the account kept even when Kiro refused it", async () => {
await withFetch(() => new Response("{}", { status: 403 }), async () => {
let res = await generate(creds(new Error("refreshing Kiro's sign-in: 503 Service Unavailable")), {}, msgReq)
expect(res.status).toBe(502)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
res = await generate(creds(gone("Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE")), {}, msgReq)
expect(res.status).toBe(502)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
})
})
test("Kiro's own 401 is passed on without marking the account", async () => {
await withFetch(() => new Response(JSON.stringify({ message: "bad token" }), { status: 401 }), async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(401)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
expect((await res.json()).error.message).toBe("bad token")
})
})
test("an error Kiro gives no words for is Go's status text", () => {
expect(failure(500, "")).toEqual({ status: 500, message: "Internal Server Error" })
})
test("a refresh is worded as the built-in's", async () => {
const c = { method: "social", refresh: "r", region: "us-east-1", access: "a" }
await withFetch(() => new Response("", { status: 500 }), async () => {
await expect(refresh(c)).rejects.toThrow(/^refreshing Kiro's sign-in: 500 Internal Server Error$/)
})
await withFetch(() => new Response("", { status: 400 }), async () => {
await expect(refresh(c)).rejects.toMatchObject({ gone: true, message: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" })
})
await expect(refresh({ ...c, refresh: "" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired; sign in again with `kiro-cli login` or the Kiro IDE" })
await expect(refresh({ ...c, method: "odd" })).rejects.toMatchObject({ message: "Kiro's sign-in has expired" })
})
// a success, even after a renewal, never cleared the built-in's account
test("an answer says the account is kept, streamed or not, renewed or not", async () => {
const ok = () => new Response(stream(text("Hello")), { status: 200 })
for (const s of [true, false]) {
await withFetch(ok, async () => {
const res = await generate(creds(), {}, { ...msgReq, stream: s })
expect(res.status).toBe(200)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
})
let n = 0
await withFetch(() => (n++ ? ok() : new Response("{}", { status: 403 })), async () => {
const res = await generate(creds(), {}, { ...msgReq, stream: s })
expect(res.status).toBe(200)
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
})
}
})
// onemezao on Discord: Kiro's 429 USER_REQUEST_RATE_EXCEEDED ("Too many
// requests, please wait before trying again.") went to magpie with no word
// of when, so magpie asked the one account again after 1, 2 and 4s and on
// through its patience, six asks of the same request where Kiro had said
// how long to wait. Kiro's wait goes on as Retry-After, from wherever Kiro's
// own clients read it.
test("Kiro's wait before asking again goes on as Retry-After", async () => {
const limited = JSON.stringify({ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" })
const cases = [
[{ "x-amzn-kiro-ratelimit-retry-after": "12500" }, limited, "13"],
[{ "x-amz-retry-after": "3000" }, limited, "3"],
[{}, JSON.stringify({ message: "Too many requests", reason: "USER_REQUEST_RATE_EXCEEDED", retryAfterMilliseconds: 20000 }), "20"],
[{ "retry-after": "7" }, limited, "7"],
[{ "retry-after": new Date(Date.now() + 30_000).toUTCString() }, limited, null],
[{}, limited, "30"],
[{ "x-amzn-kiro-ratelimit-retry-after": "soon" }, limited, "30"],
[{}, JSON.stringify({ message: "Too many requests", reason: "SERVICE_REQUEST_RATE_EXCEEDED" }), null],
]
for (const [headers, body, want] of cases) {
await withFetch(() => new Response(body, { status: 429, headers }), async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(429)
expect((await res.json()).error.message).toContain(JSON.parse(body).message + " (" + JSON.parse(body).reason + ")")
const got = res.headers.get("Retry-After")
if (headers["retry-after"]?.includes("GMT")) expect(Number(got)).toBeWithin(28, 32)
else expect(got).toBe(want)
})
}
})
// onemezao on Discord: through pi, every request of one Kiro account was
// refused with Kiro's "Too many requests, please wait before trying
// again. (USER_REQUEST_RATE_EXCEEDED)", 42s each, while the Kiro IDE
// answered on the same account. The words said neither whose limit it
// was nor what to do, and with no wait said magpie asked the same
// account again at 1, 2 and 4s, the whole request each time.
test("an account's request rate says whose limit it is, what to do and the request ID", async () => {
const body = JSON.stringify({ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" })
await withFetch(
() => new Response(body, { status: 429, headers: { "x-amzn-requestid": "3f1c-req" } }),
async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(429)
// past magpie's same-account retries (longestPause, 8s)
expect(Number(res.headers.get("Retry-After"))).toBeGreaterThan(8)
const b = await res.json()
expect(b.error.type).toBe("rate_limit_error")
const m = b.error.message
expect(m).toContain("Kiro is limiting how often this Kiro account sends requests")
expect(m).toContain("(USER_REQUEST_RATE_EXCEEDED)")
expect(m).toContain("Wait a minute")
expect(m).toContain("Kiro support")
expect(m).toContain("request ID 3f1c-req")
// magpie's creditWords would take it for money owed, never retried
expect(m).not.toMatch(/balance|credit|billing|payment|suspended/i)
},
)
})
test("an account's request rate in the stream is the same plain 429, with a wait", async () => {
for (const s of [true, false]) {
const res = await ask(
stream(frame({ ":message-type": "exception", ":exception-type": "ThrottlingException" },
{ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" })),
s,
)
expect(res.status).toBe(429)
expect(Number(res.headers.get("Retry-After"))).toBeGreaterThan(8)
const m = (await res.json()).error.message
expect(m).toMatch(/^rate limited: Kiro is limiting how often this Kiro account sends requests/)
expect(m).toContain("(USER_REQUEST_RATE_EXCEEDED)")
}
})
// onemezao on Discord: a "hi" answered, and the next message straight
// after was Kiro's 429 USER_REQUEST_RATE_EXCEEDED, while the Kiro IDE on
// the same account and model took two messages in a row. The IDE doesn't
// get fewer of these: its client (agent 1.1.787, QClientRetryStrategy)
// waits a throttle out, 1s then 2s or Kiro's retryAfterMilliseconds, and
// tries again, up to 3 tries. The plugin sent the first 429 back at once.
const limitedBody = JSON.stringify({ message: "Too many requests, please wait before trying again.", reason: "USER_REQUEST_RATE_EXCEEDED" })
const answered = () =>
new Response(new ReadableStream({ start(c) { c.enqueue(text("hello")); c.close() } }), { status: 200 })
const lower = (h) => Object.fromEntries(Object.entries(h).map(([k, v]) => [k.toLowerCase(), v]))
test("a throttle is waited out and tried again, as the Kiro IDE does, each try counted under one invocation", async () => {
pauses.length = 0
const tries = []
await withFetch((url, init) => {
tries.push(lower(init.headers))
return tries.length === 1 ? new Response(limitedBody, { status: 429 }) : answered()
}, async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(200)
expect(JSON.stringify(await res.json())).toContain("hello")
})
expect(tries.length).toBe(2)
expect(tries.map((h) => h["amz-sdk-request"])).toEqual(["attempt=1; max=3", "attempt=2; max=3"])
expect(tries.map((h) => h["x-amzn-kiro-attempt"])).toEqual(["1;max=3", "2;max=3"])
expect(tries[1]["amz-sdk-invocation-id"]).toBe(tries[0]["amz-sdk-invocation-id"])
// the IDE's throttling pause: 1s, 20% either way
expect(pauses.length).toBe(1)
expect(pauses[0]).toBeWithin(800, 1200.001)
})
test("a throttle that outlasts the IDE's tries is the plain 429, after 1s and 2s", async () => {
for (const reason of ["USER_REQUEST_RATE_EXCEEDED", "CREDIT_CONSUMPTION_RATE_EXCEEDED", "SERVICE_REQUEST_RATE_EXCEEDED"]) {
pauses.length = 0
let n = 0
await withFetch(() => (n++, new Response(JSON.stringify({ message: "Too many requests", reason }), { status: 429 })), async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(429)
expect((await res.json()).error.message).toContain(reason)
})
expect(n).toBe(TRIES)
expect(pauses.length).toBe(2)
expect(pauses[0]).toBeWithin(800, 1200.001)
expect(pauses[1]).toBeWithin(1600, 2400.001)
}
})
test("Kiro's own wait is the pause, and one past 20s goes back to magpie untried", async () => {
pauses.length = 0
let n = 0
const said = JSON.stringify({ message: "Too many requests", reason: "USER_REQUEST_RATE_EXCEEDED", retryAfterMilliseconds: 3500 })
await withFetch(() => (n++ ? answered() : new Response(said, { status: 429 })), async () => {
expect((await generate(creds(), {}, msgReq)).status).toBe(200)
})
expect(pauses).toEqual([3500])
pauses.length = 0
n = 0
await withFetch(() => (n++, new Response(limitedBody, { status: 429, headers: { "x-amzn-kiro-ratelimit-retry-after": "45000" } })), async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).toBe(429)
expect(res.headers.get("Retry-After")).toBe("45")
})
expect(n).toBe(1)
expect(pauses).toEqual([])
})
test("a usage limit, a model's capacity or another 4xx is not tried again", async () => {
const cases = [
[429, { message: "Monthly limit", reason: "MONTHLY_REQUEST_COUNT" }],
[429, { message: "Daily limit", reason: "DAILY_REQUEST_COUNT" }],
[429, { message: "busy", reason: "INSUFFICIENT_MODEL_CAPACITY" }],
[400, { message: "Improperly formed request." }],
]
for (const [status, body] of cases) {
pauses.length = 0
let n = 0
await withFetch(() => (n++, new Response(JSON.stringify(body), { status })), async () => {
const res = await generate(creds(), {}, msgReq)
expect(res.status).not.toBe(200)
})
expect(n).toBe(1)
expect(pauses).toEqual([])
}
})
test("a request cancelled while a throttle is waited out ends at once, and isn't sent again", async () => {
let n = 0
const ctl = new AbortController()
timing.sleep = (ms, signal) => {
queueMicrotask(() => ctl.abort())
return realSleep(60_000, signal)
}
try {
await withFetch(() => (n++, new Response(limitedBody, { status: 429 })), async () => {
const t0 = Date.now()
await expect(generate(creds(), {}, msgReq, ctl.signal)).rejects.toThrow("cancelled")
expect(Date.now() - t0).toBeLessThan(5000)
})
} finally {
timing.sleep = async (ms) => void pauses.push(ms)
}
expect(n).toBe(1)
})