Files
magpie/internal/cli/claude_code_cli_test.go
T
yetone 20c0688316 gateway: Claude Code processes are held to what the machine's memory holds; a full room is a 503 the next provider takes (#2956)
Cause: nothing bounded how many Claude Code processes magpie runs for
Claude subscriptions. Busy runs had no limit, idle ones were capped at 6
and parked ones at 16 per bridge, and one-off tests, warm-ups and /usage
reads were counted nowhere. The reporter's 512 MiB systemd service had 2
busy runs and 14 starting at once when the memory cgroup's OOM killer
ended them.

Measured (Docker arm64, real Claude Code 2.1.303):
- one idle run holds about 205 MiB RSS, 86-112 MiB of it anonymous;
- six runs under a 512 MiB memcg gave oom_kill 2 and a peak of 512 MiB.

Fix: claudeRoom (claude_room.go). Every Claude Code takes a place before
it starts and frees it when its process exits. That covers startRun and
runClaudeTree (tests, warm-up, /usage).

How many may run:
- the user's claudeRunsMost (`magpie claude-code runs N|auto`). It is
  machine-local (KeepOwn), and the Settings page's save keeps it.
- otherwise, on Linux, (limit - 256 MiB) / 128 MiB, at least 1. The limit
  is the least of MemTotal, cgroup v2 memory.max and memory.high up the
  tree, and cgroup v1 memory.limit_in_bytes. The reporter's 512 MiB
  cgroup gives 2, and 1 GiB gives 6.
- otherwise no bound: macOS, Windows, or limits that can't be read.

A full room first lets go of the oldest idle run. Its session is
shelved, so the next turn resumes it. Next it lets go of a run parked
past parkLongest. Busy runs are never let go. Otherwise it waits up to
2 minutes, then answers 503 with the reason and the command.

Routing treats that 503 as protected. No Claude account is rested or
asked next, since each would wait for the same room, and another
provider in the group answers.

Tests (each run red by hand on the broken code):
- TestClaudeRunsHeldToTheRoom: 6 conversations at room 2. With take
  forced to always admit: "6 Claude Code processes were alive at once,
  2 may be". Fixed: at most 2, and all 6 answer 200.
- TestClaudeRoomLetsAnIdleRunGoAndItResumes, TestClaudeRoomFullIs503 and
  TestClaudeOneOffsTakeRoom went red with take forced open.
- TestClaudeNoRoomPassesOnAndRestsNobody went red with the routing
  exemption off: both Claude accounts were tried and rested.
- TestClaudeMemRunsFromTheCgroup uses the reporter's literal meminfo,
  cgroup path and memory.max.
- TestClaudeCodeRunsSetsTheUsersOwn went red with validation loosened.
- TestClaudeRunsMostIsMachineLocal went red without the KeepOwn line.
- TestSettingsSaveKeepsWhatItDoesNotSend (internal/gui guard) caught a
  Settings page save clearing the value. It is kept now.

Run at this tree (macOS, go1.26.8):
- go test -timeout 45m -count=1 ./... with pipefail, under a load
  average of 650-800 from other sessions: 61 packages ok. Three were not:
  - internal/agent and internal/gateway hit the 45m timeout mid-test.
    The stacks show no hang. Re-run at -timeout 120m: agent ok (2779s).
  - In gateway, TestClaudeAccountsSpentFallBackToCodex hit its 30s wall
    bound. No room wait was logged before it, and it passed 5 of 5
    alone.
  - In the same run TestClaudeRoomLetsAnIdleRunGoAndItResumes was red
    because of its own check: a random request id in the fake's log
    spelled "a1". It now reads only the fake's "told" lines. Flipped to
    "a2", it goes red.
  - internal/gui: TestPanelJoinsFullScreenSpaces (a macOS window test)
    passes alone. TestSetAnswersWhileDevinAndProvidersHang has a 10s
    bound, and at the base commit under the same load it failed 2 of 3.
- The touched packages again, -count=1: settings, cli and gui ok.
  gateway: the room tests and TestClaudeAccountsSpentFallBackToCodex
  ok at -count=5.
- gofmt -l: clean.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.

Not tried:
- the Docker 512 MiB reproduction re-run with this build against real
  Claude Code. The fix is shown with fake runs only.
- a real cgroup v1 host.
- the site's docker docs (en/zh/ja) don't mention `claude-code runs` yet.
2026-10-20 20:23:57 +08:00

149 lines
4.6 KiB
Go

package cli
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/claudecode"
"github.com/yetone/magpie/internal/libc"
"github.com/yetone/magpie/internal/settings"
)
// claudeCodeOut runs `magpie claude-code args…` and gives what it printed.
func claudeCodeOut(t *testing.T, args ...string) (string, error) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
var out strings.Builder
done := make(chan struct{})
go func() {
b, _ := io.ReadAll(r)
out.Write(b)
close(done)
}()
err = claudeCodeCmd(args)
w.Close()
os.Stdout = old
<-done
r.Close()
return out.String(), err
}
// `magpie claude-code install --yes` on a machine with no Claude Code (a
// container, Jorben on Discord) downloads the release's build, says from
// where and to where, and the subscription then runs it.
func TestClaudeCodeInstallDownloadsTheRelease(t *testing.T) {
platform, err := claudecode.Platform(runtime.GOOS, runtime.GOARCH, false)
if err != nil {
t.Skip(err)
}
if libc.Musl() {
t.Skip("a musl Linux asks for the -musl build")
}
const body = "#!/bin/sh\necho '2.1.296 (Claude Code)'\n"
sum := sha256.Sum256([]byte(body))
exe := map[bool]string{true: "claude.exe", false: "claude"}[runtime.GOOS == "windows"]
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/latest":
fmt.Fprint(w, "2.1.296")
case "/2.1.296/manifest.json":
fmt.Fprintf(w, `{"version":"2.1.296","manifestSignatureEnforcement":"flag","platforms":{%q:{"binary":%q,"checksum":%q,"size":%d}}}`,
platform, exe, hex.EncodeToString(sum[:]), len(body))
case "/2.1.296/" + platform + "/" + exe:
fmt.Fprint(w, body)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
oldBase, oldOwn := claudecode.Base, claudeCode.own
claudecode.Base, claudeCode.own = srv.URL, func() string { return "" }
t.Cleanup(func() { claudecode.Base, claudeCode.own = oldBase, oldOwn; _ = claudecode.Remove() })
out, err := claudeCodeOut(t)
if err != nil || !strings.Contains(out, "magpie claude-code install") {
t.Fatalf("status before: %q, %v", out, err)
}
out, err = claudeCodeOut(t, "install", "--yes")
if err != nil {
t.Fatalf("install: %v\n%s", err, out)
}
for _, want := range []string{"2.1.296", srv.URL + "/2.1.296/" + platform + "/" + exe, claudecode.Root(), "SHA-256", "downloaded and checked"} {
if !strings.Contains(out, want) {
t.Errorf("install didn't say %q:\n%s", want, out)
}
}
if p, v := claudecode.Downloaded(); v != "2.1.296" || p == "" {
t.Fatalf("Downloaded() = %q, %q", p, v)
}
if out, _ := claudeCodeOut(t, "install", "--yes"); !strings.Contains(out, "downloaded already") {
t.Errorf("a second install: %q", out)
}
if out, _ := claudeCodeOut(t); !strings.Contains(out, "downloaded by magpie") {
t.Errorf("status after: %q", out)
}
if _, err := claudeCodeOut(t, "remove"); err != nil {
t.Fatal(err)
}
if p, _ := claudecode.Downloaded(); p != "" {
t.Errorf("remove left %s", p)
}
}
// `magpie claude-code runs N` is the user's own bound on Claude Code
// processes (#2956), which the gateway's 503 names; auto gives it back to
// the machine's memory, and a value that isn't a count is refused and
// writes nothing.
func TestClaudeCodeRunsSetsTheUsersOwn(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
out, err := claudeCodeOut(t, "runs", "3")
if err != nil {
t.Fatal(err)
}
if got := settings.Load().ClaudeRunsMost; got != 3 {
t.Fatalf("claudeRunsMost is %d after `runs 3`", got)
}
if !strings.Contains(out, "3 Claude Code processes may run at once") || !strings.Contains(out, "your setting") {
t.Fatalf("runs 3 said:\n%s", out)
}
for _, bad := range []string{"0", "-2", "lots", "--yes"} {
if _, err := claudeCodeOut(t, "runs", bad); err == nil {
t.Fatalf("runs %s was taken", bad)
}
if got := settings.Load().ClaudeRunsMost; got != 3 {
t.Fatalf("runs %s wrote %d", bad, got)
}
}
if _, err := claudeCodeOut(t, "runs", "--help"); err != nil {
t.Fatal(err)
}
if got := settings.Load().ClaudeRunsMost; got != 3 {
t.Fatalf("runs --help wrote %d", got)
}
if _, err := claudeCodeOut(t, "runs", "auto"); err != nil {
t.Fatal(err)
}
if got := settings.Load().ClaudeRunsMost; got != 0 {
t.Fatalf("runs auto left %d", got)
}
out, err = claudeCodeOut(t, "runs")
if err != nil || strings.Contains(out, "your setting") {
t.Fatalf("runs after auto said (%v):\n%s", err, out)
}
}