Files
magpie/internal/gateway/plugin_parity_test.go
T
yetone 3dc25a6168 tests: a plugin fake's vendor counts only its own test's requests (#3357)
Run 39913278700 at 65e80405b (ubuntu, Race): TestClinePluginPinsDeepSeekAndGLM
"the plugin sent 7 requests" for 6 asks, in 0.33s. #3347 was the same
class: TestPluginToldWhereTheAgentWorks got 2 for 1, in 0.66s.

Cause, as far as it is known. The extra request did not come from the
test's own route:
- not a gateway retry: retryPause is 1s, so a retried ask can't finish
  in 0.33s or 0.66s. #3347's "a first try failed with a 5xx and was
  retried" doesn't fit either run's time;
- not the plugin host: the gateway reaches the host over stdio JSON-RPC
  (no HTTP retry), and host.js fetchAs calls the loader's fetch once;
- a never-reset log of every request the cline test's vendor got showed
  exactly 12 (6 asks x 2 runs), all POST /v1/chat/completions from
  magpie/dev, with nothing in the background.
So the seventh came from outside the test. The likely sender is a late
request from another test, in this shard or another of race-shards.sh's
four processes, reaching a port the kernel handed to this test's
httptest server (the class d0ccbbebc met with a freed port). Which test
sent it is still unknown.

Fix the class: testenv.FakeVendor(t, h) serves a fake plugin's vendor
at $FAKE_BASE and sets $FAKE_RUN to a nonce made for the test. The fake,
renew and renewrace plugins send it as X-Fake-Run. A request without it
gets 421 and is logged with its method, URI, remote address, User-Agent,
Authorization and size, so the next one on CI names its sender. Every
gateway and plugin test that served the fake's vendor with
httptest.NewServer plus FAKE_BASE now uses it (10 gateway, 5 plugin
files). The cline test now counts against the asks' recorded tries, as
65e80405b did for the workdir test: it fails on a real duplicate and
logs each retry's status. No exactly-once guarantee was loosened.

Reproduction by injection, at be002aca0:
- a request to FAKE_BASE from outside the route, with the filter off:
  "the plugin sent 7 requests for 6 asks tried 6 times" (the CI shape);
  with it on, the test passes and logs the 421 line;
- the fake plugin fetching twice for glm-5.3 (a real duplicate) still
  fails: "sent 8 ... tried 6". Both breaks were restored.

Ran at be002aca0 (macOS, -tags nogui):
- gofmt -l clean; go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows ok;
- internal/plugin -race -count=20 ok (157.5s);
- the edited gateway files' tests -race -count=20 ok (93.1s);
Rebased on c8c6e7e23 (it brings TestPluginThinkingOff, on besideFake),
and ran there: gofmt -l clean; vet of the three packages for darwin,
linux nogui and windows ok; TestPluginThinkingOff, the cline and the
workdir tests -race -count=20 ok (18.3s); internal/gateway (363.6s),
internal/plugin (83.9s) and internal/testenv -timeout 45m ok, with no
421 line logged;
- a Linux container run of gateway.race in four shards like CI's,
  -test.v: ok, and no stray was seen.

Not tried: the stray was never caught in the act, here or in the
container, so the sender is a hypothesis. The count=20 run over all 142
besideFake tests hit 45m in TestPluginStreamLargeReplies (sizing, no
FAIL) and was narrowed to the edited files. No product code changed, so
the full ./... suite was not run.
2026-10-23 16:57:33 +08:00

196 lines
6.9 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
)
// movedFake is the fake plugin signed in as the built-in id it was moved
// onto, its requests going to up.
func movedFake(t *testing.T, id string, up http.Handler) {
t.Helper()
bun := testenv.Bun(t)
fresh(t)
t.Setenv("MAGPIE_BUN", bun)
t.Setenv("FAKE_ID", id)
t.Cleanup(plugin.Settle)
testenv.FakeVendor(t, up)
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{id: map[string]any{"state": provider.MovePlugin}})
if err := os.WriteFile(filepath.Join(dir, "migrations.json"), b, 0o600); err != nil {
t.Fatal(err)
}
if !provider.Moved(id) {
t.Fatalf("%s isn't marked moved", id)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := plugin.Providers(ctx); err != nil {
t.Fatal(err)
}
if _, err := plugin.APIKey(ctx, id, 0, nil, "k1", plugin.NewAccount); err != nil {
t.Fatal(err)
}
if p, err := provider.Find(id); err != nil || !p.IsPlugin() {
t.Fatalf("Find(%s) = %+v, %v", id, p, err)
}
}
// Factory moved onto its plugin counts a prompt's tokens as the built-in
// did, by estimate: the vendor isn't asked.
func TestMovedCountTokensEstimated(t *testing.T) {
var mu sync.Mutex
var asked []string
movedFake(t, "factory", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
asked = append(asked, r.URL.Path)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"input_tokens":999}`))
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages/count_tokens", strings.NewReader(`{"model":"factory/fake-claude","messages":[{"role":"user","content":"hello there"}]}`))
New().Handler().ServeHTTP(rec, req)
var got struct {
InputTokens int `json:"input_tokens"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); rec.Code != 200 || err != nil || got.InputTokens == 0 {
t.Fatalf("count_tokens: %d %s", rec.Code, rec.Body)
}
mu.Lock()
defer mu.Unlock()
if len(asked) > 0 || got.InputTokens == 999 {
t.Fatalf("the vendor was asked to count: %v, %d", asked, got.InputTokens)
}
}
// thoughtChat is a fast request with an assistant turn that reasoned, and
// chatBody the chat request built of it for host.
var thoughtChat = &Request{Fast: true, Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Thinking, Text: "pondered"}, {Kind: Text, Text: "hello"}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "again"}}},
}}
func chatBody(t *testing.T, host string) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(buildChat(thoughtChat, "m", host, false), &m); err != nil {
t.Fatal(err)
}
return m
}
// Cursor moved onto its plugin is told fast mode as the built-in told
// Cursor: its plugin reads the chat request's service_tier. No other
// chat upstream is told it.
func TestCursorPluginFast(t *testing.T) {
if m := chatBody(t, "cursor"); m["service_tier"] != "priority" {
t.Errorf("Cursor's plugin wasn't told fast: %v", m["service_tier"])
}
for _, host := range []string{"api.openai.com", "openrouter.ai", "zed", "api.deepseek.com", provider.CommandCodePlanID} {
if m := chatBody(t, host); m["service_tier"] != nil {
t.Errorf("%s was told a service tier", host)
}
}
}
// A Command Code Go conversation moved onto its plugin keeps its
// reasoning, as the built-in replayed it to /alpha/generate: its plugin
// reads reasoning_content. DeepSeek still gets it, others don't.
func TestCommandCodePluginReasoning(t *testing.T) {
reasoning := func(host string) any {
return chatBody(t, host)["messages"].([]any)[1].(map[string]any)["reasoning_content"]
}
for _, host := range []string{provider.CommandCodePlanID, "api.deepseek.com"} {
if got := reasoning(host); got != "pondered" {
t.Errorf("%s got reasoning %v", host, got)
}
}
for _, host := range []string{"api.openai.com", "cursor", "zed"} {
if got := reasoning(host); got != nil {
t.Errorf("%s got reasoning_content %v", host, got)
}
}
}
// A moved provider's account is told in the trace as its provider's, so
// its plan reads as the built-in's did, not as a plugin's.
func TestTraceNamesMovedAccount(t *testing.T) {
p := provider.Provider{ID: "grok", Name: "Grok", Account: &provider.Account{Agent: "plugin", User: "me@example.com", Plan: "SuperGrok Heavy"}}
w := weighed(candidate{p: p, rest: "grok", model: "grok-4"}, p, weighing{}, false, "")
if w.Kind != "account" || w.Agent != "grok" || w.Plan != "SuperGrok Heavy" {
t.Fatalf("weighed = %+v, want grok's account", w)
}
}
// A failed tool result reaches the plugins of Devin and Qoder as their
// built-ins sent it, "Error: " first, and Cursor's as is_error, which its
// plugin reads; no other chat upstream is told either.
func TestPluginToolFailureSaid(t *testing.T) {
failed := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "go"}}},
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "c1", Name: "Bash", Args: json.RawMessage(`{}`)}}},
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "c1", Text: "exit status 1", IsError: true}}},
}}
tool := func(host string) map[string]any {
var m struct{ Messages []map[string]any }
if err := json.Unmarshal(buildChat(failed, "m", host, false), &m); err != nil {
t.Fatal(err)
}
for _, msg := range m.Messages {
if msg["role"] == "tool" {
return msg
}
}
t.Fatalf("%s: no tool message in %v", host, m.Messages)
return nil
}
for _, host := range []string{"devin", "qoder", "qoder-cn"} {
if got := tool(host); got["content"] != "Error: exit status 1" || got["is_error"] != nil {
t.Errorf("%s: %v", host, got)
}
}
if got := tool("cursor"); got["content"] != "exit status 1" || got["is_error"] != true {
t.Errorf("cursor: %v", got)
}
for _, host := range []string{"api.openai.com", "api.deepseek.com", "zed", provider.CommandCodePlanID} {
if got := tool(host); got["content"] != "exit status 1" || got["is_error"] != nil {
t.Errorf("%s: %v", host, got)
}
}
}
// A moved Command Code account's chat is built for its plugin, not for the
// built-in's API host it shows, so a Go conversation keeps its reasoning
// (chatReplaysReasoning) as one added on the plugin does.
func TestMovedBuildHostIsPlugin(t *testing.T) {
movedFake(t, provider.CommandCodePlanID, http.NotFoundHandler())
p, err := provider.Find(provider.CommandCodePlanID)
if err != nil {
t.Fatal(err)
}
if got := buildHost(*p); got != provider.CommandCodePlanID {
t.Fatalf("buildHost = %q, Host = %q", got, p.Host())
}
}