Files
magpie/internal/gateway/claude_rss_test.go
T
yetone a093e9c3a5 claude: a Claude Code run holding over its memory budget is let go after its turn, its session resumed (#3256)
claudeRoom bounded how many Claude Code processes run, not how large
each one is. A run is kept for its conversation's next turn, turn after
turn, and on a service never restarted one grew for days: a
node-MainThread in magpie.service reached 8 GiB RSS on a 31 GiB host and
the OOM killer took the machine down (#3256).

Now each time a run's reply ends, its process tree's resident memory is
read (proc.Tree.RSS: /proc VmRSS on Linux, ps on macOS, the working sets
of its job's processes on Windows, so an npm claude.cmd's node counts)
and logged with its pid. Over the budget (an eighth of memLimit on
Linux, of the computer's memory elsewhere, 1 GiB at least, 4 GiB if
unknown), a whole turn's run is not kept idle: its session is shelved
and the next turn resumes it in a new Claude Code with --resume, told
only the new messages. A run parked on tool calls is let go past 1.5x
the budget (no session to shelve there; its results start a new run).
Each Claude Code also logs pid and model at start, and run time, how it
ended and peak RSS (ru_maxrss) at its end, so an OOM pid can be found in
magpie's log. Budget on the reporter's 31 GiB host: 3.9 GiB.

Run (worktree at 99de8e1ad + this change, macOS arm64):
- go test -timeout 45m ./internal/gateway -run
  'Claude|Subscription|Room|Park|Idle|Resume' -count=1: ok (60.5s).
- go test ./internal/proc -count=1: every test ok except
  TestNoCommandBypassesProc, red on origin/main since 75e78a5a0
  (internal/tui/keep.go, filed as #3567, not this change).
- New tests: TestClaudeOversizedRunIsLetGoAndResumes (injected RSS over
  budget: the run ends, the next turn runs --resume s<pid> and is not
  told a1 again), TestClaudeRunWithinBudgetIsKept,
  TestClaudeOversizedParkedRunIsLetGo, TestClaudeRunBudgetScalesWithMemory
  (31 GiB MemTotal -> an eighth; 2 GiB -> the 1 GiB floor), TestTreeRSS
  (a real sleep's RSS read; none once waited for).
- Broken by hand: with both checks turned off, the oversized idle and
  parked tests go red ("the oversized run to end", "a run over its
  budget was kept waiting on its tool calls").
- Real Claude Code 2.1.310 in a sandbox HOME and CLAUDE_CONFIG_DIR,
  stream-json like the bridge, against DeepSeek's Anthropic endpoint
  (deepseek-chat, real key, synthetic 40KB turns): RSS after turns
  1/10/20/30 = 192/244/223/233 MiB, peak 245 MiB over 30 turns and
  ~1.2 MB of conversation. oversized() on that real process with the
  budget 1 MiB under its RSS said over; with the real budget on this
  64 GiB Mac (8192 MiB) it said keep.
- gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/proc ./internal/gateway clean.

Not tried: a real Claude subscription run through the bridge on Linux
until it crosses the budget (the retire path is shown with injected RSS
on the fake Claude Code, and the RSS read on a real one); the Windows
RSS reader and job listing on the Windows box (vet only); a Linux run of
the /proc reader (macOS reads through ps); the full ./internal/gateway
package.
2026-10-25 17:41:41 +08:00

135 lines
3.8 KiB
Go

package gateway
import (
"context"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/proc"
)
// giveRSS has every Claude Code run read as holding rss (over the budget
// when over), what its real process holds left out.
func giveRSS(t *testing.T, over bool, share int64) {
t.Helper()
old := claudeRunRSS
claudeRunRSS = func(*proc.Tree) (int64, bool) {
budget, _ := claudeRunBudget()
budget = budget * share / 2
if over {
return budget + 1, true
}
return budget, true
}
t.Cleanup(func() { claudeRunRSS = old })
}
// A run that holds more than claudeRunBudget once its turn is whole is let
// go, not kept for the next turn: its session is shelved, and that turn
// resumes it in a new Claude Code, told only the new message (#3256: one
// kept for days reached 8 GiB and took the machine down).
func TestClaudeOversizedRunIsLetGoAndResumes(t *testing.T) {
h := newScriptHarness(t, "ok", "")
freshRoom(t, 4)
giveRSS(t, true, 2)
h.ask("rules A", "a1")
var pidA string
for pid := range h.runs() {
pidA = pid
}
eventually(t, "the oversized run to end", func() bool {
h.s.subscription.mu.Lock()
defer h.s.subscription.mu.Unlock()
return len(h.s.subscription.runs) == 0 && len(h.s.subscription.idle) == 0
})
h.ask("rules A", "a1", "a2")
runs := h.runs()
if len(runs) != 2 {
t.Fatalf("runs: %v", runs)
}
resumed := false
for pid, l := range runs {
if pid != pidA && strings.Contains(l, "--resume s"+pidA) {
resumed = true
for _, line := range strings.Split(l, "\n") {
if strings.HasPrefix(line, "told ") && strings.Contains(line, "a1") {
t.Fatalf("the resumed run was told the conversation again:\n%s", l)
}
}
}
}
if !resumed {
t.Fatalf("the next turn didn't resume the oversized run's session s%s: %v", pidA, runs)
}
}
// One within the budget is kept, and its next turn goes to the same
// Claude Code.
func TestClaudeRunWithinBudgetIsKept(t *testing.T) {
h := newScriptHarness(t, "ok", "")
freshRoom(t, 4)
giveRSS(t, false, 2)
h.ask("rules A", "a1")
h.ask("rules A", "a1", "a2")
if runs := h.runs(); len(runs) != 1 {
t.Fatalf("a run within its budget wasn't kept: %v", runs)
}
}
// A run waiting on its caller's tool results is let go past half as much
// again as the budget, and kept up to it.
func TestClaudeOversizedParkedRunIsLetGo(t *testing.T) {
fakeClaudeCalling(t)
s := New()
t.Cleanup(s.subscription.abortAll)
giveRSS(t, false, 3)
kept := askForCall(t, s, context.Background(), "read a file")
giveRSS(t, true, 3)
over := askForCall(t, s, context.Background(), "read another file")
if t.Failed() {
return
}
if n := leftover([]int{over}, 3*time.Second); n != 0 {
t.Fatal("a run over its budget was kept waiting on its tool calls")
}
if !alive(kept) {
t.Fatal("a run within its budget was let go")
}
}
// The budget is an eighth of the memory magpie may use, a floor under it.
func TestClaudeRunBudgetScalesWithMemory(t *testing.T) {
root := t.TempDir()
putMeminfo(t, root, "MemTotal: 32505856 kB\n")
oldGOOS, oldRoot := memGOOS, memRoot
memGOOS, memRoot = "linux", root
t.Cleanup(func() { memGOOS, memRoot = oldGOOS, oldRoot })
budget := func() int64 {
runBudget.Once = sync.Once{}
n, _ := claudeRunBudget()
return n
}
t.Cleanup(func() { runBudget.Once = sync.Once{} })
if n := budget(); n != 32505856<<10/8 {
t.Fatalf("31 GiB holds a run of %d MiB", n>>20)
}
putMeminfo(t, root, "MemTotal: 2097152 kB\n")
if n := budget(); n != claudeRunFloor {
t.Fatalf("2 GiB holds a run of %d MiB, not the floor", n>>20)
}
}
func putMeminfo(t *testing.T, root, text string) {
t.Helper()
if err := os.MkdirAll(filepath.Join(root, "proc"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "proc", "meminfo"), []byte(text), 0o644); err != nil {
t.Fatal(err)
}
}