magpie icon indicating copy to clipboard operation
magpie copied to clipboard

gateway: a plugin's in-stream error frame is relayed as data — its code/status never reach routing

Open MYCF711 opened this issue 1 month ago • 8 comments

Summary

A provider plugin that returns an OpenAI-compatible stream can end it with an error frame:

data: {"error":{"message":"...","type":"upstream_error","code":"upstream_timeout","status":504}}

Once the plugin has already sent 200, that frame is the only signal it can give — the HTTP status is spent. Today magpie relays it as ordinary bytes: the account is not rested, the turn is not recorded as failed, and nothing downstream can tell "the model answered" from "the model died halfway".

This is not #3197 / #3346 (the upstream connection died). Here the plugin deliberately ended the stream and said why; the information exists and is dropped.

Where this already works

internal/gateway/chat.go:1311 — on the translation path a Chat reply's {"error": ...} is parsed, filterRefused pulls out code / status, and it becomes Event{Kind: KError, Code, Status}.

Where it doesn't

internal/gateway/gateway.go:3965 — when the provider speaks the client's own protocol (relay == true), the reply goes through s.passthrough(...), which tidies and relays bytes. Nothing parses {"error": ...} on that path.

Plugin-served models always take it: a plugin's loader.fetch returns an OpenAI-compatible Response, so client and provider protocol match by construction. For every plugin, an in-stream error frame is opaque.

Two concrete gaps

  1. passthrough ignores the error frame. No markUnfit / rest, no failed-turn accounting — the same account keeps being picked for the same request, and the routing view shows a healthy turn.
  2. streamFailure() and filterRefused() disagree on the shape. internal/gateway/gateway.go:5222 writes {"error":{"message":...,"type":"api_error"}} with no code / status, while the Chat parser at chat.go:1312 reads exactly those fields. So even magpie's own mid-stream failure frame carries none of the routing signal a plugin frame does.

Questions

  1. Should passthrough parse {"error": ...} at least to (a) end the stream with the protocol's own terminator and (b) record the failure / rest the account? I understand from #3197 that failover itself is impossible once output has started — I'm not asking for that.
  2. Should streamFailure() carry code / status so a client sees the same shape whether the failure came from the plugin or from magpie?
  3. If plugin-side codes are meant to be client-only, that belongs in the plugin docs (HOOKS.md §7 in the scaffold) — right now the scaffold tells plugin authors to set status on the frame, which implies the gateway reads it.

Repro

Any plugin that ends a stream with an error frame — e.g. a provider whose runtime has a hard per-turn wall clock: the plugin watches the clock, aborts at 285s, and emits {"error": {..., "code": "upstream_timeout", "status": 504}}. The client gets a readable message; routing sees nothing.

Not asking

  • Changing the "once output started, no failover" rule — that's a deliberate design and #3197 settles the stream-ending part.
  • Anything about pre-first-byte failover, which already works.

MYCF711 avatar Nov 02 '26 05:11 MYCF711

Reproduced the part of this that is still live on main, and fixed it on a fork branch: fix/4855-relay-error-frame (skygunner/magpie, head 5d2adb0fa, based on main at 8abdf53a8).

What main already does (checked with wire-level fakes, kept as is): the frame is relayed byte for byte under the 200, the turn is recorded as failed in Recent calls / Routing / Usage (the frame's message and its type/code as ErrType), and the account does rest — e68327b217 ("an error carried in a 200 fails as its own status would", Oct 28) landed that side after the report's line numbers were taken. So gap 1's "no failed-turn accounting" is already untrue.

What was still broken — the title's claim: the frame's own status/code members are never read. Every classifier guessed a status from the error message's words (streamStatus). Concretely, on bare main:

  • your exact frame (code:"upstream_timeout", status:504, mid-reply): the rest row read Status: 200, Error: "OK: the upstream timed out" — the failure rested as other under an "OK" status line;
  • a terse frame naming 429 (message:"busy") failed as other at a word-guessed 502, not as a rate limit;
  • the same frame as the stream's first event failed the try at the guessed 502 (errorReply even decodes the status member already and still returns the guess).

Fix

  • One reader, namedStatusOf: the status an error object names on a member of its own — a number 400–599, status first, code second (Gemini's OpenAI-compatible relays carry theirs as code); a string code is not a status.
  • Named before guessed wherever the raw frame is in hand: a held stream's error event, a whole 200 body that is only an error, a carried error (carriedStatus), and a reply already streaming — the sniffer notes the named status on the try (an X-Magpie- note header the client never sees), and the routing loop and restAfter fail and rest the turn at it.
  • Your Q2: magpie's own Chat failure frame now carries code and status beside its message, the same shape a plugin's frame has (streamFailure).
  • An error naming no status reads exactly as before.

Verification

Check Result
TestRelayStreamErrorFrameSaysItsStatus on base 8abdf53a8 FAIL: mid-reply rest at Status 200/"OK: …", terse 429 as other, first-event try at 502
the same with the change green: 504 rests as other saying "Gateway Timeout", 429 as rate, first-event try/route/usage at 504; frame still relayed byte for byte
TestRelayStreamErrorFrameWithoutStatusAsBefore green on both — a frame naming no status reads as before
neighbors (stream accounting, passthrough/severed, rest/failure/fallback/refusal/rate/quota, gemini compat, gather, plugins) 724 pass, 1 pre-existing red (TestServeWSLListensBesideLoopback, environment, red on bare main here too)
count=3, -race, gofmt, go vet -tags nogui (native/linux/windows), go build pass

Not verified: a real plugin over the gateway — the wire-level fakes reproduce your frames; the gathered path (a non-streaming client behind a streaming plugin) still word-guesses, unchanged. On your Q3: I found no HOOKS.md scaffold in magpie or in the community plugins repo as checked out here, so there was nothing to align; if it lives elsewhere, the reader now honors what it tells authors to set.

This is a fork branch, ready for review, not a claim on the issue's ownership.

skygunner avatar Nov 02 '26 21:11 skygunner

我这边的状态:能补的正好是「真实插件验证」这一项

看了 @skygunner 的 fix/4855-relay-error-frame(5d2adb0fa),他自己划的两条边界都合理:fork 分支待评审、没在真实插件上验过。

补一句我这边的条件 —— magpie-magicrew-auth 走的就是插件流式转发,帧形状和他复现的一致(上游在 HTTP 200 的 SSE 里回 {"code":…,"message":…},不是非 2xx)。所以「真实插件跑一遍、看 code/status 有没有真的进路由」这件事我这边能补,不需要 wire-level fake。

具体两条路,看你们哪条方便:

  1. 分支 rebase 到当前 main / 开个 PR,我拉下来在本机跑一轮:用 magicrew 两个站各发一次会被上游拒的请求,把 trace 里 fail 前后对照贴回来。
  2. 或者先不动代码:告诉我你想要的帧样例,我用插件构造同样的帧先确认 namedStatusOf 能读到 status/code,再等你合。

不着急,但这条别烂尾 —— 缺的恰恰是「帧自带的 status 到不了路由」这一步的实测,而不是又一个 fake。

MYCF711 avatar Nov 03 '26 05:11 MYCF711

Live-plugin frames, as promised — no fakes.

From this machine's usage log (137,771 calls since 10-24), 145 calls came back 200 with a non-empty err. Of those, 32 are an upstream error frame that arrived inside a 200 SSE stream — every one of them wps-lingxi/deepseek-v4.1-flash, and every one recorded as a served call:

  • 19 × 灵犀上游返回 AuditFailed:我还在不断学习中…(请求或内容有问题,重试无效)(HTTP 502)
  • 3 × 灵犀上游返回 AuditFailed:…(上游审核未通过)(HTTP 502)
  • 3 × 灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)
  • 2 × 灵犀上游返回 AIError:AI服务异常
  • 3 × 灵犀上游返回 AuditFailed:… (no status named)

Three of the latest, verbatim:

2026-11-04T18:29:11  wps-lingxi/deepseek-v4.1-flash  status=200  ms=9583  err=灵犀上游返回 AuditFailed:…(HTTP 502)
2026-11-04T18:46:44  wps-lingxi/deepseek-v4.1-flash  status=200  ms=3173  err=灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)
2026-11-04T18:46:47  wps-lingxi/deepseek-v4.1-flash  status=200  ms=3582  err=灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)

What routing sees: a served call. The 502/503 exists only in the plugin's error text — no fail entry, no failover, no backoff. The two 503s are six seconds apart and both went to the same model, which is the concrete shape of “the frame's status never reaches routing”.

The other 101 rows are not this bug. They are magpie's own guards (magpie ended this reply: the model's reasoning was stuck in a loop…) — I am separating them out so the count is not flattered.

If the raw bytes are what you need: the wps-lingxi plugin is third-party (providers-aaaa/magpie-wps-lingxi). Say the word and I will instrument our own plugin (magicrew) to dump the first bad frame verbatim — that one I can change.

MYCF711 avatar Nov 04 '26 12:11 MYCF711

Landed in 538026e62, released in v0.1.2962. skygunner's patch is in, with your report as the case. When an error frame comes inside a 200, the status it names is the one the call fails at, rests at, and is booked at in Routing and Usage:

  • a numeric status or code member from 400 to 599;
  • otherwise "(HTTP 503)" or "(HTTP 503)" in the words, for 429 and 5xx only.

Your wps-lingxi 503 frame, mid-reply, now fails over as a 503 and shows 503 in Routing, where it showed 200, was rested as "other" and read "OK: …". A quoted string code ("429", "1113") is the vendor's own code, so it is not taken as a status. Words magpie wrote itself (the loop guard, an empty reply) name no status.

Left out of the patch: giving magpie's own error frames a code and status. Another magpie on the LAN would read its loop guard as a named 502.

Not tried: a real wps-lingxi account, or whether an AuditFailed counted as a 502 should rest the account. Leaving this open until you see it on your group.

yetone avatar Nov 04 '26 15:11 yetone

One thing the fix does not reach, and it is every plugin we run.

httpSaid matches only the bracketed form:

var httpSaid = regexp.MustCompile(`[((]\s*HTTP\s*(429|5\d\d)\s*[))]`)

Our five live plugins all write it without brackets:

plugin text it throws
loomy-auth "${what}返回 HTTP ${res.status}"
officeace `OfficeAce 目录读取失败:HTTP ${r.status}`
ima-local-auth `ima: HTTP ${res.status} …`
today-plugin `换 token 失败:HTTP ${res.status} …`
trustoken-auth `HTTP ${res.status}`

So textStatus returns 0 for every one of them, namedStatus returns 0, carriedStatus hands back the 200, and the frame is relayed as data exactly as before. The only plugin that benefits today is wps-lingxi, and only because it happens to write (HTTP 503) with full-width brackets — that is why my sample worked and the rest of the fleet does not.

Suggestion, one line: accept the bare form too, keeping the same narrow range:

var httpSaid = regexp.MustCompile(`[((]?\s*HTTP\s*(429|5\d\d)\s*[))]?`)

The 429/5xx restriction is what makes it safe — a 4xx a message quotes is still ignored, per the comment above it. Two anchors are worth keeping, though:

  • "HTTP 500" inside a quoted body the plugin pasted (…上游返回 400:{"code":"InvalidArgument"} has no HTTP word, but a vendor that echoes HTTP 503 in its own message would now be read as the status)
  • a plugin that says HTTP 502 about its own upstream call, not about the reply that reached magpie

If you would rather not widen the regex, the alternative is the five plugins each moving to the bracketed form — five edits against one, and the next plugin written by someone else gets it wrong again. I would take the regex.

No PR from me (non-collaborator), so this is the diff in prose.

MYCF711 avatar Nov 04 '26 15:11 MYCF711

Live check on this machine, which is still on 0.1.2901 — the fix (538026e62, v0.1.2962) has not reached it yet, so this is the "before" side, and it is a second frame type from the same plugin:

2026-11-04 23:14:27  wps-lingxi/kimi-k3.1-pro  status=200
  err: 灵犀上游返回 AuditFailed:我还在不断学习中,暂时无法回答此问题,请尝试重新提问(上游审核未通过)(HTTP 502)

Two things worth noting:

  1. The frame names its status in the bracketed form — (HTTP 502) with full-width brackets — which is exactly what httpSaid accepts. So this frame would be read as a 502 the moment v0.1.2962 is on the box; it is not a format problem like the five plugins I listed above. It was recorded as 200 only because the running build predates the patch.
  2. It is an AuditFailed, not a 503 — the same plugin's other error family. Your note says you did not try "whether an AuditFailed counted as a 502 should rest the account". This row is one of those: if it rests the account, a moderation refusal takes the account out of rotation for a request-level cause.

This machine has 2,036 calls since the 22:02 start: 2,023 at 200, 13 at 499 (agent cancelled), and this single 200-with-502. When I install ≥ v0.1.2962 I will re-run the same query and post the before/after.

MYCF711 avatar Nov 04 '26 15:11 MYCF711

Verified on 0.1.2971 (restarted 23:53:28). The before/after is clean.

Same error shape, both sides of the restart. Across 141,425 usage rows, 27 carry (HTTP 5xx) in err:

when rows status booked
before 23:53:28 25 200 × 25
after 23:53:28 2 503 × 1, 502 × 1

Two verbatim rows from after the restart (account masked):

2026-11-05T00:06:20  wps-lingxi/kimi-k3.1-pro  status=503  ms=42562  in=0 out=0
  err: 灵犀上游返回 AIError:AI服务异常(上游暂时不可用,可重试)(HTTP 503)
  err_type=upstream_unavailable

2026-11-05T00:08:32  wps-lingxi/kimi-k3.1-pro  status=502  ms=13862  in=0 out=0
  err: 灵犀上游返回 AuditFailed:…(上游审核未通过)(HTTP 502)

The pre-restart twin of the second is the same sentence, 23:14:27 — booked status=200, err_type=audit_blocked, 316,783 upstream bytes. It read as a normal success.

app.log agrees with the rows, so the status is not a display artefact: failed: 503 after 42.562s at 00:07:03 (00:06:20.704 + 42.562s), and failed: 502 after 13.862s at 00:08:46.

What I cannot show: rest accounting. No line in the log after 23:53 mentions rest/cooldown, and the 502 request's three parallel attempts (10 ms apart, three accounts) all ended 499/502 — so no successful failover either. The status attribution is proven; the consequence is not.

Closing as verified. The bracket-form gap from my previous comment still stands as a separate finding — five live plugins write HTTP N without brackets.

MYCF711 avatar Nov 04 '26 16:11 MYCF711

Thanks for the follow-up and for checking the 502/503 bookings. I traced these five examples and exercised their error-producing functions through Magpie's plugin host and gateway. The ima inference example returns a real HTTP 502 before the stream; the other examples originate in account, catalog or token operations, so their status text is not necessarily the status of an inference stream. I would keep the existing bracketed/numeric handling rather than match every HTTP 503 in message text, since that can also be quoted response content. If you have a different plugin version producing one of these errors inside an actual 200 SSE response, a redacted frame and Routing/Usage entry would help us check that specific path.

For clarity, four auxiliary-error fixtures intentionally invoke the original function from an adapter inference hook; only ima runs its real loader/chat/inference path. That proves transport of the thrown errors, not that each auxiliary function is normally called during inference. I used the publicly captured plugin sources, which may differ from your installed versions. The quoted-status control covers a pre-stream HTTP response, not all 200 SSE frames. These tests do not establish moderation cooldown or successful failover. No production code changed. AI-assisted investigation.

skygunner avatar Nov 08 '26 20:11 skygunner