Files
magpie/internal/gateway/tool_loop_test.go
T
yetone de281760e2 gateway: a conversation going round one tool call with the same result is answered by magpie after 8 turns (audie on Discord)
audie on Discord: on 10-21 Codex Desktop, routed to WorkBuddy's
deepseek-v4-pro, ran the same read-code tool call 308 times between 13:24
and 13:52 (316 requests, 212.65 credits). That evening it did it 340 more
times between 19:58 and 20:22 (343 requests, 324.52 credits). loopGuard
only catches a loop inside one streamed reply. Here every reply was a
short, valid call. The loop runs across turns, so it shows in the
request's own history.

stoppedToolLoop (internal/gateway/tool_loop.go) runs in serveAgent after
the session is recorded and before hooks, middleware and routing. It also
runs in the Codex backend's passthrough on Codex's own ChatGPT sign-in. It
needs the last 8 turns to be the same exchange:
- the same calls: name plus arguments, key order ignored, call ids ignored;
- answered with the same results: text, error flag and images, with
  Codex's "Wall time", "Chunk ID" and "duration_seconds" taken out
  (runNoise);
- with nothing else said on the user's side.
When it finds one, it answers the turn in the agent's own protocol,
streamed or whole (Responses, Chat, Anthropic, Gemini through
relayStatus), with a notice that names the call. Nothing goes upstream, and
no prompt, base_instructions or identity text sent to a vendor changes.
A different result, or any word from the user, starts the count again.
The notice is a turn without calls, so the user's next message carries
on. The check keeps no state, so it is per conversation, and a retried
request doesn't count twice.

The turn is recorded the way Codex's title turns are. sentNowhere's body
becomes answeredHere (from-protocol aware): the Routing trace shows "Tool
loop stopped", and a usage row has provider magpie, rejected, the
conversation's session and native session, and an error starting
"tool loop:". So Usage and Sessions both show why.

Cost: a body with fewer than 8 tool results isn't parsed (a
bytes.Count). For a longer one, only the newest 64 items are parsed,
found with gjson (tailOf). For a 1.5MB Codex turn that is 1.1ms and
2.5MB, against 30ms and 20MB for a full parse (BenchmarkToolLoopCheck).

There is no new setting. Settings › Models › Replies › Stop looping
replies (noLoopGuard, on by default) turns this off together with the
reply guard, and the notice says so. The GUI sub-text is unchanged.
docs/subsystems/gateway-routing.md has a bullet on it.

Run at this commit (vet/build/race at parent bf2e067ef; the full suite
after the rebase onto 50f52b540, at 558b21b7e):
- gofmt -l clean.
- go vet ./... on darwin, GOOS=linux go vet -tags nogui ./..., and
  GOOS=windows go vet ./....
- go build on darwin, linux (-tags nogui) and windows.
- TestToolLoop* and the Codex title/description/prediction tests under
  -race (TestToolLoop* -count=3).
- The tests, in a sandbox HOME against fake vendors:
  - TestToolLoopIsStoppedOnEveryProtocol: 60 poll turns then 8 Codex
    reads with a varying chunk id and wall time, on Responses (stream and
    whole), Codex's backend path, Chat (stream and whole), Anthropic
    (stream and whole) and Gemini. The vendor is asked 0 times, the
    notice and the protocol's done marker reach the agent, and the usage
    row is magpie, rejected, "tool loop", with the session.
  - TestToolLoopStoppedOnCodexsOwnSignIn: gpt-5.5 on the passthrough,
    with a fake CodexBase.
  - TestToolLoopShortOrOffGoesOn: 7 turns, and 40 with the setting off.
  - TestToolLoopLetsProgressBy: 200 polls whose answer moves, and a loop
    followed by the notice and a word from the user. Neither is stopped.
  - TestToolLoopSums.
- Broken by hand, each red, each restored:
  - The guard skipped: every protocol subtest and the Codex sign-in test
    fail ("the agent wasn't told of the loop").
  - runNoise removed: the same tests fail, plus TestToolLoopSums.
  - Results left out of the sum: every progress subtest fails ("a poll
    whose answer moves was stopped").
- Full suite: set -o pipefail; go test -tags nogui -timeout 45m ./...
  through suite-lock, in a sandbox HOME, at 558b21b7e on 50f52b540:
  exit 0, 69 packages ok, no FAIL (internal/gateway 854s, internal/agent
  812s, internal/provider 393s, internal/gui 291s).
- No GUI file changed, so the GUI suite wasn't run.

Not tried:
- A real Codex Desktop or WorkBuddy loop, or any real account. The
  fixture's shape is Codex's exec_command output; audie's literal bytes
  weren't available.
- The Windows box.
- Codex over websocket (magpie answers it 426).
- Responses conversations that use previous_response_id. They carry only
  the newest turn, so they are never stopped.
- Loops with more parallel calls a turn than fit in 64 items.
- A poll that gets the same answer 8 times in a row is stopped too. The
  user's next word, or the setting, carries on.
- dsh's two ~1M-token requests to DeepSeek on 10-23 are a different
  problem, not addressed here.
2026-10-23 21:36:51 +08:00

332 lines
15 KiB
Go

package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// countingVendor is a Chat vendor that answers every request with a word,
// streamed or whole as asked, and counts the requests it got.
type countingVendor struct{ asked atomic.Int64 }
func (v *countingVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
v.asked.Add(1)
if strings.Contains(string(body), `"stream":true`) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{"role":"assistant","content":"read it"}}]}`+"\n\n")
io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","model":"deepseek-v4-pro","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12}}`+"\n\n")
io.WriteString(w, "data: [DONE]\n\n")
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"deepseek-v4-pro","choices":[{"index":0,"message":{"role":"assistant","content":"read it"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12}}`)
}
// toolLoopOn is a gateway whose provider wb serves deepseek-v4-pro from v.
func toolLoopOn(t *testing.T, v *countingVendor) string {
t.Helper()
fresh(t)
vendor := httptest.NewServer(v)
t.Cleanup(vendor.Close)
if err := provider.Save(provider.Provider{ID: "wb", Name: "WorkBuddy", Key: "k", Chat: vendor.URL + "/v1", Models: []string{"deepseek-v4-pro"}}); err != nil {
t.Fatal(err)
}
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
return gw.URL
}
// codexRead is the reporter's turn: Codex Desktop's exec_command reading
// the same code, its output's wall time and chunk id differing each run.
func codexRead(i int) (args, result string) {
return `{"cmd":"sed -n 1,200p src/parser.rs","workdir":"/Users/audie/code/app"}`,
fmt.Sprintf("Chunk ID: %06x\nWall time: 0.0%d1 seconds\nProcess exited with code 0\nOriginal token count: 41\nOutput:\npub fn parse(s: &str) -> Ast {\n todo!()\n}\n", 0xa1b2c3+i, i%9)
}
// pollJob is a poll whose answer moves: the same call, a new result.
func pollJob(i int) (args, result string) {
return `{"cmd":"gh run view 123 --json status"}`, fmt.Sprintf(`{"status":"in_progress","steps_done":%d}`, i)
}
type exchangeOfTurn func(i int) (args, result string)
// toolTurns is a request of from's API holding n turns of tool use made
// by turn, after the user's ask, then tail (raw messages of that API).
func toolTurns(from provider.Protocol, n int, turn exchangeOfTurn, stream bool, tail ...string) string {
var items []string
switch from {
case provider.Responses:
items = append(items, `{"type":"message","role":"user","content":[{"type":"input_text","text":"why does parse panic?"}]}`)
for i := range n {
args, result := turn(i)
items = append(items,
fmt.Sprintf(`{"type":"reasoning","summary":[{"type":"summary_text","text":"Reading parser %d"}]}`, i),
fmt.Sprintf(`{"type":"function_call","name":"exec_command","arguments":%q,"call_id":"call_%d"}`, args, i),
fmt.Sprintf(`{"type":"function_call_output","call_id":"call_%d","output":%q}`, i, result))
}
items = append(items, tail...)
return fmt.Sprintf(`{"model":"wb/deepseek-v4-pro","stream":%t,"store":false,"instructions":"You are Codex.","tools":[{"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}],"input":[%s]}`, stream, strings.Join(items, ","))
case provider.Chat:
items = append(items, `{"role":"user","content":"why does parse panic?"}`)
for i := range n {
args, result := turn(i)
items = append(items,
fmt.Sprintf(`{"role":"assistant","content":null,"tool_calls":[{"id":"call_%d","type":"function","function":{"name":"exec_command","arguments":%q}}]}`, i, args),
fmt.Sprintf(`{"role":"tool","tool_call_id":"call_%d","content":%q}`, i, result))
}
items = append(items, tail...)
return fmt.Sprintf(`{"model":"wb/deepseek-v4-pro","stream":%t,"tools":[{"type":"function","function":{"name":"exec_command","parameters":{"type":"object"}}}],"messages":[%s]}`, stream, strings.Join(items, ","))
case provider.Anthropic:
items = append(items, `{"role":"user","content":"why does parse panic?"}`)
for i := range n {
args, result := turn(i)
items = append(items,
fmt.Sprintf(`{"role":"assistant","content":[{"type":"text","text":"Let me look again."},{"type":"tool_use","id":"toolu_%d","name":"Bash","input":%s}]}`, i, args),
fmt.Sprintf(`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_%d","content":%q}]}`, i, result))
}
items = append(items, tail...)
return fmt.Sprintf(`{"model":"wb/deepseek-v4-pro","max_tokens":8000,"stream":%t,"tools":[{"name":"Bash","input_schema":{"type":"object"}}],"messages":[%s]}`, stream, strings.Join(items, ","))
}
// Gemini
items = append(items, `{"role":"user","parts":[{"text":"why does parse panic?"}]}`)
for i := range n {
args, result := turn(i)
items = append(items,
fmt.Sprintf(`{"role":"model","parts":[{"functionCall":{"name":"run_shell_command","args":%s}}]}`, args),
fmt.Sprintf(`{"role":"user","parts":[{"functionResponse":{"name":"run_shell_command","response":{"output":%q}}}]}`, result))
}
items = append(items, tail...)
return fmt.Sprintf(`{"tools":[{"functionDeclarations":[{"name":"run_shell_command","parameters":{"type":"object"}}]}],"contents":[%s]}`, strings.Join(items, ","))
}
var toolLoopAsks = []struct {
name string
from provider.Protocol
path string
stream bool
done string // how the agent's reply ends well
}{
{"responses", provider.Responses, "/v1/responses", true, `"type":"response.completed"`},
{"responses whole", provider.Responses, "/v1/responses", false, `"status":"completed"`},
{"codex", provider.Responses, CodexPath + "/responses", true, `"type":"response.completed"`},
{"chat", provider.Chat, "/v1/chat/completions", true, "data: [DONE]"},
{"chat whole", provider.Chat, "/v1/chat/completions", false, `"finish_reason":"stop"`},
{"anthropic", provider.Anthropic, "/v1/messages", true, `"type":"message_stop"`},
{"anthropic whole", provider.Anthropic, "/v1/messages", false, `"stop_reason":"end_turn"`},
{"gemini", provider.Gemini, "/v1beta/models/wb/deepseek-v4-pro:streamGenerateContent?alt=sse", true, `"finishReason":"STOP"`},
}
func askAgent(t *testing.T, url, body string) string {
t.Helper()
req, _ := http.NewRequest(http.MethodPost, url, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("session_id", "01a15199-593c-77d1-9913-ce0e1efd48e8")
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
t.Fatalf("status %d: %s", res.StatusCode, b)
}
return string(b)
}
// The reporter's loop (audie on Discord: Codex Desktop on WorkBuddy's
// deepseek-v4-pro reading the same code 308 times): once the same call has
// had the same result toolLoopRepeats turns in a row, the next turn is
// answered by magpie in the agent's own API, a finished reply saying why,
// and the vendor is never asked; Usage and the session's requests have it
// as magpie's, sent nowhere, with the reason.
func TestToolLoopIsStoppedOnEveryProtocol(t *testing.T) {
for _, x := range toolLoopAsks {
t.Run(x.name, func(t *testing.T) {
v := &countingVendor{}
gw := toolLoopOn(t, v)
// a long conversation of progress first, which the guard reads
// only the end of (tailOf)
turn := func(i int) (string, string) {
if i < 60 {
return pollJob(i)
}
return codexRead(i)
}
got := askAgent(t, gw+x.path, toolTurns(x.from, 60+toolLoopRepeats, turn, x.stream))
if !strings.Contains(got, "magpie stopped this turn") || !strings.Contains(got, x.done) || !strings.Contains(got, "sed -n 1,200p src/parser.rs") {
t.Fatalf("the agent wasn't told of the loop in its API:\n%s", got)
}
if n := v.asked.Load(); n != 0 {
t.Fatalf("the vendor was asked %d times for a looping turn", n)
}
var rec usage.Record
for range 50 {
if recs := usage.Load(time.Time{}); len(recs) > 0 {
rec = recs[len(recs)-1]
break
}
time.Sleep(20 * time.Millisecond)
}
if rec.Provider != "magpie" || !rec.Rejected || !strings.Contains(rec.Error, "tool loop") || rec.Session != "01a15199-593c-77d1-9913-ce0e1efd48e8" {
t.Fatalf("usage record %+v", rec)
}
})
}
}
// Codex on its own sign-in, a turn relayed to the ChatGPT backend as it
// came, is stopped the same: its loop spends the user's ChatGPT plan.
func TestToolLoopStoppedOnCodexsOwnSignIn(t *testing.T) {
v := &countingVendor{}
toolLoopOn(t, &countingVendor{})
up := httptest.NewServer(v)
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
gw := httptest.NewServer(New().Handler())
t.Cleanup(gw.Close)
body := strings.Replace(toolTurns(provider.Responses, toolLoopRepeats, codexRead, true), `"model":"wb/deepseek-v4-pro"`, `"model":"gpt-5.5"`, 1)
got := askAgent(t, gw.URL+CodexPath+"/responses", body)
if !strings.Contains(got, "magpie stopped this turn") || !strings.Contains(got, `"type":"response.completed"`) {
t.Fatalf("Codex wasn't told of the loop:\n%s", got)
}
if n := v.asked.Load(); n != 0 {
t.Fatalf("the ChatGPT backend was asked %d times for a looping turn", n)
}
// one short goes on to the backend
askAgent(t, gw.URL+CodexPath+"/responses", strings.Replace(toolTurns(provider.Responses, toolLoopRepeats-1, codexRead, true), `"model":"wb/deepseek-v4-pro"`, `"model":"gpt-5.5"`, 1))
if n := v.asked.Load(); n != 1 {
t.Fatalf("the ChatGPT backend was asked %d times for a turn short of a loop", n)
}
}
// One turn short of the loop goes to the vendor, as does the reporter's
// loop with the guard turned off in Settings.
func TestToolLoopShortOrOffGoesOn(t *testing.T) {
for _, x := range toolLoopAsks {
t.Run(x.name, func(t *testing.T) {
v := &countingVendor{}
gw := toolLoopOn(t, v)
got := askAgent(t, gw+x.path, toolTurns(x.from, toolLoopRepeats-1, codexRead, x.stream))
if strings.Contains(got, "magpie stopped") || v.asked.Load() != 1 {
t.Fatalf("%d turns of the same call were stopped (vendor asked %d):\n%s", toolLoopRepeats-1, v.asked.Load(), got)
}
if err := settings.Save(settings.Settings{NoLoopGuard: true}); err != nil {
t.Fatal(err)
}
got = askAgent(t, gw+x.path, toolTurns(x.from, 40, codexRead, x.stream))
if strings.Contains(got, "magpie stopped") || v.asked.Load() != 2 {
t.Fatalf("the loop was stopped with Stop looping replies off (vendor asked %d):\n%s", v.asked.Load(), got)
}
})
}
}
// Work that makes progress is never stopped, however long it goes on: a
// poll answered differently each time, and the reporter's read of the
// same code once the user has said something since, magpie's notice
// included in the conversation.
func TestToolLoopLetsProgressBy(t *testing.T) {
notice := map[provider.Protocol][]string{
provider.Responses: {`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"magpie stopped this turn"}]}`, `{"type":"message","role":"user","content":[{"type":"input_text","text":"read it once more, then fix it"}]}`},
provider.Chat: {`{"role":"assistant","content":"magpie stopped this turn"}`, `{"role":"user","content":"read it once more, then fix it"}`},
provider.Anthropic: {`{"role":"assistant","content":"magpie stopped this turn"}`, `{"role":"user","content":"read it once more, then fix it"}`},
provider.Gemini: {`{"role":"model","parts":[{"text":"magpie stopped this turn"}]}`, `{"role":"user","parts":[{"text":"read it once more, then fix it"}]}`},
}
for _, x := range toolLoopAsks {
t.Run(x.name, func(t *testing.T) {
v := &countingVendor{}
gw := toolLoopOn(t, v)
got := askAgent(t, gw+x.path, toolTurns(x.from, 200, pollJob, x.stream))
if strings.Contains(got, "magpie stopped") || v.asked.Load() != 1 {
t.Fatalf("a poll whose answer moves was stopped (vendor asked %d):\n%s", v.asked.Load(), got)
}
// the loop, magpie's notice and the user's word after it
body := toolTurns(x.from, toolLoopRepeats, codexRead, x.stream, notice[x.from]...)
got = askAgent(t, gw+x.path, body)
if strings.Contains(got, "magpie stopped this turn before") || v.asked.Load() != 2 {
t.Fatalf("the user's word after the notice was stopped (vendor asked %d):\n%s", v.asked.Load(), got)
}
})
}
}
// What tells one exchange from another: the call's name and arguments
// (whatever their keys' order), its result less what Codex writes of the
// run, and whether it failed; never the call's id.
func TestToolLoopSums(t *testing.T) {
call := func(id, name, args string) Part {
return Part{Kind: ToolCall, ID: id, Name: name, Args: json.RawMessage(args)}
}
result := func(id, text string) Part { return Part{Kind: ToolResult, CallID: id, Text: text} }
sum := func(c, r Part) uint64 {
e, ok := exchangeOf([]Part{c}, []Part{r})
if !ok {
t.Fatal("no exchange")
}
return e.sum
}
base := sum(call("a", "read", `{"path":"x","limit":2}`), result("a", "Wall time: 0.0246 seconds\nOutput:\nfn x()"))
same := []uint64{
sum(call("b", "read", `{"limit":2, "path":"x"}`), result("b", "Wall time: 1.5 seconds\nOutput:\nfn x()")),
}
differ := []uint64{
sum(call("c", "read", `{"path":"y","limit":2}`), result("c", "Wall time: 0.0246 seconds\nOutput:\nfn x()")),
sum(call("d", "grep", `{"path":"x","limit":2}`), result("d", "Wall time: 0.0246 seconds\nOutput:\nfn x()")),
sum(call("e", "read", `{"path":"x","limit":2}`), result("e", "Wall time: 0.0246 seconds\nOutput:\nfn y()")),
sum(call("f", "read", `{"path":"x","limit":2}`), Part{Kind: ToolResult, CallID: "f", Text: "Wall time: 0.0246 seconds\nOutput:\nfn x()", IsError: true}),
}
for i, s := range same {
if s != base {
t.Errorf("same exchange %d summed apart", i)
}
}
for i, s := range differ {
if s == base {
t.Errorf("different exchange %d summed the same", i)
}
}
// a turn with no call, or no result, is no exchange
if _, ok := exchangeOf([]Part{{Kind: Text, Text: "done"}}, []Part{result("a", "x")}); ok {
t.Error("a turn with no call is an exchange")
}
if _, ok := exchangeOf([]Part{call("a", "read", `{}`)}, []Part{{Kind: Text, Text: "stop"}}); ok {
t.Error("a turn with no result is an exchange")
}
}
// The guard reads every agent turn with results enough: a long Codex
// conversation, ~1.5MB of 400 reads, costs it one parse.
func BenchmarkToolLoopCheck(b *testing.B) {
big := strings.Repeat("let x = 1;\n", 300)
body := []byte(toolTurns(provider.Responses, 400, func(i int) (string, string) {
return fmt.Sprintf(`{"cmd":"sed -n %d,200p src/f.rs"}`, i), big
}, true))
b.SetBytes(int64(len(body)))
for b.Loop() {
if !mayLoop(provider.Responses, body) {
b.Fatal("no results")
}
req, err := parse(provider.Responses, tailOf(provider.Responses, body))
if err != nil {
b.Fatal(err)
}
if _, ok := toolLoopOf(req.Messages); ok {
b.Fatal("a loop")
}
}
}