usage, gui: a model says how many of its replies were ended for looping (#1858)
#1858 asked for recovery across turns when a model loops. magpie is a gateway and can't rewind the agent's session, so that is not planned now. What it can do is let the reader see which model loops. Each reply the loop guard ends (#1359) is logged with err_type "reply_loop", but Usage only counted it among the failures. usage.LoopErrType is now that type (the gateway's loopErrType is it), and Totals.Loops counts, among the failed requests, those ended for looping. A handed-on try is still no request. The Overview's model, agent, account and key rows and the Requests ranking say "{n} looped" beside "{n} failed", and the ranking's "Other" adds them up. Translated into zh, zh-TW, ja and de. Run: TestLoopsCountedPerModel (Overview groups, the ledger sum and Breakdown; red with the increment removed). go test ./internal/usage ./internal/gateway ./internal/gui; gofmt -l; go vet on darwin, linux -tags nogui and windows. The new usage-loops.test.cjs ran in chromium and webkit, 5 languages at 360 and 1100px, 20 pass; it fails 10 of 10 on HEAD~ assets. usage-*, ledger-*, own-requests, i18n-keys and gui-zh-tw/ja/de in both engines: 565 pass. Not run: a real looping model through the gateway (the logging path is unchanged from #1359).
This commit is contained in:
@@ -57,7 +57,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came.
|
||||
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (`sseStart` reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun: `eventLead`) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply.
|
||||
- Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held.
|
||||
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop`. A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
|
||||
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
|
||||
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
|
||||
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
|
||||
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is back (`soonestBack`). A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`). A time the vendor names stands over it. A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// usageHalfLife is how fast the tokens a key served stop counting against
|
||||
@@ -209,7 +210,7 @@ const (
|
||||
|
||||
// loopErrType is the usage log's ErrType for a reply ended for looping
|
||||
// (#1359), told apart from what vendors call their errors.
|
||||
const loopErrType = "reply_loop"
|
||||
const loopErrType = usage.LoopErrType
|
||||
|
||||
// proxyDown is the error Go gives when the proxy itself can't be reached,
|
||||
// over HTTP (proxyconnect) or SOCKS (socks connect).
|
||||
|
||||
@@ -17025,6 +17025,8 @@ function renderUsage() {
|
||||
if (id === "usageAgents" && g.id === "magpie") who.firstChild.append(ownBadge());
|
||||
else if (g.own?.calls) sub.push(ownCalls(g.own.calls));
|
||||
if (g.errors) sub.push(t("{n} failed", { n: g.errors }));
|
||||
// of those, the replies magpie ended stuck in a loop (#1858)
|
||||
if (g.loops) sub.push(t("{n} looped", { n: g.loops }));
|
||||
if (g.retried) sub.push(t("{n} answered on a retry", { n: g.retried }));
|
||||
// how long the streamed replies took to begin, and how fast they
|
||||
// wrote after (#196)
|
||||
@@ -17826,6 +17828,8 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
const l2 = el("div", "rk-b");
|
||||
more.forEach((m, i) => l2.append(...(i ? [" · ", m] : [m])));
|
||||
if (x.errors) l2.append(" · ", Object.assign(el("span", "rk-bad"), { textContent: t("{n} failed", { n: x.errors }) }));
|
||||
// of those, the replies magpie ended stuck in a loop (#1858)
|
||||
if (x.loops) l2.append(" · ", Object.assign(el("span", "rk-bad rk-loop"), { textContent: t("{n} looped", { n: ledNum(x.loops) }), title: t("Replies magpie ended because the model kept repeating itself") }));
|
||||
b.append(l1, bar, l2);
|
||||
if (!plain) b.onclick = () => choose(x);
|
||||
b.onpointerenter = () => box.chart?.emphasize?.(x.id);
|
||||
@@ -17835,7 +17839,7 @@ function drawLedRank(box, l, split, metric, picked, choose, compact) {
|
||||
for (const x of top) box.append(one(x, x.color));
|
||||
if (rest.length) {
|
||||
const tot = rest.reduce((acc, x) => {
|
||||
for (const k of ["calls", "errors", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
|
||||
for (const k of ["calls", "errors", "loops", "input", "output", "cache_read", "cache_write", "cost", "timed", "ttft_ms", "decode_ms", "decode_out", "decode_n", "floor_out", "floor_ms", "floor_n"]) acc[k] = (acc[k] || 0) + (x[k] || 0);
|
||||
return acc;
|
||||
}, { id: "\0other", name: t("Other ({n})", { n: rest.length }) });
|
||||
box.append(one(tot, "var(--faint)", true));
|
||||
|
||||
@@ -2839,6 +2839,8 @@ const I18N = {
|
||||
"call": "次调用",
|
||||
"calls": "次调用",
|
||||
"{n} failed": "{n} 次失败",
|
||||
"{n} looped": "{n} 次陷入循环",
|
||||
"Replies magpie ended because the model kept repeating itself": "magpie 因模型一直重复自己而中止的回复",
|
||||
"week of {label}": "{label} 起的一周",
|
||||
"{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次调用",
|
||||
"{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次调用",
|
||||
@@ -7326,6 +7328,8 @@ const I18N = {
|
||||
"call": "次呼叫",
|
||||
"calls": "次呼叫",
|
||||
"{n} failed": "{n} 次失敗",
|
||||
"{n} looped": "{n} 次陷入迴圈",
|
||||
"Replies magpie ended because the model kept repeating itself": "magpie 因模型一直重複自己而中止的回覆",
|
||||
"week of {label}": "{label} 起的一週",
|
||||
"{when} · {tokens} tokens · {n} call": "{when} · {tokens} token · {n} 次呼叫",
|
||||
"{when} · {tokens} tokens · {n} calls": "{when} · {tokens} token · {n} 次呼叫",
|
||||
@@ -11819,6 +11823,8 @@ const I18N = {
|
||||
"call": "回の呼び出し",
|
||||
"calls": "回の呼び出し",
|
||||
"{n} failed": "{n} 件が失敗",
|
||||
"{n} looped": "{n} 件はループ",
|
||||
"Replies magpie ended because the model kept repeating itself": "モデルが同じことを繰り返し続けたため magpie が止めた応答",
|
||||
"week of {label}": "{label} の週",
|
||||
"{when} · {tokens} tokens · {n} call": "{when} · {tokens} トークン · {n} 回の呼び出し",
|
||||
"{when} · {tokens} tokens · {n} calls": "{when} · {tokens} トークン · {n} 回の呼び出し",
|
||||
@@ -16311,6 +16317,8 @@ const I18N = {
|
||||
"call": "Aufruf",
|
||||
"calls": "Aufrufe",
|
||||
"{n} failed": "{n} fehlgeschlagen",
|
||||
"{n} looped": "{n} in einer Schleife",
|
||||
"Replies magpie ended because the model kept repeating itself": "Antworten, die magpie beendet hat, weil sich das Modell ständig wiederholte",
|
||||
"week of {label}": "Woche ab {label}",
|
||||
"{when} · {tokens} tokens · {n} call": "{when} · {tokens} Token · {n} Aufruf",
|
||||
"{when} · {tokens} tokens · {n} calls": "{when} · {tokens} Token · {n} Aufrufe",
|
||||
|
||||
@@ -999,6 +999,13 @@ the count and the sum stay whole and the page never scrolls sideways; in
|
||||
Chromium and WebKit, in every language. `MAGPIE_ASSETS` pointed at older
|
||||
assets shows it failing.
|
||||
|
||||
`usage-loops.test.cjs` checks that Usage says, per model, how many of its
|
||||
replies magpie ended stuck in a loop (#1858): "2 looped" beside the model's
|
||||
failures in the Overview's row and the Requests ranking, the ranking's
|
||||
"Other" adding up those it holds, and nothing for a model with none. At 360
|
||||
and 1100 wide the page never scrolls sideways; in Chromium and WebKit, in
|
||||
every language. `MAGPIE_ASSETS` pointed at older assets shows it failing.
|
||||
|
||||
`usage-keys-fold.test.cjs` checks the Usage page's card of a provider with
|
||||
many keys, each its balance (361 on Discord: an OpenRouter card listed every
|
||||
key's): the first three are in sight, the rest behind "Show N more keys" at
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Usage says, per model, how many of its replies magpie ended because the
|
||||
// model was stuck in a loop (#1858, err_type "reply_loop"): beside "{n}
|
||||
// failed" in the Overview's model rows and in the Requests ranking, the
|
||||
// ranking's "Other" adding up those it holds. A model with none says
|
||||
// nothing of it. Nothing runs past the window at 360 or 1100 wide, in
|
||||
// every language, Chromium and WebKit; the API is faked.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets"));
|
||||
const looped = { en: "{n} looped", zh: "{n} 次陷入循环", "zh-TW": "{n} 次陷入迴圈", ja: "{n} 件はループ", de: "{n} in einer Schleife" };
|
||||
|
||||
const share = (id, calls, errors, loops) => ({ id, calls, errors, loops, input: 1000 * calls, output: 50 * calls, cache_read: 0, cache_write: 0, cost: 0, unpriced: calls });
|
||||
// kimi looped twice of 3 failures; glm failed once, not for looping; and
|
||||
// past the 7 shown, two more that looped once each, in "Other"
|
||||
const BY = [share("kimi-k3", 40, 3, 2), share("glm-5", 30, 1, 0), ...["a", "b", "c", "d", "e"].map((x, i) => share("m-" + x, 20 - i, 0, 0)),
|
||||
share("tail-1", 2, 1, 1), share("tail-2", 1, 1, 1)];
|
||||
|
||||
function serve(lang) {
|
||||
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd" };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/usage") {
|
||||
return json({
|
||||
period: url.searchParams.get("period"), calls: 70, errors: 4, loops: 2, input: 70000, output: 3500, cache_read: 0, reasoning: 0, unpriced: 70, cost: 0, bucket: "hour",
|
||||
series: [{ t: new Date().toISOString(), input: 70000, output: 3500, calls: 70, cost: 0 }],
|
||||
agents: [{ id: "claude", name: "Claude Code", calls: 70, errors: 4, loops: 2, input: 70000, output: 3500, cost: 0 }],
|
||||
models: [
|
||||
{ id: "p/kimi-k3", provider: "p", model: "kimi-k3", name: "kimi-k3", calls: 40, errors: 3, loops: 2, input: 40000, output: 2000, cost: 0 },
|
||||
{ id: "p/glm-5", provider: "p", model: "glm-5", name: "glm-5", calls: 30, errors: 1, input: 30000, output: 1500, cost: 0 },
|
||||
], path: "",
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/api/usage/requests") {
|
||||
return json({ period: url.searchParams.get("period"), rows: [], offset: 0, total: 113, calls: 113, errors: 7, loops: 4, input: 113000, output: 5650, cache_read: 0, cache_write: 0, cost: 0, unpriced: 113,
|
||||
by: { model: BY }, bucket: "hour", series: [], agents: [] });
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
|
||||
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [360, 1100]) {
|
||||
test(`${engine} ${lang} ${width}: a model says how many of its replies looped`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const errors = [];
|
||||
const n = (k) => looped[lang].replace("{n}", k);
|
||||
const open = async (tab) => {
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(8000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang));
|
||||
await page.addInitScript((tab) => localStorage.setItem("magpie.usageTab", tab), tab);
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
return page;
|
||||
};
|
||||
|
||||
// Overview: kimi's row says 2 looped beside 3 failed; glm's says none
|
||||
let page = await open("usage");
|
||||
const rows = page.locator("#usageModels .row");
|
||||
await rows.first().waitFor();
|
||||
const kimi = await page.locator('#usageModels .row[data-id="p/kimi-k3"] .sub').textContent();
|
||||
const glm = await page.locator('#usageModels .row[data-id="p/glm-5"] .sub').textContent();
|
||||
assert(kimi?.includes(n(2)), `kimi's row: ${kimi}`);
|
||||
assert(glm && !glm.includes(n(0)) && !glm.includes(n(1)), `glm's row: ${glm}`);
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the page scrolls sideways");
|
||||
|
||||
// Requests: the ranking says it of kimi, not of glm, and Other adds
|
||||
// up its two
|
||||
page = await open("requests");
|
||||
const rank = page.locator("#ledRank .rk-loop");
|
||||
await rank.first().waitFor();
|
||||
const loops = await rank.allTextContents();
|
||||
assert.deepEqual(loops, [n(2), n(2)], "kimi's 2, and Other's 1 + 1");
|
||||
const rk = await page.locator("#ledRank > *").allTextContents();
|
||||
assert(!rk.find((x) => x.includes("glm-5")).includes(n(0)));
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the page scrolls sideways");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Usage counts, per model, the replies magpie ended because the model
|
||||
// was stuck in a loop (#1858): they are among its failed calls, and the
|
||||
// model's row says how many of them were loops, apart from the vendor's
|
||||
// own errors. The Overview's model groups and the Requests ranking both
|
||||
// count them; a handed-on try is no request of its own.
|
||||
func TestLoopsCountedPerModel(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
now := time.Now()
|
||||
at := func(m int) string { return now.Add(time.Duration(m-10) * time.Second).Format(time.RFC3339Nano) }
|
||||
lines := []string{
|
||||
// two replies of kimi ended for looping, as the gateway logs them:
|
||||
// the agent had its 200, with the stream's error
|
||||
`{"t":"` + at(1) + `","agent":"claude","provider":"p","model":"kimi","in":10,"out":900,"ms":5,"status":200,"err":"p: stopped a reply stuck repeating itself","err_type":"` + LoopErrType + `","route_id":1}`,
|
||||
`{"t":"` + at(2) + `","agent":"claude","provider":"p","model":"kimi","in":10,"out":900,"ms":5,"status":200,"err":"p: stopped a reply stuck repeating itself","err_type":"` + LoopErrType + `","route_id":2}`,
|
||||
// a vendor's own error, and an answer
|
||||
`{"t":"` + at(3) + `","agent":"claude","provider":"p","model":"kimi","ms":5,"status":429,"err":"rate limited","err_type":"rate_limit_error","route_id":3}`,
|
||||
`{"t":"` + at(4) + `","agent":"claude","provider":"p","model":"kimi","in":10,"out":5,"ms":5,"status":200,"route_id":4}`,
|
||||
// another model's loop, on a try handed on: no request of its own
|
||||
`{"t":"` + at(5) + `","agent":"claude","provider":"p","model":"glm","in":10,"out":900,"ms":5,"status":200,"err":"p: stopped a reply stuck repeating itself","err_type":"` + LoopErrType + `","route_id":5,"handed_on":true}`,
|
||||
`{"t":"` + at(6) + `","agent":"claude","provider":"q","model":"glm","in":10,"out":5,"ms":5,"status":200,"route_id":5,"tries":2}`,
|
||||
}
|
||||
os.MkdirAll(filepath.Dir(Path()), 0o755)
|
||||
if err := os.WriteFile(Path(), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := map[string][2]int{"p/kimi": {3, 2}, "p/glm": {0, 0}, "q/glm": {0, 0}} // errors, loops
|
||||
s := Summarize(Today)
|
||||
seen := 0
|
||||
for _, g := range s.Models {
|
||||
w, ok := want[g.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
seen++
|
||||
if g.Errors != w[0] || g.Loops != w[1] {
|
||||
t.Errorf("overview %s: errors %d, loops %d; want %d, %d", g.ID, g.Errors, g.Loops, w[0], w[1])
|
||||
}
|
||||
}
|
||||
if seen != 3 {
|
||||
t.Fatalf("overview models %+v", s.Models)
|
||||
}
|
||||
if s.Loops != 2 {
|
||||
t.Errorf("overview total loops %d, want 2", s.Loops)
|
||||
}
|
||||
|
||||
rows, sum, _ := Ledger(Today, Filter{})
|
||||
if sum.Loops != 2 || sum.Errors != 3 {
|
||||
t.Errorf("ledger sum: errors %d, loops %d", sum.Errors, sum.Loops)
|
||||
}
|
||||
byModel := map[string][2]int{"kimi": {3, 2}, "glm": {0, 0}}
|
||||
seen = 0
|
||||
for _, sh := range Breakdown(rows, "model") {
|
||||
w, ok := byModel[sh.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
seen++
|
||||
if sh.Errors != w[0] || sh.Loops != w[1] {
|
||||
t.Errorf("requests %s: errors %d, loops %d; want %d, %d", sh.ID, sh.Errors, sh.Loops, w[0], w[1])
|
||||
}
|
||||
}
|
||||
if seen != 2 {
|
||||
t.Errorf("requests ranked %d of kimi and glm", seen)
|
||||
}
|
||||
}
|
||||
+14
-3
@@ -338,9 +338,12 @@ type Totals struct {
|
||||
// Calls are the requests, Errors those the agent got an error for, and
|
||||
// Retried those answered after a try that failed first (Record.Tries):
|
||||
// a try handed on is in neither count, but its tokens are in the sums
|
||||
Calls int `json:"calls"`
|
||||
Errors int `json:"errors"`
|
||||
Retried int `json:"retried,omitempty"`
|
||||
Calls int `json:"calls"`
|
||||
Errors int `json:"errors"`
|
||||
Retried int `json:"retried,omitempty"`
|
||||
// Loops are those of Errors magpie ended for looping (LoopErrType):
|
||||
// a model's count of them says how often it got stuck (#1858)
|
||||
Loops int `json:"loops,omitempty"`
|
||||
Input int `json:"input"`
|
||||
Output int `json:"output"`
|
||||
CacheRead int `json:"cache_read"`
|
||||
@@ -546,6 +549,11 @@ func (t *Totals) add(r Record, price *catalog.Price) {
|
||||
t.Cost += r.CostAt(*price)
|
||||
}
|
||||
|
||||
// LoopErrType is a record's ErrType for a reply magpie ended because the
|
||||
// model was stuck in a loop (#1359), told apart from what vendors call
|
||||
// their errors.
|
||||
const LoopErrType = "reply_loop"
|
||||
|
||||
// count counts r as the request it ends: failed, answered on a retry, or
|
||||
// answered; a try handed on to another is no request of its own.
|
||||
func (t *Totals) count(r Record) {
|
||||
@@ -556,6 +564,9 @@ func (t *Totals) count(r Record) {
|
||||
switch {
|
||||
case r.Failed():
|
||||
t.Errors++
|
||||
if r.ErrType == LoopErrType {
|
||||
t.Loops++
|
||||
}
|
||||
case r.Tries > 1:
|
||||
t.Retried++
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user