magpie icon indicating copy to clipboard operation
magpie copied to clipboard

[Bug] Claude Desktop retries Claude overflow after successful DeepSeek failover, including within the same turn

Open hipposonCN opened this issue 1 month ago • 4 comments

Claude Desktop repeatedly selects a Claude subscription model that returns Prompt is too long, then silently succeeds through DeepSeek. This happens even on two consecutive requests labeled as the same turn. Earlier in the same session, Claude models successfully processed nearly 1M input tokens. Please help investigate the effective limit and repeated retries; the available evidence does not establish Extra usage as the root cause.

Environment

  • macOS, Apple Silicon; Magpie 0.1.1364.
  • Claude Desktop in third-party Gateway mode, using group/progressive-vibe-claude and typesafe/jev-latest.
  • Environment collected after the incident: Claude Desktop 3.6556.2; Claude Code on PATH 2.1.310. These are collection-time versions, not proof of the exact Desktop/bridge builds used by the earlier failing requests.
  • Incidents below occurred on 2026-10-24, UTC+08:00. All five rows belong to the same original session, anonymized as session-A.
  • The selected routes identify one Claude subscription account, labeled Pro. The local account cache matches that account; its identity is omitted.

Observed behavior

  1. A long-running Desktop Code conversation uses the routing group.
  2. The intent rule selects Sonnet or another Claude model.
  3. That attempt returns 400, fail: overflow, Prompt is too long.
  4. Another member succeeds, so Desktop receives a final 200. Routing shows a rejected Claude attempt but no client-visible error.
  5. Subsequent requests again attempt Claude before falling back. Two consecutive records below both identify the selected rule's turn as 106.

This was extracted from real routing logs, not a synthetic reproduction. No private conversation or production request was replayed to prepare this report.

Sanitized log evidence

tokens_field is the routing record's rule.tokens. reported_input is calculated from the successful member's usage (in + cache_read + cache_write). Neither is presented as an authoritative count of the input received by a failed Claude attempt.

Time (+08:00) Request ID Turn Attempts, in order Successful member's reported input
14:10:02.528 1792822157213 101 Sonnet 400 / overflow in 66 ms; Opus 200 Opus: 2 + 977,558 cache read + 20,766 cache write = 998,326
14:10:36.519 1792822157214 101 Opus 400 / overflow in 65 ms; Sonnet 200 Sonnet: 2 + 996,343 cache read + 2,269 cache write = 998,614
14:11:29.999 1792822157217 102 Haiku 400 / overflow; Sonnet 400 / overflow; Opus 400 / overflow; DeepSeek 200 DeepSeek: 607,721 + 62,336 cache read = 670,057
14:16:58.672 1792822157237 106 Sonnet 400 / overflow in 3,395 ms; DeepSeek 200 DeepSeek: 184 + 674,048 cache read = 674,232
14:17:10.559 1792822157238 106 Sonnet 400 / overflow in 4,544 ms; DeepSeek 200 DeepSeek: 521 + 674,688 cache read = 675,209

The last row corresponds to the screenshot's approximately 676.1K total tokens: 675,209 input + 906 output = 676,115. That is DeepSeek's usage, not a measurement proving what Sonnet received.

Representative routing excerpts (allowlisted fields only):

{"request_id":1792822157237,"session":"session-A","time":"2026-10-24T14:16:58.6726+08:00","rule":{"n":5,"turn":106,"use":"claude/claude-sonnet-5-5","tokens_field":673268},"affinity":{"mode":"session","last":"deepseek","lastTurn":105,"why":"rule"},"tries":[{"model":"claude-sonnet-5-5","status":400,"fail":"overflow","error":"Prompt is too long","ms":3395},{"model":"deepseek-flash","status":200,"ms":6638}],"status":200,"usage":[{"provider":"deepseek","model":"deepseek-flash","in":184,"out":576,"cache_read":674048}]}
{"request_id":1792822157238,"session":"session-A","time":"2026-10-24T14:17:10.559608+08:00","rule":{"n":5,"turn":106,"use":"claude/claude-sonnet-5-5","held":true,"tokens_field":674232},"affinity":{"mode":"session","within":true,"last":"deepseek","lastTurn":106,"why":"rule"},"tries":[{"model":"claude-sonnet-5-5","status":400,"fail":"overflow","error":"Prompt is too long","ms":4544},{"model":"deepseek-flash","status":200,"ms":9996}],"status":200,"usage":[{"provider":"deepseek","model":"deepseek-flash","in":521,"out":906,"cache_read":674688}]}

Some earlier failures (including the first three rows' fast failures) include Magpie's extended explanation identifying a Claude Code local preflight check, with the conditional explanation about an account requiring Extra usage for long context. Other attempts only say Prompt is too long. The failed-attempt records do not include an upstream maximum or a Claude-side input token count.

Configuration and uncertainty

The current settings were collected after the incidents and have changed during troubleshooting; they are not an exact historical reproduction fixture:

{
  "magpie": {
    "fullContext": true,
    "desktopLongest": true,
    "group_affinity": "session",
    "group_context": -1
  },
  "current_desktop_group_catalog": {
    "id": "mythos-magpie-7447083768",
    "max_input_tokens": 500000,
    "max_output_tokens": 393216
  },
  "current_claude_settings": {
    "env": {"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "1048576"},
    "modelSettings": {
      "mythos-magpie-7447083768": {"autoCompactWindow": 400000}
    }
  }
}

The local Claude account cache currently has hasExtraUsageEnabled: false and cachedExtraUsageDisabledReason: "org_level_disabled". These are cached flags, not a live verification of billing policy or evidence that Anthropic returned the long-context Extra usage rejection for the specific attempts above. The earlier successful Claude usage near 1M also makes a blanket statement that this account always has a 200K window insufficient.

Expected behavior / questions

  • Preserve successful fallback, but avoid repeatedly trying a member known not to fit the current conversation when no relevant condition changed.
  • Please check why failover did not appear to stick across the two records labeled turn 106. Does the trace turn ID imply the same turn for this behavior, and is a new intent/rule decision overriding the successful member?
  • Distinguish the routing estimate, each member's effective limit, and the final successful member's reported input in diagnostics. A single healthy context meter can otherwise obscure the rejected member's actual limit.
  • Determine whether this is a retained Claude Code process/account limit, a request transformation/resume discrepancy, or a context/compaction metadata problem before recommending paid Extra usage or a global reduction to 200K.
  • If no member can accept the request, preserve an overflow response the client can recognize and compact on. Do not turn on paid usage or silently discard history as a fix.

Possibly related: #2162 (Claude Code local preflight explanation), #1404 (the successful member supplies the displayed count), and #3348 (learning effective limits after overflow). This report is specifically about the Claude subscription bridge with Desktop and the contradictory success/failure evidence above; I have not established a shared root cause with those issues.

Emails, account identifiers, local paths, original session UUIDs, credentials, request headers, private prompts, custom intent text, and tool payloads are omitted. I have retained a local JSON extraction with these five records and source line references.

hipposonCN avatar Oct 24 '26 06:10 hipposonCN

Taking this. Direction: Prompt is too long overflow is request-scoped, not account-scoped, so today the failed Claude attempt leaves no seat state behind and every later request re-pays the same attempt — your turn-106 pair shows no learning across two identical failures. Will first trace whether the overflow classification feeds any rest/seat state at all (and how #3348's resend concern relates) before changing anything; patch or diagnosis to follow on my fork.

ggbdpq avatar Oct 24 '26 06:10 ggbdpq

An overflow refusal is now remembered per conversation, and the member that refused is asked last instead of first.

Summary

A 400 "prompt is too long" says the request is too long for the model, not that anything is wrong with the account — so nobody rests, nothing was recorded, and the next request of the same conversation tried the same member first, failed the same way, and fell back again, on every request (#3453: a rule sent every turn to a Claude subscription bridge that answered "Prompt is too long" while DeepSeek answered; two consecutive requests of one turn each paid the refused try first). The conversation now remembers, per provider's model, how large the request was when it was refused, and that member is ordered behind the others for this conversation only.

What changed

  • internal/gateway/affinity.go: overflowLearned (conversation → provider\x00model → refused size and time), noteOverflow (records the size on a 400 overflow), forgetOverflow (drops the record when the member answers), behindOverflow (moves members that refused this conversation at no more than the current size behind the ready ones, keeping the plan's weights in step).
  • internal/gateway/gateway.go: behindOverflow runs right after roomy in serve (so the routing rule has already been heard via ruleOver); a 400 overflow calls noteOverflow with len(body), while a 413 byte cap does not (that is the request bytes, not the conversation too long for the model); after answered, forgetOverflow drops the memory.
  • internal/gateway/group_test.go: fresh clears overflowLearned between tests.
  • internal/gateway/overflow_learn_test.go (new): TestOverflowRefusedOnceIsAskedLast — member a refuses every request with the overflow of #3453, member b answers; a rule pins a first. Asserts the first request pays the refused try (Tries[0].Fail == failOverflow), the second request of the same conversation reaches b without trying a, another conversation still starts with a, and the same conversation compacted below the refused size finds a where the rule put it again.

The member is put behind, not out: it is still asked when every other member has failed, a rule naming it is still honored, and what it answers makes magpie forget the refusal. A request smaller than what was refused — the agent has compacted the conversation — leaves the member where the rule put it. Another conversation is unaffected, resting or nearly spent members keep their order, and only who is asked first among the ready changes.

Verification

| Check | Result | | Targeted go test -tags nogui -run TestOverflowRefusedOnceIsAskedLast ./internal/gateway/ | ok, 1.032s (-count=1) on 4622fff0 | | Ablation: internal/gateway/affinity.go + internal/gateway/gateway.go reverted to 4683a038, same test | FAIL — undefined: overflowLearned (group_test.go:52); restored → ok again | | git status in the worktree | clean after the ablation round-trip | | Full go test -tags nogui ./internal/gateway/ | not run this round; claimed green in the commit's Run section | | go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; builds for darwin/linux/windows | not run this round; claimed clean in the commit's Run section |

Attribution: AI-written; I've read the whole diff and the tests pass. Please keep the author (ggbdpq) or add Co-authored-by: ggbdpq <[email protected]>.

patch: hunt77-b-3453-overflow-learning (#3453) — git am applies it as is; SHA-256 first 16: 969164c2f0647759
From 4622fff0f945bb1447794ae4fedc509199af1504 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Sat, 24 Oct 2026 15:05:41 +0800
Subject: [PATCH] gateway: a member that refused this conversation as too long
 is asked last, not first
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

What changed: an overflow (400, "prompt is too long") is the request's
length, not the account's, so it rests nobody — and left no trace: the
next request of the same conversation tried the member again, failed the
same way, and fell back again, for every request (#3453: a rule sent
every turn to a Claude subscription bridge that answered "Prompt is too
long" and DeepSeek answered; two consecutive requests of one turn each
paid the refused try first). Now the conversation remembers, per
provider's model, how large the request was when it was refused, and the
member is put behind the others — behind, not out: it is still asked
when every other member has failed, a rule that names it is still
heard (ruleOver has run), and what it answers makes magpie forget the
refusal. A request smaller than what was refused — the agent has
compacted the conversation — finds the member where the rule put it.
Another conversation is unaffected, and a byte cap (413) is not
remembered: it is not the conversation too long for the model.

Run: GOCACHE=... GOMODCACHE=... go test -tags nogui -run
'TestOverflowRefusedOnceIsAskedLast' ./internal/gateway/ (red on
4683a038, green here); go test -tags nogui ./internal/gateway/; go vet
./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...;
go build for darwin, linux, windows.

Generated-by: GLM-5.3-Flash (ZCode)
---
 internal/gateway/affinity.go            | 106 ++++++++++++++++++++++++
 internal/gateway/gateway.go             |  14 ++++
 internal/gateway/group_test.go          |   3 +
 internal/gateway/overflow_learn_test.go |  68 +++++++++++++++
 4 files changed, 191 insertions(+)
 create mode 100644 internal/gateway/overflow_learn_test.go

diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go
index a30da86d..7543df0e 100644
--- a/internal/gateway/affinity.go
+++ b/internal/gateway/affinity.go
@@ -848,6 +848,112 @@ func withoutCompaction(body []byte) ([]byte, bool) {
 	return nil, false
 }
 
+// overflowLearned remembers, per conversation and the provider's model
+// that refused it, how large the request was when the model answered it
+// too long (#3453: a rule sent every request of a conversation to a
+// member whose bridge refused it as too long; another member answered,
+// and the next request tried the first all over again — twice within one
+// turn). An overflow says nothing is wrong with the account — the
+// request was too long for the model — so nobody rests, and the memory
+// is the conversation's, not the member's: another conversation, or a
+// key or account of the model on it, goes to it as before. The next
+// request of the same conversation, grown or unchanged, is refused the
+// same way, the fallback each time spending the member's answer and the
+// agent's wait.
+var overflowLearned = struct {
+	sync.Mutex
+	m map[string]map[string]refusedLong // conversation → provider\x00model → what it refused
+}{m: map[string]map[string]refusedLong{}}
+
+// refusedLong is a request a conversation's member refused as too long:
+// its own bytes as they came, at the time it was refused. A conversation
+// only grows — so what is remembered holds — until its agent compacts
+// it, and one smaller than what was refused may hold now — so what is
+// remembered yields.
+type refusedLong struct {
+	at    time.Time
+	bytes int
+}
+
+// noteOverflow remembers that c's model refused this conversation as too
+// long at size bytes.
+func noteOverflow(key string, c candidate, size int) {
+	now := time.Now()
+	overflowLearned.Lock()
+	defer overflowLearned.Unlock()
+	m := overflowLearned.m[key]
+	if m == nil {
+		m = map[string]refusedLong{}
+		overflowLearned.m[key] = m
+	}
+	m[c.p.ID+"\x00"+c.model] = refusedLong{at: now, bytes: size}
+	if len(overflowLearned.m) > 4096 {
+		for k, m := range overflowLearned.m {
+			old := true
+			for _, r := range m {
+				if now.Sub(r.at) <= stickKeep {
+					old = false
+				}
+			}
+			if old {
+				delete(overflowLearned.m, k)
+			}
+		}
+	}
+}
+
+// forgetOverflow drops what was remembered of c's model refusing this
+// conversation: it has just answered it, whatever its size — the bridge
+// that refused it a moment ago may take it now.
+func forgetOverflow(key string, c candidate) {
+	overflowLearned.Lock()
+	defer overflowLearned.Unlock()
+	m := overflowLearned.m[key]
+	if m == nil {
+		return
+	}
+	delete(m, c.p.ID+"\x00"+c.model)
+	if len(m) == 0 {
+		delete(overflowLearned.m, key)
+	}
+}
+
+// behindOverflow puts, of cs, the members whose models refused this very
+// conversation as too long at no more than size — what it is now, or has
+// grown to since — behind the others, so the member that answered last
+// is asked first instead (#3453). The rule that sends the turn to one of
+// them has been heard (ruleOver has run); the member is still asked when
+// every other member has failed: it is put behind, not out, and when it
+// answers the memory of its refusal is dropped. A request smaller than
+// what was refused — the agent has compacted the conversation — leaves
+// the member where it was. What rests, or is all but used up, is ordered
+// as it was: this moves only who of those ready is asked first.
+func behindOverflow(key string, cs []candidate, pl planned, size int) ([]candidate, planned) {
+	if len(cs) < 2 || len(pl.order) != len(cs) {
+		return cs, pl
+	}
+	overflowLearned.Lock()
+	noted := overflowLearned.m[key]
+	overflowLearned.Unlock()
+	if len(noted) == 0 {
+		return cs, pl
+	}
+	var behind, ready []candidate
+	var behindW, readyW []Weighed
+	for i, c := range cs {
+		if r, ok := noted[c.p.ID+"\x00"+c.model]; ok && size >= r.bytes {
+			behind, behindW = append(behind, c), append(behindW, pl.order[i])
+			continue
+		}
+		ready, readyW = append(ready, c), append(readyW, pl.order[i])
+	}
+	if len(behind) == 0 || len(ready) == 0 {
+		return cs, pl
+	}
+	pl.order = append(readyW, behindW...)
+	return append(ready, behind...), pl
+}
+
 // withoutKinds is a Responses request without its input items of these
 // types.
 func withoutKinds(body []byte, kinds ...string) ([]byte, bool) {
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 9fb97de7..f3d0ec4d 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -2281,6 +2281,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 	// asked: it would only refuse it. Those left out are the last resort,
 	// once every one with room is out of its allowance (small, below)
 	cands, pl, small, smallW := roomy(cands, pl, from, body)
+	// a member whose model refused this very conversation as too long at
+	// no more than this size is asked last: what it refused once the
+	// grown conversation is refused again, and the member that answered
+	// is asked first (#3453)
+	cands, pl = behindOverflow(stuck, cands, pl, len(body))
 	// of those resting, only the one back soonest is asked (#1799); the
 	// whole list still finds a Codex account to spend a reset on
 	all := cands
@@ -3150,6 +3155,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 				try.Fail = failOverflow
 				if hw.code() == http.StatusRequestEntityTooLarge {
 					try.Fail = failOther
+				} else {
+					// the conversation is remembered what this model
+					// refused as too long, to ask it last next time
+					// (#3453); a byte cap (413 above) isn't the
+					// conversation too long for the model, and isn't one
+					noteOverflow(stuck, c, len(body))
 				}
 				s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
 				skipped = append(skipped, c.label()+": "+call.Error)
@@ -3562,6 +3573,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
 			// conversation, and the turn's size, where they were
 			if hit == nil || !hit.Compact {
 				answered(stuck, c, aff.Turn, call.Usage)
+				// what it answered, it holds: whatever it refused as too
+				// long on the way is forgotten (#3453)
+				forgetOverflow(stuck, c)
 			}
 			// the trigger was kept, so whoever answered sealed it: a
 			// fallback whose own native compaction is off too, whose seal
diff --git a/internal/gateway/group_test.go b/internal/gateway/group_test.go
index c9b11021..37c9c57b 100644
--- a/internal/gateway/group_test.go
+++ b/internal/gateway/group_test.go
@@ -49,6 +49,9 @@ func fresh(t *testing.T) {
 	refusedSeals.Lock()
 	refusedSeals.m = map[string]sealsRefused{}
 	refusedSeals.Unlock()
+	overflowLearned.Lock()
+	overflowLearned.m = map[string]map[string]refusedLong{}
+	overflowLearned.Unlock()
 	turnRules.Lock()
 	turnRules.m = map[string]turnRule{}
 	turnRules.Unlock()
diff --git a/internal/gateway/overflow_learn_test.go b/internal/gateway/overflow_learn_test.go
new file mode 100644
index 00000000..85b2fc10
--- /dev/null
+++ b/internal/gateway/overflow_learn_test.go
@@ -0,0 +1,68 @@
+package gateway
+
+import (
+	"strings"
+	"testing"
+
+	"github.com/yetone/magpie/internal/provider"
+)
+
+// #3453 (hipposonCN): a rule sends every request of a conversation to a
+// member whose model refuses the conversation as too long; another member
+// takes it, and the next request tries the first all over again — twice
+// within one turn of the report's trace. What refused the conversation as
+// too long is put behind the member that answered it, for that
+// conversation alone: an overflow is the request's length, not the
+// account's, so nobody rests — and another conversation, or this one made
+// smaller by its agent's compacting, finds the member where the rule put
+// it, the size may hold now.
+func TestOverflowRefusedOnceIsAskedLast(t *testing.T) {
+	fresh(t)
+	over := `{"error":{"message":"prompt is too long: 674232 tokens > 200000 token maximum","type":"invalid_request_error"}}`
+	a := &scripted{replies: []reply{{400, "", over}, {400, "", over}, {400, "", over}}}
+	b := &scripted{replies: []reply{{200, "", chatOK}, {200, "", chatOK}, {200, "", chatOK}}}
+	scriptedOn(t, "a", provider.Chat, a)
+	scriptedOn(t, "b", provider.Chat, b)
+	if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered, Affinity: provider.AffinitySession,
+		Rules: []provider.Rule{{Use: "a/m", Tokens: 1}}}); err != nil {
+		t.Fatal(err)
+	}
+	s := New()
+	body := `{"model":"group/g","messages":[{"role":"user","content":"say something about this"}]}`
+
+	// the rule puts a first; it refuses the conversation as too long, and
+	// b answers
+	code, out := postAs(t, s, "s1", body)
+	if code != 200 || !strings.Contains(out, "hello") || a.n != 1 || b.n != 1 {
+		t.Fatalf("first: %d %s (a %d, b %d)", code, out, a.n, b.n)
+	}
+	r := lastRoute(s)
+	if len(r.Tries) != 2 || r.Tries[0].Fail != failOverflow {
+		t.Fatalf("first tries: %+v", r.Tries)
+	}
+
+	// the next request of the same conversation, the rule heard as it
+	// was: b is asked first, what a refused as too long at this size it
+	// refuses again — the conversation has only grown
+	a.n, b.n = 0, 0
+	code, out = postAs(t, s, "s1", body)
+	if code != 200 || a.n != 0 || b.n != 1 {
+		t.Fatalf("second: %d %s (a %d, b %d)", code, out, a.n, b.n)
+	}
+
+	// another conversation begins with a, as the rule says: what a
+	// refused was the first conversation's length, not this one's
+	a.n, b.n = 0, 0
+	code, out = postAs(t, s, "s2", body)
+	if code != 200 || a.n != 1 || b.n != 1 {
+		t.Fatalf("another conversation: %d %s (a %d, b %d)", code, out, a.n, b.n)
+	}
+
+	// the first conversation compacted to less than what a refused: a is
+	// asked as the rule says again, the size may hold now
+	a.n, b.n = 0, 0
+	code, out = postAs(t, s, "s1", `{"model":"group/g","messages":[{"role":"user","content":"up"}]}`)
+	if code != 200 || a.n != 1 || b.n != 1 {
+		t.Fatalf("compacted: %d %s (a %d, b %d)", code, out, a.n, b.n)
+	}
+}
-- 
2.50.1 (Apple Git-155)

Branch with the commit: hunt77-b-overflow-learning (head 4622fff0f945bb1447794ae4fedc509199af1504).

ggbdpq avatar Oct 24 '26 08:10 ggbdpq

Refreshed on today's upstream: the conversation-scoped overflow memory still has no counterpart upstream, and the patch is rebased, re-verified and applies cleanly.

What this is

Same fix as before: a 400 "prompt is too long" is the request's length, not the account's, so it rests nobody and left no trace — every request of the conversation paid the refused try first (#3453). The conversation now remembers, per provider's model, how large the request was when it was refused, and that member is asked last — behind, not out — until it answers or the conversation shrinks below the refused size.

Why refreshed

Upstream moved through this area today (#3289's rest rules, vendor-stated retry times, busy-models-last ordering, and a5a9cdf7b which stops re-telling a refused big conversation to the same Claude subscription's other accounts). None of these remembers an overflow refusal for a conversation, and the rebased patch composes with all of them: the gate test (TestOverflowRefusedOnceIsAskedLast) still fails on a clean upstream tree, so the face is still open. One upstream test needed a two-line accommodation: TestRelayInputCapGoesToTheNextMember's second phase shares its server with the first, whose overflow left the memory behind; as that phase checks how a plain bad request is classed, its memory now starts empty. Production semantics are unchanged: a plain 400 still fails the group at whichever member is asked, in any order.

Verification

Check Result
go test -tags nogui -count=1 -run TestOverflowRefusedOnceIsAskedLast ./internal/gateway/ red on 788057340, 4c815ac2a and c688211d1 with the test alone; green on the branch head
Full go test -tags nogui -count=1 ./internal/gateway/ ok, 515s on head c51fd52cc
Ablation: product half (affinity.go, gateway.go hooks) reverted to c688211d1, same test FAIL — second: (a 1, b 1); restored → ok
go vet -tags nogui ./internal/gateway/; gofmt -l internal/gateway/ clean

Branch with the commit: hunt77-b-overflow-learning (head c51fd52cc, base c688211d1).

Attribution: AI-written; I've read the whole diff and the tests above were run by me on this machine.

patch: hunt77-b-overflow-learning (#3453) — git am applies it as is on today's tip (`39bade71d`); SHA-256 first 16: 2ecee68ce23dae85
From c51fd52ccab77d8404e95d8faa532bdc526fd45d Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Sat, 24 Oct 2026 15:05:41 +0800
Subject: [PATCH] gateway: a member that refused this conversation as too long
 is asked last, not first
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

What changed: an overflow (400, "prompt is too long") is the request's
length, not the account's, so it rests nobody — and left no trace: the
next request of the same conversation tried the member again, failed the
same way, and fell back again, for every request (#3453: a rule sent
every turn to a Claude subscription bridge that answered "Prompt is too
long" and DeepSeek answered; two consecutive requests of one turn each
paid the refused try first). Now the conversation remembers, per
provider's model, how large the request was when it was refused, and the
member is put behind the others — behind, not out: it is still asked
when every other member has failed, a rule that names it is still
heard (ruleOver has run), and what it answers makes magpie forget the
refusal. A request smaller than what was refused — the agent has
compacted the conversation — finds the member where the rule put it.
Another conversation is unaffected, and a byte cap (413) is not
remembered: it is not the conversation too long for the model.

TestRelayInputCapGoesToTheNextMember's second phase shares its server
with the first, whose overflow left this conversation's memory of a's
refusal behind; as that phase says how a plain bad request is classed,
its memory starts empty.

Run: go test -tags nogui -count=1 -run
'TestOverflowRefusedOnceIsAskedLast' ./internal/gateway/ (red on
c688211d1 with the test alone, green here); go test -tags nogui
-count=1 ./internal/gateway/; go vet -tags nogui ./internal/gateway/;
gofmt -l internal/gateway clean. Broken by hand: the product half of
the commit dropped (affinity.go, gateway.go hooks), the test red at
"second: (a 1, b 1)"; restored, green.

Generated-by: GLM-5.3-Flash (ZCode)
---
 internal/gateway/affinity.go            | 106 ++++++++++++++++++++++++++++++++
 internal/gateway/gateway.go             |  14 +++++
 internal/gateway/group_test.go          |   3 +
 internal/gateway/overflow_cap_test.go   |   9 ++-
 internal/gateway/overflow_learn_test.go |  68 ++++++++++++++++++++
 5 files changed, 199 insertions(+), 1 deletion(-)

ggbdpq avatar Nov 01 '26 07:11 ggbdpq

Landed in e0a5091b7, with your authorship, in v0.1.2583: a member that refused this conversation as too long is asked last, not first. Two follow-ups are mine:

  • 3af592f58: the overflow memory was read without its lock while another request was writing it, which can crash with Go's concurrent map read and map write. It is now read under the lock; TestOverflowMemoryReadWhileNoted covers it, and the routing page of docs/subsystems is updated.
  • 8a4e32feb: the tests now also cover a compacted conversation and an answered one staying one conversation.

Review: -race -count=20 ok, and the whole gateway package ok (1059s). At the pushed head 768228a4f, on the test Mac: the full suite go test -tags nogui -count=1 -timeout 45m ./... is ok in all 87 packages (gateway 852.6s), plus go vet ./..., Linux and Windows go vet, and the budget tests in internal/gui. Not tried: a real Codex conversation past a member's window. Leaving this open for the reporter.

yetone avatar Nov 01 '26 09:11 yetone