usage: Failed lists the requests a fallback answered, as Routing shows their tries failed (maohy915 on X)

maohy915 runs magpie on a NAS and uses it from another computer's magpie
through Remote magpie. The NAS's Routing page showed failed calls, but
Usage → Requests → Failed found none. Reproduced with two sandbox
instances on mote (B → remote-magpie → A, where A's provider `bad`
answers 429 and falls back to `good`). A's trace had 2 requests and 1
rerouted. Usage had 2 rows, Failed had 0 and Retried had 1. A try that
fails and is handed on writes no row when nothing is billed, and its
request's row is an answer on the second try. Failed kept only
LostRequest, the requests whose agent got the error, so the failed try
was nowhere under Failed. Plain failures, remote or not, were already
listed; only rerouted ones were missing.

Failed now keeps every request a try failed on (Record.FailedTry): the
requests the agent got an error for, the tries handed on, and the
requests a later try answered. Retried still keeps only the answered
ones. The counts are unchanged: each request is counted once, by how it
ended (小一's rule), so a Failed list reads "1 failed · 2 answered on a
retry". The Failed option and the card's "N failed" button now say so in
their tooltip, in every language. Filtered page cells are cached on disk
under the filter, so settledCountVersion goes to 4; the first start after
the upgrade pairs the history again once.

Run (mote):
- go test ./internal/usage ./internal/usageapi ./internal/gui: ok.
- New test TestFailedKeepsRequestsAFallbackAnswered; updated
  TestRequestsCountedOnceWithTheirRetries.
- GUI, both engines: ledger-retried (5 languages, 420/1100), i18n-keys,
  i18n-en-no-cjk, usage-ledger, api-key-usage, purpose-filter,
  usage-ledger-content, usage-phone-head, usage-loops, usage-request-page.
  All pass except known reds: i18n-keys "a plugin's words are its own"
  (#6422/#6423) and usage-ledger "newest live route needs no
  return-to-live button" (#4078/#3104/#4626).
- gofmt; go vet for darwin, linux -tags nogui, and windows.
- Real repro with a binary built from this tree: A's Failed went from 0
  rows to the rerouted request, both in the API and in the real page
  (Chromium).

Broken by hand:
- Filter back to LostRequest: both Go tests red.
- The Failed option's title dropped: ledger-retried red.

Not tried:
- Restoring settledCountVersion to 3 doesn't turn
  TestSettledCountedAsVersioned red: it counts only Filter{}. The bump is
  by reading.
- Not tried on a real NAS or in the desktop app's remote window; the
  page is the NAS's own web page.
This commit is contained in:
yetone
2026-11-13 14:17:49 +08:00
parent a96d88effa
commit d370bef982
8 changed files with 91 additions and 19 deletions
+4 -4
View File
@@ -131,7 +131,7 @@ magpie.strings({
"{n} model unpriced": "{n} 个模型未计价",
"{n} models unpriced": "{n} 个模型未计价",
"Show only the requests answered on a retry": "只看重试后成功的请求",
"Show only the failed requests": "只看失败的请求",
"Show the requests a try failed on, with those a later try answered": "只看有一次尝试失败的请求,含后来重试成功的",
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "这次尝试失败,请求已转交给下一个:请求按最终结果计数,不算这次尝试",
"{p} succeeded": "成功 {p}",
"{a} cache": "缓存 {a}",
@@ -400,7 +400,7 @@ magpie.strings({
"{n} model unpriced": "{n} 個模型未計價",
"{n} models unpriced": "{n} 個模型未計價",
"Show only the requests answered on a retry": "只看重試後成功的請求",
"Show only the failed requests": "只看失敗的請求",
"Show the requests a try failed on, with those a later try answered": "只看有一次嘗試失敗的請求,含後來重試成功的",
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "這次嘗試失敗,請求已轉交給下一個:請求依最終結果計數,不算這次嘗試",
"{p} succeeded": "成功 {p}",
"{a} cache": "快取 {a}",
@@ -669,7 +669,7 @@ magpie.strings({
"{n} model unpriced": "{n} 個のモデルは価格不明",
"{n} models unpriced": "{n} 個のモデルは価格不明",
"Show only the requests answered on a retry": "再試行で成功したリクエストだけを表示",
"Show only the failed requests": "失敗したリクエストだけを表示",
"Show the requests a try failed on, with those a later try answered": "試行が失敗したリクエストを表示(後の試行で応答されたものも含む)",
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "この試行は失敗し、リクエストは次へ引き継がれました。リクエストはこの試行ではなく最終結果で数えます",
"{p} succeeded": "成功 {p}",
"{a} cache": "キャッシュ {a}",
@@ -938,7 +938,7 @@ magpie.strings({
"{n} model unpriced": "{n} Modell ohne Preis",
"{n} models unpriced": "{n} Modelle ohne Preis",
"Show only the requests answered on a retry": "Nur die nach erneutem Versuch beantworteten Anfragen zeigen",
"Show only the failed requests": "Nur die fehlgeschlagenen Anfragen zeigen",
"Show the requests a try failed on, with those a later try answered": "Anfragen zeigen, bei denen ein Versuch fehlschlug, auch von einem späteren beantwortete",
"This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try": "Dieser Versuch schlug fehl, und die Anfrage ging an den nächsten weiter: Gezählt wird die Anfrage nach ihrem Ausgang, nicht nach diesem Versuch",
"{p} succeeded": "{p} erfolgreich",
"{a} cache": "{a} Cache",
+4 -1
View File
@@ -2155,7 +2155,7 @@ function renderLedgerDash(l) {
// an error: not those their agent canceled, which are counted apart
const settled = l.calls - (l.canceled || 0);
block("Requests", fmtN(l.calls), l.errors
? jumps(jump(t("{n} failed", { n: fmtN(l.errors) }), "failed", t("Show only the failed requests")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / settled)).toFixed(1) + "%" }))
? jumps(jump(t("{n} failed", { n: fmtN(l.errors) }), "failed", t("Show the requests a try failed on, with those a later try answered")), " · " + t("{p} succeeded", { p: (100 * (1 - l.errors / settled)).toFixed(1) + "%" }))
: line(t("none failed")), "", exactN(l.calls));
if (l.retried) strip.lastChild.append(jumps(jump(t("{n} answered on a retry", { n: fmtN(l.retried) }), "retried", t("Show only the requests answered on a retry"))));
if (l.canceled) {
@@ -2944,6 +2944,9 @@ function renderLedger() {
for (const [on, name] of [["", "All"], ["failed", "Failed"], ["retried", "Retried"]]) {
const b = el("button", "opt" + (on === shown ? " on" : ""), t(name));
if (on === "retried") b.title = t("Show only the requests answered on a retry");
// a request a later try answered is still one a try failed on, as
// Routing shows it (maohy915 on X)
if (on === "failed") b.title = t("Show the requests a try failed on, with those a later try answered");
b.onclick = () => {
if (on === ledStatusOf()) return;
for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b);
+12 -5
View File
@@ -4,7 +4,9 @@
// rows had been answered): a request answered after a try that failed is
// counted beside the failures as answered on a retry. Each count is a
// button for its requests: "N failed" turns on the list's Failed filter,
// "N answered on a retry" its Retried one, and the button again turns it
// which lists every request a try failed on, those a later try answered
// too, as Routing shows them failed (maohy915 on X: Routing had failed
// calls the Failed filter didn't), "N answered on a retry" its Retried one, and the button again turns it
// off. A try handed on to the next says so in its row, and a request that
// took more than one says how many. No click moves the page, nothing runs
// past the window at 420 or 1100 wide, in every language; the API is faked.
@@ -49,7 +51,7 @@ function serve(lang, asked) {
const q = url.searchParams;
asked.push(q);
const base = { period: q.get("period"), agents: [{ id: "codex", name: "Codex", icon: "codex" }] };
if (q.get("failed") === "1") return json({ ...base, ...sum([FAILED], 1, 1, 0) });
if (q.get("failed") === "1") return json({ ...base, ...sum([RETRIED, HANDED, FAILED], 2, 1, 1) });
if (q.get("retried") === "1") return json({ ...base, ...sum([RETRIED], 1, 0, 1) });
return json({ ...base, ...sum([RETRIED, HANDED, FAILED, OK], 3, 1, 1) });
}
@@ -66,7 +68,7 @@ function serve(lang, asked) {
};
}
const STRINGS = ["{n} failed", "{n} answered on a retry", "Retried", "Failed", "Show only the failed requests", "Show only the requests answered on a retry",
const STRINGS = ["{n} failed", "{n} answered on a retry", "Retried", "Failed", "Show the requests a try failed on, with those a later try answered", "Show only the requests answered on a retry",
"handed on", "{n} tries", "This try failed and the request was handed on to the next: the request is counted by how it ended, not by this try"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
@@ -106,7 +108,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const failed = card.locator("button.led-jump.bad"), retried = card.locator("button.led-jump:not(.bad)");
assert.equal(await failed.textContent(), await tr("{n} failed", { n: "1" }));
assert.equal(await retried.textContent(), await tr("{n} answered on a retry", { n: "1" }));
assert.equal(await failed.getAttribute("title"), await tr("Show only the failed requests"));
assert.equal(await failed.getAttribute("title"), await tr("Show the requests a try failed on, with those a later try answered"));
assert.equal(await page.locator("#ledStatus .opt").nth(1).getAttribute("title"), await tr("Show the requests a try failed on, with those a later try answered"));
// whole, inside the card, and nothing past the window
const fits = await card.evaluate((b) => {
const r = b.getBoundingClientRect();
@@ -149,9 +152,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
let q = await press(failed);
assert.equal(q.get("failed"), "1");
assert.equal(q.get("retried"), null);
await page.waitForFunction(() => document.querySelectorAll(".led tbody tr.led-row").length === 1);
// the failed request, the try handed on and the request it was
// handed to, each counted by how it ended
await page.waitForFunction(() => document.querySelectorAll(".led tbody tr.led-row").length === 3);
assert.equal(await page.locator("#ledStatus .opt.on").textContent(), await tr("Failed"));
assert.equal(await card.locator("button.led-jump.bad").getAttribute("aria-pressed"), "true");
assert.equal(await status(0), "200 · " + (await tr("{n} tries", { n: 3 })));
assert((await page.locator("#ledSum").textContent()).includes((await tr("{n} failed", { n: "1" })) + " · " + (await tr("{n} answered on a retry", { n: "1" }))));
// pressed again: every request
q = await press(card.locator("button.led-jump.bad"));
assert.equal(q.get("failed"), null);
+50
View File
@@ -0,0 +1,50 @@
package usage
import (
"testing"
"time"
)
// maohy915 on X: a magpie on a NAS, used from another computer's magpie,
// showed failed calls on Routing while Usage's Failed filter found none.
// The calls had failed on one provider and been answered by its fallback:
// the failed try wrote no row (nothing was billed) and its request's row
// is an answer on the second try. Failed keeps that request, as Routing
// shows its try failed, and a try handed on, beside the requests the
// agent got an error for; Retried still keeps only the answered ones.
func TestFailedKeepsRequestsAFallbackAnswered(t *testing.T) {
pageHome(t)
now := time.Now()
at := func(s int) time.Time { return now.Add(time.Duration(s-30) * time.Second) }
Append(Record{Time: at(1), Agent: "claude", Provider: "good", Model: "m2", Requested: "bad/m1", Input: 5, Output: 2, Status: 200, RouteID: 1, Tries: 2, Via: "desk"})
Append(Record{Time: at(2), Agent: "claude", Provider: "good", Model: "m2", Requested: "bad/m1", Input: 5, Output: 2, Status: 200, RouteID: 2, Via: "desk"})
Append(Record{Time: at(3), Agent: "claude", Provider: "bad", Model: "m1", Input: 5, Status: 429, Error: "rate limited", RouteID: 3, HandedOn: true, Via: "desk"})
Append(Record{Time: at(4), Agent: "claude", Provider: "good", Model: "m2", Input: 5, Output: 2, Status: 200, RouteID: 3, Tries: 2, Via: "desk"})
Append(Record{Time: at(5), Agent: "claude", Provider: "bad", Model: "m1", Status: 429, Error: "rate limited", RouteID: 4, Via: "desk"})
Append(Record{Time: at(6), Agent: "claude", Provider: "good", Model: "m2", Status: StatusCanceled, Error: AgentCanceled, ErrType: CanceledErrType, RouteID: 5, Tries: 2, Via: "desk"})
routes := func(rows []Row) map[int64]int {
m := map[int64]int{}
for _, r := range rows {
m[int64(r.RouteID)]++
}
return m
}
rows, sum, _ := Ledger(All, Filter{Failed: true})
if got := routes(rows); len(rows) != 4 || got[1] != 1 || got[3] != 2 || got[4] != 1 {
t.Fatalf("Failed kept routes %v (%d rows), want 1, 3 (both tries) and 4", got, len(rows))
}
if sum.Calls != 3 || sum.Errors != 1 || sum.Retried != 2 {
t.Fatalf("Failed's sum %+v: want 3 requests, 1 failed, 2 answered on a retry", sum)
}
if p := QueryPage(All, Filter{Failed: true}, 0, 50); p.Total != 4 || p.Sum.Errors != 1 || p.Sum.Retried != 2 {
t.Fatalf("Failed page: %d rows, %+v", p.Total, p.Sum)
}
if p := QueryPage(All, Filter{Retried: true}, 0, 50); p.Total != 2 || p.Sum.Errors != 0 {
t.Fatalf("Retried page: %d rows, %+v", p.Total, p.Sum)
}
// counted once each, by how it ended, as before
if p := QueryPage(All, Filter{}, 0, 50); p.Sum.Calls != 5 || p.Sum.Errors != 1 || p.Sum.Retried != 2 || p.Sum.Canceled != 1 {
t.Fatalf("all: %+v", p.Sum)
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ import (
// history again on its first start, the cold start's peak (#2278). Raise
// it with any change to what a row counts as; TestSettledCountedAsVersioned
// fails until it is raised.
const settledCountVersion = "3"
const settledCountVersion = "4"
func heatDiskPath() string {
return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json")
+7 -5
View File
@@ -101,10 +101,12 @@ type Filter struct {
// Account narrows to the calls a subscription account answered, by its
// name as Record.Account gives it (#557)
Account string
// Failed keeps the rows of the requests the agent got an error for
// (Record.LostRequest), Retried those of the requests answered after a
// try that failed first (Record.RetriedRequest): what the Requests
// card's two counts are of
// Failed keeps the rows of every request a try failed on
// (Record.FailedTry): those the agent got an error for, the tries
// handed on, and the requests a later try answered, as Routing shows
// them failed (maohy915 on X). Retried keeps only the requests answered
// after a try that failed first (Record.RetriedRequest). The Requests
// card still counts each request once, by how it ended.
Failed bool
Retried bool
Query string
@@ -224,7 +226,7 @@ func (f Filter) keepsRecord(r *Record, codexIdentity bool, subagent, parentAgent
if !f.computer(r) {
return false
}
if f.Failed && !r.LostRequest() {
if f.Failed && !r.FailedTry() {
return false
}
if f.Retried && !r.RetriedRequest() {
+6 -3
View File
@@ -70,12 +70,15 @@ func TestRequestsCountedOnceWithTheirRetries(t *testing.T) {
t.Fatalf("%d rows handed on, want 2", handed)
}
// Failed keeps every request a try failed on, as Routing shows them
// (maohy915 on X): the two that failed, the two tries handed on and
// the two answers after them; still counted by how each ended
failed, fsum, _ := Ledger(Today, Filter{Failed: true})
if len(failed) != 2 || fsum.Errors != 2 || fsum.Calls != 2 {
if len(failed) != 6 || fsum.Errors != 2 || fsum.Retried != 2 || fsum.Calls != 4 {
t.Fatalf("failed filter: %d rows, %+v", len(failed), fsum)
}
for _, r := range failed {
if r.HandedOn || !r.Failed() {
if r.RouteID == 104 || !r.Failed() && r.Tries < 2 {
t.Fatalf("failed filter kept %+v", r)
}
}
@@ -93,7 +96,7 @@ func TestRequestsCountedOnceWithTheirRetries(t *testing.T) {
if page.Sum.Calls != 5 || page.Sum.Errors != 2 || page.Sum.Retried != 2 {
t.Fatalf("page sum %+v", page.Sum)
}
if p := QueryPage(Today, Filter{Failed: true}, 0, 100); p.Total != 2 {
if p := QueryPage(Today, Filter{Failed: true}, 0, 100); p.Total != 6 || p.Sum.Errors != 2 || p.Sum.Retried != 2 {
t.Fatalf("failed page has %d rows", p.Total)
}
if p := QueryPage(Today, Filter{Retried: true}, 0, 100); p.Total != 2 {
+7
View File
@@ -938,6 +938,13 @@ func (t *Totals) count(r Record) {
// failed row that no later try took over from.
func (r Record) LostRequest() bool { return r.Failed() && !r.HandedOn }
// FailedTry is whether a try of r's request failed: r failed (whether the
// agent got the error or a later try took over), or r answered after a
// try that failed first. What Usage's Failed filter keeps: Routing shows
// those tries failed, and a request a fallback answered had none of its
// own failures listed under Failed (maohy915 on X).
func (r Record) FailedTry() bool { return r.Failed() || r.RetriedRequest() }
// RetriedRequest is whether r ends a request that was answered after a try
// that failed first (not one its agent canceled after a failed try).
func (r Record) RetriedRequest() bool { return !r.HandedOn && r.Answered() && r.Tries > 1 }