Files
magpie/internal/gateway/textcalls_close_test.go
T
yetone d1173c8c16 gateway: DeepSeek's calls close left in a reply's text (</||DSML|| calls>) is dropped, after a call the upstream made too
喜欢一个人 on Discord (v0.1.1299, macOS arm64, a Responses client
translated to Chat, deepseek-v4.1-flash through a relay, 232312 in /
645 out, stop "stop"): the client got the text "\n</||DSML|| calls>"
and the agent loop ended mid-turn. Their history has ||DSML|| calls>
712 times against 133 <||DSML||invoke.

Reproduced on origin/main 9b0f48612 (v0.1.1316+1) with those bytes. A
whole block of invokes closed with </||DSML|| calls> was already the
call on every route (the junk regex takes any DSML tag; 7ea8aeaba and
d0c587aee). What leaked was the close with no block before it in the
text:

- after a call the upstream made itself (a relay that made the calls of
  DeepSeek's invokes and left the wrapper's close as text):
  textCallSee and textCallTidy stopped reading text once a native call
  came, and wholeTextCalls left such a message alone, so the close went
  to the client on every route, the Responses translation the reporter
  uses included (a final_answer message after the function_call);
- with no call: textCallAt found only DSML opens (dsmlMark closing
  false), so a lone close was never held and went out as text.

Now textCallAt finds a DSML close as it finds an open, and held text
that is tags and nothing else goes, with the spaces before it after a
native call (spaceBack, settled). No call is read out of a native
reply's text; text that isn't only tags goes on as it came (prose about
</|DSML|invoke> keeps it).

Not rewritten by magpie: nothing in magpie turns tool_calls into
" calls". The only Go source with | is textcalls.go; redact's Writer
restores only {{KIND_xxxxxxxx}} placeholders, and #3143 (88119d4f6,
10-21) changed masking of the request, not reply text. The reporter's
earliest is 10-13, and OKURBITO's capture on #2623 (10-17, workbuddy
deepseek-flash, observedPipes) already has <||DSML|| calls> as the
model wrote it: DeepSeek's own spelling.

Tests (textcalls_close_test.go), from the reporter's bytes:
- TestDSMLCloseLeftAfterCalls: a native call, then "\n</||DSML|| calls>"
  cut at every valid byte, with no opener, <||DSML|| calls> or
  <||DSML||tool_calls> before the call; Chat stream, Chat whole,
  Responses stream and whole, Anthropic stream and whole.
- TestDSMLCloseAlone: "Done.\n</||DSML|| calls>" with no call, every cut,
  Chat stream and whole, Responses both; prose with a close kept.
- TestDSMLBlockClosedWithCalls: the full invoke/parameter block closed
  with " calls>", opened three ways, every cut on Chat, every 5th on
  Responses stream and whole. Green on the old code too (a guard).

Red on the old code: TestDSMLCloseLeftAfterCalls and TestDSMLCloseAlone
FAIL with origin/main's textcalls.go. Broken by hand, each red alone:
textCallSee.settle without settled (responses stream=true keeps the
close), wholeTextCalls' native branch off (chat whole keeps it),
textCallAt back to opens only (chat stream and alone keep it).

Docs: gateway-routing.md's text-calls entry.

Run at the tree pushed (go test -timeout 45m ./... in a sandbox HOME at
308f693df, tree cfd91bbea, on origin/main c358e7660; only messages
changed since): 68 packages ok, exit 0. The one red at an earlier run
(770c5fc48), TestGeminiCompatRelayEndedShort, is answered in the finish
commit. gofmt -l clean; go vet ./internal/gateway for darwin, linux
-tags nogui and windows clean.

Not tried: a real relay or the reporter's client; the bytes are the
reporter's, from their usage row and client history. A close spelled
another way than DeepSeek's DSML marks is not covered.

Reported by 喜欢一个人 on Discord.
2026-10-22 04:54:04 +08:00

161 lines
8.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"net/http/httptest"
"strings"
"testing"
"unicode/utf8"
"github.com/yetone/magpie/internal/provider"
)
// 喜欢一个人 on Discord (v0.1.1299, a Responses client, deepseek-v4.1-flash
// through a relay): the client got the text "\n</||DSML|| calls>",
// DeepSeek's calls wrapper closed as it writes it (no tool_, a space after
// the pipes), and nothing went on. These are the reporter's bytes: the
// close as it came, and the invokes and parameters with two pipes as their
// client's history has them.
const reportedClose = "\n</||DSML|| calls>"
const reportedBlock = "<||DSML||tool_calls>\n<||DSML||invoke name=\"exec_command\">\n<||DSML||parameter name=\"cmd\" string=\"true\">ls -la</||DSML||parameter>\n</||DSML||invoke>" + reportedClose
const execChatTool = `"tools":[{"type":"function","function":{"name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}}]`
const execResponsesTool = `"tools":[{"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}]`
// nativeExec is a chunk in which the upstream made the call itself.
const nativeExec = `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"ls -la\"}"}}]},"finish_reason":null}]}`
// cuts are s sent as two chunks at every place a chunk's JSON can cut it.
func cuts(s string) [][]string {
var out [][]string
for i := 1; i < len(s); i++ {
if utf8.ValidString(s[:i]) {
out = append(out, []string{chunkOf(s[:i]), chunkOf(s[i:])})
}
}
return out
}
// A relay that made the call of DeepSeek's invokes itself left the
// wrapper's close in the text after it: the close goes, with the line
// break before it, on every route and wherever the stream cuts it.
func TestDSMLCloseLeftAfterCalls(t *testing.T) {
chat := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],` + execChatTool + `}`
for _, before := range []string{"", "<||DSML|| calls>\n", "<||DSML||tool_calls>"} {
for _, parts := range cuts(reportedClose) {
up := []string{nativeExec}
if before != "" {
up = []string{chunkOf(before), nativeExec}
}
text, calls, _, raw := relayedChat(t, chat, append(append(up, parts...), stopChunk)...)
if text != "" || calls["exec_command"] != `{"cmd":"ls -la"}` || strings.Contains(raw, "DSML") {
t.Fatalf("chat, %q before, %q: text %q calls %v\n%s", before, parts, text, calls, raw)
}
}
}
whole := `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"Running it.` + strings.ReplaceAll(reportedClose, "\n", `\n`) + `","tool_calls":[{"id":"call_up","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"ls -la\"}"}}]},"finish_reason":"tool_calls"}]}`
text, wcalls, finish, raw := wholeChat(t, `{"model":"a/m","messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, "application/json", whole)
if strOr(text) != "Running it." || len(wcalls) != 1 || finish != "tool_calls" || strings.Contains(raw, "DSML") {
t.Fatalf("chat whole: text %q calls %+v finish %q\n%s", strOr(text), wcalls, finish, raw)
}
for _, stream := range []string{"true", "false"} {
items, raw := responsesItems(t, `{"model":"a/m","stream":`+stream+`,"input":"go",`+execResponsesTool+`}`,
nativeExec, chunkOf(reportedClose[:6]), chunkOf(reportedClose[6:]), stopChunk)
if len(items) != 1 || items[0]["type"] != "function_call" || items[0]["arguments"] != `{"cmd":"ls -la"}` || strings.Contains(raw, "DSML") {
t.Fatalf("responses stream=%s: %v\n%s", stream, items, raw)
}
}
fresh(t)
a := &scripted{}
scriptedOn(t, "a", provider.Chat, a)
for _, stream := range []string{"true", "false"} {
a.replies = []reply{{200, "text/event-stream", sse(nativeExec, chunkOf(reportedClose), stopChunk, `data: [DONE]`)}}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(
`{"model":"a/m","max_tokens":100,"stream":`+stream+`,"messages":[{"role":"user","content":"go"}],"tools":[{"name":"exec_command","input_schema":{"type":"object"}}]}`)))
body := rec.Body.String()
if rec.Code != 200 || strings.Contains(body, "DSML") || strings.Contains(body, `"type":"text"`) ||
!strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"stop_reason":"tool_use"`) {
t.Fatalf("anthropic stream=%s: %d %s", stream, rec.Code, body)
}
}
}
// The whole block, closed as the reporter's was, is the call on every
// route, streamed at every cut and whole, opened with tool_calls, with
// " calls" or not at all.
func TestDSMLBlockClosedWithCalls(t *testing.T) {
chat := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],` + execChatTool + `}`
for _, block := range []string{
reportedBlock,
strings.Replace(reportedBlock, "tool_calls>", " calls>", 1),
reportedBlock[strings.Index(reportedBlock, "\n")+1:],
} {
s := "Let me look.\n\n" + block
for _, parts := range cuts(s) {
text, calls, finish, raw := relayedChat(t, chat, append(parts, stopChunk)...)
if text != "Let me look.\n\n" || calls["exec_command"] != `{"cmd":"ls -la"}` || finish != "tool_calls" || strings.Contains(raw, "DSML") {
t.Fatalf("chat %q: text %q calls %v finish %q\n%s", parts, text, calls, finish, raw)
}
}
text, wcalls, finish, raw := wholeChat(t, `{"model":"a/m","messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, "application/json", wholeChatUp(s))
if strOr(text) != "Let me look.\n\n" || len(wcalls) != 1 || finish != "tool_calls" || strings.Contains(raw, "DSML") {
t.Fatalf("chat whole: text %q calls %+v finish %q\n%s", strOr(text), wcalls, finish, raw)
}
for _, stream := range []string{"true", "false"} {
for i := 1; i < len(s); i += 5 {
if !utf8.ValidString(s[:i]) {
continue
}
items, raw := responsesItems(t, `{"model":"a/m","stream":`+stream+`,"input":"go",`+execResponsesTool+`}`, chunkOf(s[:i]), chunkOf(s[i:]), stopChunk)
var call map[string]any
for _, it := range items {
if it["type"] == "function_call" {
call = it
}
}
if call == nil || call["arguments"] != `{"cmd":"ls -la"}` || strings.Contains(raw, "DSML") {
t.Fatalf("responses stream=%s cut %d: %v\n%s", stream, i, items, raw)
}
}
}
}
}
// A DSML close with nothing written before it and no call is dropped as
// other tags and nothing else are; text after it keeps it, as written.
func TestDSMLCloseAlone(t *testing.T) {
chat := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],` + execChatTool + `}`
for _, parts := range cuts("Done." + reportedClose) {
text, calls, finish, raw := relayedChat(t, chat, append(parts, stopChunk)...)
if text != "Done.\n" || len(calls) != 0 || finish != "stop" || strings.Contains(raw, "DSML") {
t.Fatalf("%q: text %q calls %v finish %q\n%s", parts, text, calls, finish, raw)
}
}
text, _, finish, raw := wholeChat(t, `{"model":"a/m","messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, "application/json", wholeChatUp("Done."+reportedClose))
if strOr(text) != "Done.\n" || finish != "stop" || strings.Contains(raw, "DSML") {
t.Fatalf("whole: text %q finish %q\n%s", strOr(text), finish, raw)
}
for _, stream := range []string{"true", "false"} {
items, raw := responsesItems(t, `{"model":"a/m","stream":`+stream+`,"input":"go",`+execResponsesTool+`}`, chunkOf("Done."+reportedClose), stopChunk)
if len(items) != 1 || items[0]["type"] != "message" || strings.Contains(raw, "DSML") {
t.Fatalf("responses stream=%s: %v\n%s", stream, items, raw)
}
}
// prose about a close: the text is kept whole
prose := "The close is </|DSML|invoke> and it ends a call."
text2, calls, finish, _ := relayedChat(t, chat, chunkOf(prose), stopChunk)
if text2 != prose || len(calls) != 0 || finish != "stop" {
t.Fatalf("prose: text %q calls %v finish %q", text2, calls, finish)
}
// and after a call the upstream made, too
text2, _, _, _ = relayedChat(t, chat, nativeExec, chunkOf(prose), stopChunk)
if text2 != prose {
t.Fatalf("prose after a call: text %q", text2)
}
}