claude: a run's pid is read once its tree is set, not while cmd.Start writes it

TestClaudeRunsNamesEachProcess was red under -race on ubuntu CI at
6104e88aa (run 40698575099): /v1/magpie/claude-runs (7f827b3b0) listed a
run whose launch was still in cmd.Start, and pid() read cmd.Process
while Start wrote it. A real race, not only the test's: the Claude runs
list can be asked for at any time. pid() now reads tree under mu first;
tree is set under mu after Start returns, so cmd.Process is read after
it is written. No pid() caller holds r.mu (claude_rss.go oversized and
letGoOversized, claude_runs.go, the park path, launch's own logs).

Run on mote (M5 Pro):
- old code, -race -count=30: no race (the window is narrow)
- old code with a 50ms sleep injected at the top of launch, -race
  -count=5: DATA RACE, FAIL
- this change with the same sleep, -count=5: ok
- without the sleep: go test -race -run Claude ./internal/gateway ok
  (84s); go test -run Claude -count=2 ok (79s)
- go vet ./internal/gateway for darwin, linux, windows: ok
Not run: the full suite (one function changed, every Claude test above).
This commit is contained in:
yetone
2026-10-28 22:39:56 +08:00
parent 174250b277
commit 983fff23d0
+7 -2
View File
@@ -83,9 +83,14 @@ func (r *subscriptionRun) oversized(share int64) (string, bool) {
return fmt.Sprintf("its Claude Code held %d MiB, over the %d MiB a run may hold to be kept (%s)", rss>>20, budget>>20, why), true
}
// pid is the run's Claude Code process id, 0 before it starts.
// pid is the run's Claude Code process id, 0 before it starts. It is
// read once tree is set under mu: cmd.Process is written by cmd.Start,
// which a list of the runs may be reading through.
func (r *subscriptionRun) pid() int {
if r.cmd == nil || r.cmd.Process == nil {
r.mu.Lock()
t := r.tree
r.mu.Unlock()
if t == nil || r.cmd == nil || r.cmd.Process == nil {
return 0
}
return r.cmd.Process.Pid