search: a picked searcher that can't serve gives way to the next that can (plugins#635)

pedestrianz (magpie-community/plugins#635) set Codex's gpt-6.1-sol to
search for Cursor's models. When the Codex plan was used up (429, usage
limit), every web search of a Cursor turn failed with it: a searcher named
in Settings gave way only to the ones named after it (SearcherThen), never
to the searchers magpie would pick itself. That rule is Gearclickist's:
Grok, picked, answered without searching, and the search moved to a
pricier Codex model the user hadn't picked.

Now a named searcher that can't serve at all hands the search on, after
those named after it, to the searchers magpie would pick in turn
(searchInTurn: the ones not spent first, up to two more providers). Can't
serve means every account or key is out of its allowance (searcherSpent),
or the search was refused for quota, credit or rate (failure() in
searchWith). Both are marked errCantServe, through a cantServe wrapper,
without changing the error's text. A named searcher that is spent is no
longer asked first; it is asked last only if no one else could search.
One that answered without searching or found nothing still gives way to
no other, so Gearclickist's case is unchanged. The Routing row and
Settings' SearcherFailed name who searched in its place
(searchingInstead, namedFailed). If none can, the errors go back to the
model as a failed tool result ("... no other provider could search in its
place") and the turn goes on to the model's answer. The AI Studio keys
443e53d6b added to searchRank are among those asked.

pickedSearchSetup's failing searcher answered 400 "search quota used up",
which is now a quota refusal that hands on. Its body is now "invalid
tools: web_search", a refusal of the request, so
TestPickedSearcherIsNotHandedOn still covers the not-handed-on case.
docs/subsystems/gateway-routing.md says when a named searcher is handed
on.

Run on mote (macOS 27), at this commit's tree, rebased on origin/main
443e53d6b (the AI Studio search keys):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/agent
  ./internal/browsermcp ./internal/cli ./internal/davsync ./internal/gui
  ./internal/imagemcp ./internal/library ./internal/settingsapi
  ./internal/tui (gateway and its importers): all ok except two reds,
  both filed and not in search. TestCodexPoolSaysTheClientsVersion
  (#4807) is red in the full package run and passes alone at this tree
  (-count=3, with the search tests). TestMainWindowCorners/macOS_26_SDK
  (#3949) is red the same way at origin/main b295d1196.
- Rebased onto b295d1196 (route-events, the WorkBuddy min, #4938; none
  touches search): go vet and go test -run
  'Search|Searcher|Picked|RouteEvents|Trace' ./internal/gateway: ok.
- gofmt -l internal/gateway: clean. GOOS=linux go vet -tags nogui and
  GOOS=windows go vet ./internal/gateway: ok.
- TestPickedSearcherThatCantServeGivesWay (new; httptest fakes, no
  network): the named ds answers ChatGPT's 429 usage_limit_reached; ds2,
  named nowhere, searches; the model gets its "22/17℃"; SearcherFailed
  says ds2 searched in ds's place, and ds2's web_search row has
  For.Instead ds/deepseek-flash. A second search, with ds now resting,
  doesn't ask ds's vendor again and goes to ds2. With ds2 removed, the
  turn still ends 200, and the model is told "search failed" with the
  usage-limit reason.

Broken by hand:
- origin/main's search.go with the new tests: the new test is red ("the
  picked searcher asked 1 times, ds2 []"); TestPickedSearcherIsNotHandedOn,
  TestSearchInPlaceOfAutoSaysWhy and TestPickedSearchersInTheirOrder
  still pass.
- With searchWith's cantServe wrapping taken out: red the same way.

Not tried: a real Codex account that is used up, with Cursor's plugin
models searching through it. Grok, Claude or Gemini as the searcher in
its place were not tried with real accounts; the fake stands in for each.
This commit is contained in:
yetone
2026-11-03 11:23:37 +08:00
parent b295d11965
commit 625938a2f8
4 changed files with 206 additions and 32 deletions
+12 -3
View File
@@ -1142,9 +1142,18 @@ after it, `SearcherThen` (Settings › Web search's "If it fails" row), in
their order. One that can't search now, is the one named, or is the same
model is skipped. The first that searches answers, and the row says why
the named one didn't search (`searchingInstead`). No other provider
searches in their place (axelburks on Discord asked for this list). When
every one fails, their errors go back to the model together, and
`webSearch` then asks the search APIs, when any are set up. Covered by
searches in their place (axelburks on Discord asked for this list), unless
the named one can't serve at all: every account or key of it out of its
allowance (`searcherSpent`), or its search refused for quota, credit or
rate (`failure`, in `searchWith`), both `errCantServe`. Then, after the
ones named after it, the searchers magpie would pick search in its place
in turn (`searchInTurn`, up to two more providers), and `namedFailed`
names the one that did. pedestrianz (plugins#635) named Codex to search
for Cursor's models; when Codex ran out and Cursor took the turns over,
every search failed with it (`TestPickedSearcherThatCantServeGivesWay`).
When every one fails, their errors go back to the model together, as a
failed tool result, and the turn goes on; `webSearch` then asks the
search APIs, when any are set up. Covered by
`TestPickedSearchersInTheirOrder`; `TestSearcherThenSaved` and
`TestSearcherThenFromSettings` cover how the list is saved. Settings only
takes a provider `Searchers()` offers. A save without the list keeps it,
+74 -25
View File
@@ -786,10 +786,16 @@ const searchersInTurn = 3
// modelSearch searches the web with the searcher's model; one magpie
// picked that fails or finds nothing gives way to the next searcher magpie
// would pick, all of them within searchWaitMost. One Settings names gives
// way to none: the search APIs, when set up, search in its place
// (webSearch), and Settings says it didn't search (SearcherFailed). Handed
// on, a search for Grok, picked, went to Codex's gpt-6-astra, a pricier
// model the user hadn't picked, on every search (Gearclickist on Discord).
// way to those named after it (SearcherThen), and, when it can't serve at
// all — out of its allowance, refused for its quota, credit or rate
// (errCantServe) — to the searchers magpie would pick in turn: a Codex
// account named to search for Cursor's models, used up, broke every
// search of the turns Cursor took over from it (pedestrianz, plugins#635).
// One that answered without searching or found nothing gives way to no
// other: the search APIs, when set up, search in its place (webSearch),
// and Settings says it didn't search (SearcherFailed). Handed on, a search
// for Grok, picked, went to Codex's gpt-6-astra, a pricier model the user
// hadn't picked, on every search (Gearclickist on Discord).
func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit, error) {
p, model, ok := searcher()
if !ok {
@@ -797,12 +803,12 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
}
ctx, cancel := sideDeadline(context.WithValue(ctx, searchingKey{}, true), "search", searchTimeout, searchWaitMost)
defer cancel()
type pick struct{ id, model string }
tried := []pick{{p.ID, model}}
tried := []searchPick{{p.ID, model}}
var said string
var hits []Hit
// one magpie picked that is out of its allowance isn't asked: it
// would only be refused again (#1801); one the Settings name is
// would only be refused again (#1801); one the Settings name is, and
// its refusal, as one out of its allowance, hands it on (errCantServe)
err := searcherSpent(p, model)
cp, _, why := chosenSearcher()
named := why == "" && cp != nil && cp.ID == p.ID
@@ -814,7 +820,7 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
}
if named {
// those Settings names after it, in their order (SearcherThen),
// and no other
// then, when it can't serve, those magpie would pick
instead, first := "", err
if err != nil && ctx.Err() == nil {
for _, v := range settings.Load().SearcherThen {
@@ -826,6 +832,7 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
ctx = searchingInstead(ctx, p, model, first)
}
instead = searcherOf(*q, m)
tried = append(tried, searchPick{q.ID, m})
var next error
if said, hits, next = s.searchBy(ctx, *q, m, query, searchEffort(*q, m)); next == nil {
err = nil
@@ -833,6 +840,16 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
}
err = errors.Join(err, next)
}
if err != nil && errors.Is(first, errCantServe) && ctx.Err() == nil {
if instead == "" {
ctx = searchingInstead(ctx, p, model, first)
}
var by string
said, hits, by, err = s.searchInTurn(ctx, query, tried, err, len(tried)+searchersInTurn-1)
if err == nil {
instead = by
}
}
if err == nil {
// what Settings says is the first's failure, and who
// searched in its place
@@ -849,14 +866,32 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
namedFailed(p, model, first, "")
}
if err != nil {
if len(settings.Load().SearcherThen) > 0 {
switch {
case errors.Is(first, errCantServe):
return "", nil, fmt.Errorf("%w (no other provider could search in its place)", err)
case len(settings.Load().SearcherThen) > 0:
return "", nil, fmt.Errorf("%w (the searchers picked in Settings › Web search, in their order: no other provider searches in their place)", err)
}
return "", nil, fmt.Errorf("%w (the searcher picked in Settings › Web search: no other provider searches in its place)", err)
}
return said, hits, nil
}
// the others in turn, those with allowance left first
if err != nil && ctx.Err() == nil {
ctx = searchingInstead(ctx, p, model, err)
said, hits, _, err = s.searchInTurn(ctx, query, tried, err, searchersInTurn)
}
return said, hits, err
}
// searchPick is a searcher a search was asked of.
type searchPick struct{ id, model string }
// searchInTurn asks the searchers magpie would pick (Searchers), those
// with allowance left first, of a provider not tried yet, until one
// searches or most have been tried in all: what it found, and which
// searched (searcherOf). err is the failures so far, which the new ones
// join.
func (s *Server) searchInTurn(ctx context.Context, query string, tried []searchPick, err error, most int) (string, []Hit, string, error) {
var turn, spent []SearcherChoice
for _, c := range Searchers() {
if c.ManualOnly || c.Small == "" {
@@ -869,29 +904,38 @@ func (s *Server) modelSearch(ctx context.Context, query string) (string, []Hit,
}
}
for _, c := range append(turn, spent...) {
if err == nil || ctx.Err() != nil || len(tried) >= searchersInTurn {
if ctx.Err() != nil || len(tried) >= most {
break
}
if slices.ContainsFunc(tried, func(t pick) bool { return t.id == c.Provider.ID }) {
if slices.ContainsFunc(tried, func(t searchPick) bool { return t.id == c.Provider.ID }) {
continue
}
if len(tried) == 1 {
ctx = searchingInstead(ctx, p, model, err)
}
tried = append(tried, pick{c.Provider.ID, c.Small})
tried = append(tried, searchPick{c.Provider.ID, c.Small})
next := searcherSpent(c.Provider, c.Small)
if next == nil {
said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query, searchEffort(c.Provider, c.Small))
}
if next != nil {
err = errors.Join(err, next)
} else {
err = nil
var said string
var hits []Hit
if said, hits, next = s.searchWith(ctx, c.Provider, c.Small, query, searchEffort(c.Provider, c.Small)); next == nil {
return said, hits, searcherOf(c.Provider, c.Small), nil
}
}
err = errors.Join(err, next)
}
return said, hits, err
return "", nil, "", err
}
// errCantServe is a searcher that can't serve a search now: every account
// or key of it out of its allowance (searcherSpent), or the search refused
// for its quota, credit or rate (searchWith). It is the provider's state,
// not what it does with a search, so another searches in its place.
var errCantServe = errors.New("can't search now")
// cantServe is err, a searcher's own error, said to be errCantServe
// without changing what it says.
type cantServe struct{ error }
func (c cantServe) Unwrap() []error { return []error{c.error, errCantServe} }
// lastNamedFail is the last search the searcher Settings names didn't
// make, for Settings to say (SearcherFailed); cleared when it searches.
var lastNamedFail struct {
@@ -971,7 +1015,7 @@ func searcherSpent(p provider.Provider, model string) error {
if !back.IsZero() {
when = " until " + heldClock(back, time.Now())
}
return fmt.Errorf("%s/%s: out of its allowance%s, not asked", p.ID, model, when)
return cantServe{fmt.Errorf("%s/%s: out of its allowance%s, not asked", p.ID, model, when)}
}
// searchingInstead is ctx with its web search's CallFor saying that the
@@ -1051,7 +1095,12 @@ func (s *Server) searchWith(ctx context.Context, p provider.Provider, model, que
if t, ok := sideTimeout(ctx); ok {
msg = t.Error()
}
return "", nil, fmt.Errorf("%s/%s: %s", p.ID, model, msg)
err := fmt.Errorf("%s/%s: %s", p.ID, model, msg)
switch failure(w.Code, w.Body.Bytes()) {
case failQuota, failCredit, failRate:
err = cantServe{err}
}
return "", nil, err
}
var text strings.Builder
var sources []string
+115
View File
@@ -0,0 +1,115 @@
package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// codexUsedUp is ChatGPT's refusal of an account whose plan's window is
// used up, the shape Codex accounts answer when they run out.
const codexUsedUp = `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":20000}}`
// usedUpSearcher is a searcher on DeepSeek's Responses API whose every
// search is refused with codexUsedUp; asked counts the searches.
func usedUpSearcher(t *testing.T) (*httptest.Server, *atomic.Int32) {
t.Helper()
var asked atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/models") {
io.WriteString(w, `{"data":[{"id":"deepseek-flash"}]}`)
return
}
asked.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
io.WriteString(w, codexUsedUp)
}))
t.Cleanup(srv.Close)
return srv, &asked
}
// The searcher picked in Settings that can't serve — its plan used up —
// gives way to the searchers magpie would pick, though none is named after
// it: pedestrianz (plugins#635) named Codex to search for Cursor's models,
// and when Codex ran out and Cursor took the turns over, every search
// failed with it. Once it is known to be out its vendor isn't asked again,
// and with no other searcher that can, the turn still ends with the
// model's answer, told the search failed.
func TestPickedSearcherThatCantServeGivesWay(t *testing.T) {
fresh(t)
// the rest its refusal leaves goes with the test
t.Cleanup(func() {
restingUntil.Lock()
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
restingUntil.Unlock()
})
searchSandbox(t)
forget := func() {
lastNamedFail.Lock()
lastNamedFail.f = SearchFailure{}
lastNamedFail.Unlock()
}
forget()
t.Cleanup(forget)
out, asked := usedUpSearcher(t)
glm, result := newBlindModel(t)
next := newFakeDeepSeek(t)
searchesOn(t, provider.Responses, out.URL)
searchesOn(t, provider.Anthropic, next.URL)
save(t, provider.Provider{ID: "ds", Name: "DeepSeek", Key: "k", Responses: out.URL + "/v1", Models: []string{"deepseek-flash"}},
provider.Provider{ID: "glm", Name: "GLM", Key: "k", Chat: glm.URL, Models: []string{"glm-flash"}},
provider.Provider{ID: "ds2", Name: "DeepSeek 2", Key: "k", Anthropic: next.URL + "/anthropic", Models: []string{"deepseek-flash"}})
st := settings.Load()
st.Searcher = "ds/deepseek-flash"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
s := New()
searchForGLM(t, s)
if asked.Load() != 1 || len(next.searches()) != 1 {
t.Fatalf("the picked searcher asked %d times, ds2 %q", asked.Load(), next.searches())
}
if r := result(); !strings.Contains(r, "22/17℃") {
t.Fatalf("the model was told %q", r)
}
f, ok := SearcherFailed()
if !ok || f.Searcher != "ds/deepseek-flash" || f.Instead != "ds2/deepseek-flash" || !strings.Contains(f.Why, "usage limit") {
t.Fatalf("SearcherFailed = %+v %v", f, ok)
}
var row *Route
for _, r := range s.Trace(context.Background(), 0, 0).Routes {
if r.Kind == "web_search" && strings.HasPrefix(r.Model, "ds2/") {
r := r
row = &r
}
}
if row == nil || row.For == nil || row.For.Instead != "ds/deepseek-flash" || !row.For.Picked {
t.Fatalf("the row of the search that answered: %+v", row)
}
// known to be out now: the next search goes to ds2, and ds's vendor
// isn't asked
searchForGLM(t, New())
if asked.Load() != 1 || len(next.searches()) != 2 {
t.Fatalf("out of its allowance, the picked searcher asked %d times, ds2 %q", asked.Load(), next.searches())
}
// no other searcher that can: the turn goes on, the model told why
if err := provider.Delete("ds2"); err != nil {
t.Fatal(err)
}
searchForGLM(t, New())
if r := result(); strings.Contains(r, "22/17℃") || !strings.Contains(r, "search failed") || !strings.Contains(r, "usage limit") {
t.Fatalf("the model was told %q", r)
}
}
+5 -4
View File
@@ -14,7 +14,8 @@ import (
// pickedSearchSetup is a search for glm/glm-flash, which can't search, with
// ds/deepseek-flash, on DeepSeek's Responses API, the first searcher: one
// that answers without searching (blind), or one whose every search is
// refused (failing). next is another searcher that would search.
// refused for what it was sent, not for its allowance (failing). next is
// another searcher that would search.
func pickedSearchSetup(t *testing.T, failing bool, nextOn provider.Protocol) (ds, next *fakeDeepSeek, result func() string) {
t.Helper()
searchSandbox(t)
@@ -36,7 +37,7 @@ func pickedSearchSetup(t *testing.T, failing bool, nextOn provider.Protocol) (ds
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":{"message":"search quota used up"}}`))
w.Write([]byte(`{"error":{"message":"invalid tools: web_search"}}`))
}))
t.Cleanup(broken.Close)
first = broken.URL
@@ -102,7 +103,7 @@ func TestPickedSearcherIsNotHandedOn(t *testing.T) {
if !ok || f.Searcher != "ds/deepseek-flash" || f.At.IsZero() {
t.Fatalf("SearcherFailed = %+v %v", f, ok)
}
if tc.failing && (f.NotSearched || f.NothingFound || !strings.Contains(f.Why, "search quota used up")) {
if tc.failing && (f.NotSearched || f.NothingFound || !strings.Contains(f.Why, "invalid tools: web_search")) {
t.Fatalf("SearcherFailed = %+v, want the picked searcher's error", f)
}
if !tc.failing && (!f.NotSearched || f.NothingFound || f.Why != "") {
@@ -180,7 +181,7 @@ func TestSearchInPlaceOfAutoSaysWhy(t *testing.T) {
if f.Instead != "ds/deepseek-flash" || f.Picked || f.Model != "glm/glm-flash" {
t.Fatalf("the answering search's row is for %+v", *f)
}
if tc.failing && (f.NothingFound || f.NotSearched || !strings.Contains(f.Why, "search quota used up")) {
if tc.failing && (f.NothingFound || f.NotSearched || !strings.Contains(f.Why, "invalid tools: web_search")) {
t.Fatalf("why %q nothing %v not searched %v, want the first searcher's error", f.Why, f.NothingFound, f.NotSearched)
}
if !tc.failing && (f.NothingFound || !f.NotSearched || f.Why != "") {